diff --git a/.gitignore b/.gitignore index b8b69fa2d..c48ce5381 100644 --- a/.gitignore +++ b/.gitignore @@ -34,3 +34,4 @@ trace_data/ /doc/user/public/* .ionide/* /.ignore +/build diff --git a/doc/user/CMakeDeps.cmake b/doc/user/CMakeDeps.cmake index 4ff607481..59a6b66b9 100644 --- a/doc/user/CMakeDeps.cmake +++ b/doc/user/CMakeDeps.cmake @@ -1 +1 @@ -set(sources /spark/doc/user/build.sh;content/_index.md;content/bts_spark/Glossary/_index.md;content/bts_spark/Help/_index.md;content/bts_spark/Help/about_spark.png;content/bts_spark/Help/image39.png;content/bts_spark/Help/image58.png;content/bts_spark/Launcher/_index.md;content/bts_spark/Launcher/image38.png;content/bts_spark/Launcher/image68.png;content/bts_spark/Logging-In-to-the-System/_index.md;content/bts_spark/Logging-In-to-the-System/image3.png;content/bts_spark/Logging-In-to-the-System/image64.png;content/bts_spark/Market/_index.md;content/bts_spark/Market/change_securities.png;content/bts_spark/Market/image11.png;content/bts_spark/Market/image14.png;content/bts_spark/Market/image20.png;content/bts_spark/Market/image21.png;content/bts_spark/Market/image23.png;content/bts_spark/Market/image24.png;content/bts_spark/Market/image34.png;content/bts_spark/Market/image49.png;content/bts_spark/Market/image53.png;content/bts_spark/Market/image66.png;content/bts_spark/Market/image69.png;content/bts_spark/Market/market_view.png;content/bts_spark/Market/settings_icon.png;content/bts_spark/Market/time_and_sales.png;content/bts_spark/My-Windows/_index.md;content/bts_spark/My-Windows/image15.png;content/bts_spark/My-Windows/image16.png;content/bts_spark/My-Windows/image37.png;content/bts_spark/Settings/_index.md;content/bts_spark/Settings/image51.png;content/bts_spark/Settings/image9.png;content/bts_spark/Spreader/_index.md;content/bts_spark/Spreader/image10.png;content/bts_spark/Spreader/image13.png;content/bts_spark/Spreader/image18.png;content/bts_spark/Spreader/image19.png;content/bts_spark/Spreader/image28.png;content/bts_spark/Spreader/image29.png;content/bts_spark/Spreader/image31.png;content/bts_spark/Spreader/image35.png;content/bts_spark/Spreader/image40.png;content/bts_spark/Spreader/image43.png;content/bts_spark/Spreader/image54.png;content/bts_spark/Spreader/image55.png;content/bts_spark/Spreader/image56.png;content/bts_spark/Spreader/image6.png;content/bts_spark/Spreader/image7.png;content/bts_spark/Spreader/image70.png;content/bts_spark/Spreader/image72.png;content/bts_spark/Spreader/image8.png;content/bts_spark/Trading/OrderTypes/index.md;content/bts_spark/Trading/_index.md;content/bts_spark/Trading/algo_studio.png;content/bts_spark/Trading/collapse_all_icon.png;content/bts_spark/Trading/cover_algo_control.png;content/bts_spark/Trading/expand_all_icon.png;content/bts_spark/Trading/image1.png;content/bts_spark/Trading/image17.png;content/bts_spark/Trading/image2.png;content/bts_spark/Trading/image25.png;content/bts_spark/Trading/image27.png;content/bts_spark/Trading/image33.png;content/bts_spark/Trading/image42.png;content/bts_spark/Trading/image44.png;content/bts_spark/Trading/image47.png;content/bts_spark/Trading/image48.png;content/bts_spark/Trading/image5.png;content/bts_spark/Trading/image50.png;content/bts_spark/Trading/image52.png;content/bts_spark/Trading/image57.png;content/bts_spark/Trading/image59.png;content/bts_spark/Trading/image60.png;content/bts_spark/Trading/image61.png;content/bts_spark/Trading/image62.png;content/bts_spark/Trading/image73.png;content/bts_spark/Trading/image74.png;content/bts_spark/Trading/join_algo_control.png;content/bts_spark/Trading/ladder.png;content/bts_spark/Trading/ladder_badges.png;content/bts_spark/Trading/ladder_main_part.png;content/bts_spark/Trading/lean_algo_control.png;content/bts_spark/Trading/mini_orderbook.png;content/bts_spark/Trading/oco_algo_control.png;content/bts_spark/Trading/offset_algo_control.png;content/bts_spark/Trading/pnl_calculation.png;content/bts_spark/Trading/pnl_window.png;content/bts_spark/Trading/recreate_icon.png;content/bts_spark/Trading/settings_icon.png;content/bts_spark/Trading/spark_menu_order_book.png;content/bts_spark/Trading/top_algo_control.png;content/bts_spark/Trading/trigger_algo_control.png;content/bts_spark/_index.md;content/release_notes/_index.md;content/system_requirements/_index.md;static/book.js;static/favicon.ico;static/image.js;templates/index.html;templates/page.html;templates/section.html;templates/shortcodes/back_button.html) \ No newline at end of file +set(sources /home/ppinto/Dropbox/bts/spark/doc/user/build.sh;content/_index.md;content/bts_spark/Glossary/_index.md;content/bts_spark/Help/_index.md;content/bts_spark/Help/about_spark.png;content/bts_spark/Help/image39.png;content/bts_spark/Help/image58.png;content/bts_spark/Launcher/_index.md;content/bts_spark/Launcher/image38.png;content/bts_spark/Launcher/image68.png;content/bts_spark/Logging-In-to-the-System/_index.md;content/bts_spark/Logging-In-to-the-System/image3.png;content/bts_spark/Logging-In-to-the-System/image64.png;content/bts_spark/Market/_index.md;content/bts_spark/Market/change_securities.png;content/bts_spark/Market/image11.png;content/bts_spark/Market/image14.png;content/bts_spark/Market/image20.png;content/bts_spark/Market/image21.png;content/bts_spark/Market/image23.png;content/bts_spark/Market/image24.png;content/bts_spark/Market/image34.png;content/bts_spark/Market/image49.png;content/bts_spark/Market/image53.png;content/bts_spark/Market/image66.png;content/bts_spark/Market/image69.png;content/bts_spark/Market/market_view.png;content/bts_spark/Market/settings_icon.png;content/bts_spark/Market/time_and_sales.png;content/bts_spark/My-Windows/_index.md;content/bts_spark/My-Windows/image15.png;content/bts_spark/My-Windows/image16.png;content/bts_spark/My-Windows/image37.png;content/bts_spark/Settings/_index.md;content/bts_spark/Settings/image51.png;content/bts_spark/Settings/image9.png;content/bts_spark/Spreader/_index.md;content/bts_spark/Spreader/image10.png;content/bts_spark/Spreader/image13.png;content/bts_spark/Spreader/image18.png;content/bts_spark/Spreader/image19.png;content/bts_spark/Spreader/image28.png;content/bts_spark/Spreader/image29.png;content/bts_spark/Spreader/image31.png;content/bts_spark/Spreader/image35.png;content/bts_spark/Spreader/image40.png;content/bts_spark/Spreader/image43.png;content/bts_spark/Spreader/image54.png;content/bts_spark/Spreader/image55.png;content/bts_spark/Spreader/image56.png;content/bts_spark/Spreader/image6.png;content/bts_spark/Spreader/image7.png;content/bts_spark/Spreader/image70.png;content/bts_spark/Spreader/image72.png;content/bts_spark/Spreader/image8.png;content/bts_spark/Trading/OrderTypes/index.md;content/bts_spark/Trading/_index.md;content/bts_spark/Trading/algo_studio.png;content/bts_spark/Trading/collapse_all_icon.png;content/bts_spark/Trading/cover_algo_control.png;content/bts_spark/Trading/expand_all_icon.png;content/bts_spark/Trading/image1.png;content/bts_spark/Trading/image17.png;content/bts_spark/Trading/image2.png;content/bts_spark/Trading/image25.png;content/bts_spark/Trading/image27.png;content/bts_spark/Trading/image33.png;content/bts_spark/Trading/image42.png;content/bts_spark/Trading/image44.png;content/bts_spark/Trading/image47.png;content/bts_spark/Trading/image48.png;content/bts_spark/Trading/image5.png;content/bts_spark/Trading/image50.png;content/bts_spark/Trading/image52.png;content/bts_spark/Trading/image57.png;content/bts_spark/Trading/image59.png;content/bts_spark/Trading/image60.png;content/bts_spark/Trading/image61.png;content/bts_spark/Trading/image62.png;content/bts_spark/Trading/image73.png;content/bts_spark/Trading/image74.png;content/bts_spark/Trading/join_algo_control.png;content/bts_spark/Trading/ladder.png;content/bts_spark/Trading/ladder_badges.png;content/bts_spark/Trading/ladder_main_part.png;content/bts_spark/Trading/lean_algo_control.png;content/bts_spark/Trading/mini_orderbook.png;content/bts_spark/Trading/oco_algo_control.png;content/bts_spark/Trading/offset_algo_control.png;content/bts_spark/Trading/pnl_calculation.png;content/bts_spark/Trading/pnl_window.png;content/bts_spark/Trading/recreate_icon.png;content/bts_spark/Trading/settings_icon.png;content/bts_spark/Trading/spark_menu_order_book.png;content/bts_spark/Trading/top_algo_control.png;content/bts_spark/Trading/trigger_algo_control.png;content/bts_spark/_index.md;content/release_notes/_index.md;content/system_requirements/_index.md;static/book.js;static/favicon.ico;static/image.js;templates/index.html;templates/page.html;templates/section.html;templates/shortcodes/back_button.html) \ No newline at end of file diff --git a/docker/linux b/docker/linux index 68f43cef8..0df20ec20 160000 --- a/docker/linux +++ b/docker/linux @@ -1 +1 @@ -Subproject commit 68f43cef8d3edbda05a9517421092ada3c392aff +Subproject commit 0df20ec20afaedf4077701548bc9bcb1f04647bf diff --git a/externals b/externals index 6d8f64ca5..c695e9694 160000 --- a/externals +++ b/externals @@ -1 +1 @@ -Subproject commit 6d8f64ca5cee3acbf9addb51428f25d54b9f906a +Subproject commit c695e96940796883cb9de2602dab2269f4715464 diff --git a/src/client/spark/Daemons/OrderTicketDaemon.cs b/src/client/spark/Daemons/OrderTicketDaemon.cs index b825740e9..251681852 100644 --- a/src/client/spark/Daemons/OrderTicketDaemon.cs +++ b/src/client/spark/Daemons/OrderTicketDaemon.cs @@ -3,11 +3,13 @@ using bts.api.core; using bts.api.orderman; using bts.spark; using mbts; +using mbts.config; using mbts.spark; using mbts.ui; using mbts.ui.spark; using System; using System.Collections.Generic; +using System.Collections.Immutable; using System.ComponentModel.Composition; using System.Reactive.Linq; using System.Windows; @@ -19,20 +21,26 @@ namespace bts.shell { readonly IBus _bus; readonly OrdersModel _model; readonly ErrorReporter _error_reporter; + readonly bool _close_on_send; IReadOnlyDictionary _md_map; TableUpdate<(SecurityImmutable? sec, OrderRecordImmutable order), uint> _orders; IDisposable _dispose; [ImportingConstructor] - public OrderTicketDaemon(IBus bus, OrdersModel model, ErrorReporter error_reporter) { + public OrderTicketDaemon(IBus bus, OrdersModel model, ErrorReporter error_reporter) + : this(bus, model, error_reporter, Configuration.get().close_on_send) { } + + public OrderTicketDaemon(IBus bus, OrdersModel model, ErrorReporter error_reporter, bool close_on_send) { _bus = bus; _model = model; _error_reporter = error_reporter; + _close_on_send = close_on_send; _dispose = Disposable.Create( model.on_orders.OnDispatcher().Subscribe(o => _orders = o), bus.subscribe(SparkTags.SecuritiesTag).OnDispatcher().Subscribe(m =>_md_map = m), bus.subscribe(SparkTags.ShowOrderTicketFromSecurityTag).OnDispatcher().Subscribe(_show_order_ticket), bus.subscribe(SparkTags.ShowOrderTicketTag).OnDispatcher().Subscribe(_show_order_ticket), + bus.subscribe(SparkTags.ShowOrderTicketAutoLookupTag).Subscribe(_show_order_tickets), bus.subscribe(SparkTags.ShowModifyOrderTag).OnDispatcher().Subscribe(_show_modify_order) ); } @@ -54,17 +62,28 @@ namespace bts.shell { void _show_order_ticket(SecurityMD smd) => _show_order_window(new OrderTicket { DataContext = new NewOrderTicketVM(_model, smd, - Observable.Return(LadderSettings.Default)) + Observable.Return(LadderSettings.Default)) { + close_on_send = _close_on_send + } }); void _show_order_ticket((OrderDefinitionImmutable def, double price, uint size) ops) { if (_md_map.TryGetValue(ops.def.SecurityKey, out SecurityMD smd)) _show_order_window(new OrderTicket { DataContext = new NewOrderTicketVM(_model, smd, ops.def, ops.price, ops.size, - Observable.Return(LadderSettings.Default.calculator_buttons)) + Observable.Return(LadderSettings.Default.calculator_buttons)) { + close_on_send = _close_on_send + } }); } + void _show_order_tickets(IImmutableSet securities) { + foreach (var id in securities.empty_if_null()) { + if (_md_map.TryGetValue(id, out var smd)) + _show_order_ticket(smd); + } + } + void _show_modify_order(uint order_key) { if (_orders.state.TryGetValue(order_key, out var ori) && ori.sec.HasValue && (ori.order.HasDef && ori.order.Def.HasCustomDef && !(ori.order.Def.CustomDef.HasStop || ori.order.Def.CustomDef.HasStopLimit))) { @@ -78,4 +97,4 @@ namespace bts.shell { } } } -} \ No newline at end of file +} diff --git a/src/client/spark/Images/Icons.cs b/src/client/spark/Images/Icons.cs index 4223bde21..eab0b9511 100644 --- a/src/client/spark/Images/Icons.cs +++ b/src/client/spark/Images/Icons.cs @@ -26,6 +26,7 @@ namespace mbts.ui { AttachAlgosKey = nameof(AttachAlgosKey), CheckMarkGeometryKey = nameof(CheckMarkGeometryKey), CopyWFGeometryKey = nameof(CopyWFGeometryKey), + CopyBoxesGeometryKey = nameof(CopyBoxesGeometryKey), DataEditGeometryKey = nameof(DataEditGeometryKey), DetachAlgosKey = nameof(DetachAlgosKey), DiskGeometryKey = nameof(DiskGeometryKey), @@ -45,6 +46,7 @@ namespace mbts.ui { KeyGeometryKey = nameof(KeyGeometryKey), LetterAKey = nameof(LetterAKey), LetterDKey = nameof(LetterDKey), + MenuOrientationGeometryKey = nameof(MenuOrientationGeometryKey), OrdersGeometryKey = nameof(OrdersGeometryKey), PauseGeometryKey = nameof(PauseGeometryKey), PaymentGeometryKey = nameof(PaymentGeometryKey), @@ -62,6 +64,8 @@ namespace mbts.ui { public static Geometry PlayGeometry => Geometry.Parse(get_geometric_path(PlayGeometryKey).FirstOrDefault() ?? string.Empty); + static readonly Pen _copy_boxes_pen = new Pen(Brushes.Black, HighDpiExtensions.RoundLayoutValue(5)).frozen(); + static readonly string base_uri = "pack://application:,,,/Images/Icons/"; private static ResourceDictionary _resources = (ResourceDictionary)Application.LoadComponent(new Uri("/Images/Vector/Icons.xaml", UriKind.RelativeOrAbsolute)); @@ -156,6 +160,7 @@ namespace mbts.ui { public static ImageSource CheckMark => create_icon(CheckMarkGeometryKey); public static ImageSource Clock { get { return load_resource_and_freeze("Clock"); } } public static ImageSource CopyWF => create_icon(CopyWFGeometryKey); + public static ImageSource CopyBoxes => create_icon(CopyBoxesGeometryKey, null, _copy_boxes_pen); public static ImageSource DataEdit => create_icon(DataEditGeometryKey); public static ImageSource Defrag { get { return load_resource_and_freeze("Defrag"); } } public static ImageSource DetachAlgos => create_icon_and_rotate(DetachAlgosKey, Brushes.Red); @@ -179,6 +184,7 @@ namespace mbts.ui { public static ImageSource Import => load_resource_and_freeze("Import"); public static ImageSource Key => create_icon(KeyGeometryKey); public static ImageSource Knight { get { return load_resource_and_freeze("Knight"); } } + public static ImageSource MenuOrientation => create_icon(MenuOrientationGeometryKey); public static ImageSource Pause => create_icon(PauseGeometryKey); public static ImageSource Payment => create_icon(PaymentGeometryKey); public static ImageSource Pencil => create_icon(PencilGeometryKey); diff --git a/src/client/spark/Images/Vector/Icons.xaml b/src/client/spark/Images/Vector/Icons.xaml index 3b4f882f6..c6a0ce46f 100644 --- a/src/client/spark/Images/Vector/Icons.xaml +++ b/src/client/spark/Images/Vector/Icons.xaml @@ -46,6 +46,18 @@ + + + M-55,5 L-55,55 L-5,55 + + + M-40,-10 L-40,40 L10,40 L10,-10 L-40,-10 + + + M-10,10 L40,10 L40,-40 L-10,-40 L-10,10 + + + M14.733902,12.084991L9.751783,17.388992 12.982842,17.436005C13.569886,17.462997 14.5229,17.350998 14.876848,17.005005 14.954852,16.929993 15.031879,16.824005 15.02486,16.593002 14.986895,15.457993 14.838883,13.438004 14.733902,12.084991z M22.507753,11.134453C22.480678,11.134323,22.467085,11.135494,22.469961,11.136993L20.64694,11.145004 16.291904,11.192993C16.388891,12.405991 16.596901,15.100998 16.647928,16.539001 16.668924,17.177994 16.448888,17.742004 16.007904,18.168991 15.210897,18.947998 13.893864,19.065002 13.179865,19.065002L9.2818066,19.005005 9.3258129,25.522003 9.3728109,25.528 9.3278271,25.882996 9.3317944,26.395996 9.3107983,26.397995C9.3167797,26.789993,9.3378369,27.552994,9.3958212,29.065994L9.4068075,29.393005C9.4207855,29.819992 9.5648295,29.994995 9.6707884,30.089005 9.9807898,30.365997 10.539817,30.390991 10.717799,30.369003L10.717799,30.375C10.88284,30.354996 11.280855,30.356003 12.823844,30.365997 13.867863,30.371002 15.206869,30.376999 16.594886,30.376999 20.757965,30.376999 23.270998,30.354996 23.862007,30.311005 24.454971,30.268005 24.661029,29.154999 24.690021,28.729996 24.690021,28.729996 24.677997,27.876999 24.661029,26.582993 24.612016,22.671005 24.51198,14.697998 24.472002,12.802002 24.461013,12.302994 24.316969,11.929993 24.034008,11.662003 23.547475,11.200003 22.697284,11.13536 22.507753,11.134453z M8.8867823,2.8410034L2.5417312,10.296997 6.4037791,10.356995C6.8917614,10.390991 8.3258005,10.341003 8.9567896,9.7299957 9.1738335,9.5189972 9.2667919,9.2659912 9.2558046,8.9089966 9.2067934,7.3889923 9.0258213,4.7480011 8.8867823,2.8410034z M10.424826,1.6239929C10.551842,3.302002 10.816799,6.951004 10.876797,8.8560028 10.903836,9.6750031 10.636804,10.360992 10.083818,10.897995 9.0667769,11.882004 7.3527657,11.987991 6.6627546,11.987991 6.4657918,11.987991 6.3367616,11.979004 6.3177796,11.977005L1.6477377,11.905991C1.6387044,14.278992 1.6236895,20.283997 1.6496909,22.358994 1.651705,22.569992 1.6437093,22.780991 1.6366904,22.992004 1.6117265,23.593994 1.5926833,24.112991 1.8537338,24.386002 2.0716933,24.612991 2.6497034,24.886002 4.1457549,24.886002 6.0127832,24.886002 7.0867711,24.876999 7.6967641,24.867004L7.6457993,17.259995 14.853899,9.5849915 16.681924,9.5650024 16.681924,9.5429993 19.454908,9.5289917 19.406934,2.6210022C19.323925,2.3549957,18.960945,1.6239929,17.387928,1.6239929z M9.1738335,0L17.387928,0C19.94692,0,20.874971,1.5299988,21.022983,2.4329987L21.077976,9.5209961 22.446951,9.5139923C22.43395,9.5130005 24.031017,9.4250031 25.148035,10.481995 25.753999,11.054001 26.071996,11.822998 26.092992,12.766998 26.142006,15.065994 26.281044,26.268997 26.307047,28.412003L26.311014,28.764999C26.279029,29.817993 25.750032,31.802002 23.979013,31.931 23.342958,31.977005 20.887972,32 16.683878,32 13.798893,32 11.107818,31.988998 10.808803,31.987991 10.789821,31.990997 9.5147806,32.112 8.6008288,31.309006 8.0858074,30.854996 7.8107797,30.229004 7.7838017,29.444992L7.7728153,29.126999C7.721789,27.759995 7.6978022,26.970993 7.6898061,26.490005 7.0547882,26.5 5.9867817,26.509003 4.1457549,26.509003 2.4377257,26.509003 1.3387128,26.192001 0.68367504,25.509003 -0.055286743,24.742004 -0.017322397,23.742004 0.012707477,22.938004 0.020702986,22.744003 0.028698692,22.559998 0.026684528,22.378998 -0.00029337304,20.240997 0.016674615,13.856995 0.026684528,11.212997L0.026684528,10.867004 0.14167619,10.610992 8.7147823,0.54100037 8.7088009,0.45899963 8.8018194,0.43800354z @@ -280,6 +292,10 @@ M22.399981,2.4000006C22.099982,2.4000006 21.899982,2.5 21.599982,2.6999998 21.199983,3.1000004 21.199983,3.8000002 21.599982,4.2000003L26.199979,8.9000001C26.599978,9.3000002 27.299977,9.3000002 27.699977,8.9000001 28.099977,8.5000002 28.099977,7.8000002 27.699977,7.4000006L23.099981,2.6999998C22.899981,2.5,22.699981,2.4000006,22.399981,2.4000006z M21.499982,0C22.299982,0,23.199981,0.30000019,23.79998,0.90000057L29.299976,6.4000001C30.599975,7.7000003,30.599975,9.7000003,29.299976,11L22.599981,17.7C21.299983,19,19.299984,19,17.999985,17.7L17.299985,17 12.699989,21.6 10.399991,20.900001 10.899991,23.400001 8.4999928,22.8 8.9999924,25.5 6.2999945,25.1 6.7999945,27.6 4.2999964,27 4.7999954,29.6 2.4999971,32 0,26.6 13.499989,13.1 16.999986,16.6 12.699989,12.3C11.399991,11,11.399991,9.0000002,12.699989,7.7000003L19.399984,1C19.899983,0.30000019,20.699983,0,21.499982,0z + + M14.997001,19.999038L15.000001,23.499012C15.000001,24.327005,14.327008,25,13.500016,25L9.9970522,25 9.9970522,23.000015 13.000022,23.000015 12.997022,20.001038z M9.000001,19.000006L9.000001,30.000006 30.000001,30.000006 30.000001,19.000006z M2,2L2,23 7.000001,23 7.000001,18.500006C7.000001,17.673006,7.6730013,17.000006,8.500001,17.000006L13.000001,17.000006 13.000001,2z M1.5,0L13.500001,0C14.327001,0,15.000001,0.67300034,15.000001,1.5L15.000001,17.000006 26.956518,17.000006 23.162404,13.207182C22.772376,12.816143 22.772376,12.184205 23.162404,11.793225 23.357907,11.597736 23.613928,11.499992 23.869827,11.499992 24.125725,11.499992 24.381502,11.597736 24.576517,11.793225L25.889371,13.105454 25.866285,12.914201C25.554945,10.547287 24.699391,8.7684691 23.308905,7.6089654 21.974919,6.4954615 20.356436,6.1229606 19.066825,6.0297103L19.059648,6.0292783 20.545799,7.5160289C20.936786,7.9070184 20.936786,8.5390015 20.545799,8.929991 20.350807,9.1249857 20.094815,9.2229831 19.838825,9.2229831 19.582834,9.2229831 19.326843,9.1249857 19.131849,8.929991L15.185988,4.9830971 18.981854,1.1871986C19.371841,0.79620934 20.004819,0.79620934 20.395805,1.1871986 20.785791,1.5771885 20.785791,2.2101717 20.395805,2.601161L18.976535,4.020443 18.999199,4.0214248C20.641604,4.1119318 22.785724,4.567862 24.590892,6.0739603 26.493747,7.660778 27.606404,10.054969 27.91277,13.209869L27.913735,13.221022 29.341699,11.793225C29.536714,11.597736 29.792459,11.499992 30.048328,11.499992 30.304196,11.499992 30.560187,11.597736 30.75569,11.793225 31.146694,12.184205 31.146694,12.816143 30.75569,13.207182L26.962552,17.000006 30.500001,17.000006C31.327001,17.000006,32.000001,17.673006,32.000001,18.500006L32.000001,30.500006C32.000001,31.327005,31.327001,32.000006,30.500001,32.000006L8.500001,32.000006C7.6730013,32.000006,7.000001,31.327005,7.000001,30.500006L7.000001,25 1.5,25C0.67300034,25,0,24.327001,0,23.5L0,1.5C0,0.67300034,0.67300034,0,1.5,0z + + M50.14375,33.389126C50.416863,33.394688,50.653496,33.587773,50.705998,33.864617L50.015995,45.114388C49.810295,46.291462,49.130394,45.097489,49.130394,45.097489L47.65659,42.640538C42.747776,49.635197 34.633152,54.221001 25.433924,54.221001 14.884193,54.221001 5.7437552,48.204125 1.2449617,39.419205 0.80087067,38.552021 0.21358696,37.705738 0.052086769,36.736958 -0.49735315,33.490925 3.4507786,32.901036 4.8049124,34.432404 5.3674143,35.067692 6.034036,36.16407 6.5079177,37.026051 10.106778,43.799416 17.2321,48.413819 25.433924,48.413819 32.656544,48.413819 39.026364,44.826695 42.903977,39.351506L40.229367,38.854115C40.229367,38.854115,38.677464,38.647118,39.742466,37.996033L50.024895,33.398526C50.064972,33.391365,50.104733,33.388333,50.14375,33.389126z M23.030291,9.0310004L27.889918,9.0310004 27.889918,13.028299C30.539786,13.205498,32.324932,13.958096,33.464161,14.528294L33.964176,14.775793 32.417435,20.038878 31.706417,19.68068C30.579987,19.11958 28.839241,18.244583 26.149073,18.244583 24.006916,18.244583 22.723183,19.122181 22.723183,20.590876 22.723183,21.894272 23.943314,22.804369 27.551308,24.187165 32.706444,26.124659 34.911,28.702853 34.911,32.817341 34.911,36.892929 32.090527,40.05172 27.673611,40.989117L27.673611,45.540001 22.767485,45.540001 22.767485,41.330414C20.252919,41.155815,17.695551,40.424118,16.101811,39.404721L15.683999,39.137619 17.221739,33.731438 17.969059,34.180634C19.088988,34.851235 21.402748,35.97873 24.340325,35.97873 26.734886,35.97873 28.276728,34.921635 28.276728,33.291336 28.276728,31.986641 27.547409,30.853846 23.986016,29.57255 20.083815,28.144253 16.095511,26.04406 16.095511,21.239174 16.095511,17.280985 18.737379,14.291395 23.030291,13.329098z M25.268765,0C35.819447,2.7347414E-07 44.961449,6.0155495 49.458798,14.804573 49.902695,15.669173 50.490094,16.516972 50.651287,17.48427 51.198281,20.734265 47.255726,21.318962 45.901341,19.789065 45.336346,19.153567 44.669552,18.051968 44.19566,17.19517 40.5957,10.421881 33.473275,5.8072398 25.268765,5.8072393 18.047545,5.8072398 11.678013,9.3918336 7.8003562,14.867073L10.474627,15.367072C10.474627,15.367072,12.026909,15.574172,10.962921,16.223872L0.67933281,20.826762C0.36037083,20.880062,0.057029126,20.669165,0.00099972012,20.354063L0.69093342,9.1118043C0.89552094,7.9296158,1.5738537,9.124924,1.5738539,9.124924L3.0452772,11.583379C7.9566038,4.584462,16.073666,2.7347414E-07,25.268765,0z diff --git a/src/client/spark/Modules/Market/MarketView/MarketViewView.xaml.cs b/src/client/spark/Modules/Market/MarketView/MarketViewView.xaml.cs index e42bf0e89..9a820ab1e 100644 --- a/src/client/spark/Modules/Market/MarketView/MarketViewView.xaml.cs +++ b/src/client/spark/Modules/Market/MarketView/MarketViewView.xaml.cs @@ -48,5 +48,5 @@ namespace mbts.ui.spark { } } - class MarketViewRowView : DIYGrid.HighPerformanceRow { } + class MarketViewRowView : DIYGrid.HighPerformanceRow { } } \ No newline at end of file diff --git a/src/client/spark/Modules/Market/MarketView/MarketViewWindow.cs b/src/client/spark/Modules/Market/MarketView/MarketViewWindow.cs index dede41acc..96ed8fab5 100644 --- a/src/client/spark/Modules/Market/MarketView/MarketViewWindow.cs +++ b/src/client/spark/Modules/Market/MarketView/MarketViewWindow.cs @@ -4,10 +4,10 @@ using bts.shell; using bts.shell.fills; using bts.spark; using bts.utils; +using bts.view; using mbts.persist; using mbts.ui; using mbts.ui.settings; -using mbts.ui.shell; using mbts.ui.spark; using mbts.ui.utility; using mbts.utils; @@ -32,6 +32,7 @@ namespace mbts.spark { SecurityCriteria _selected_security_criteria_backing, _sorted_selected_security_criteria_backing; + SparkMenuDisplayVM _menu_display_vm; public MarketViewWindow(MarketViewWindowFactory factory, IBus bus, OrdersModel orders_model, MarketViewWindowFactory.StartupData state, IWindowSettingsManager settings_manager) : base("Market View", bus, factory, SparkCommands.ShowMarketView.icon) { @@ -48,7 +49,9 @@ namespace mbts.spark { public override UIElement Content => _view; public override IEnumerable Commands => _commands; public override MarketViewWindowFactory.StartupData SaveState => - _state = new MarketViewWindowFactory.StartupData(_state.security_criteria, _vm.get_filter_states(), _vm.get_grid_save_state(), _vm.rows_view.get_sorting_criteria(_vm.columns)); + _state = new MarketViewWindowFactory.StartupData(_state.security_criteria, _vm.get_filter_states(), _vm.get_grid_save_state(), _vm.rows_view.get_sorting_criteria(_vm.columns)) { + menu_display = _menu_display_vm.safe_create() + }; public override double MinWidth => MarketViewWindowFactory.StartupData.DefaultGridSettings.columns.Where(c => c.is_visible).Sum(gcs => gcs.width) + SPARK_MENU_COLLAPSED_WIDTH @@ -101,6 +104,8 @@ namespace mbts.spark { public void thread_init() { _init_guard.check_access(); Log.notnull(_state); + _menu_display_vm = new SparkMenuDisplayVM(); + _menu_display_vm.load_from(_state.menu_display); var state_src = Observable.FromEvent, MarketViewWindowFactory.StartupData>(cb => _state_changed += cb, cb => _state_changed -= cb).StartWith(_state); _vm = new MarketViewVM(_bus, _orders_model, state_src, _settings_manager); _view = new MarketViewView { DataContext = _vm }; @@ -160,7 +165,8 @@ namespace mbts.spark { var dialog = new ShellSettingsDialog { DataContext = vm }; vm.RequestClose += (s, e) => WindowUtilities.force_close(dialog); return dialog; - })) + })), + _menu_display_vm.spark_cmd }; // _vm.selection_changed += on_selection_changed; @@ -190,5 +196,8 @@ namespace mbts.spark { _vm.Dispose(); Commands.OfType().DisposeAll(); } + + protected override void OnParentViewCreated(SparkWindowView parent_view) => + _menu_display_vm.safe_bind_to_view(parent_view); } } diff --git a/src/client/spark/Modules/Market/MarketView/MarketViewWindowFactory.cs b/src/client/spark/Modules/Market/MarketView/MarketViewWindowFactory.cs index d3ae03818..52ddefff1 100644 --- a/src/client/spark/Modules/Market/MarketView/MarketViewWindowFactory.cs +++ b/src/client/spark/Modules/Market/MarketView/MarketViewWindowFactory.cs @@ -1,6 +1,7 @@ using bts.api; using bts.proto; using bts.settings; +using bts.view; using mbts.persist; using mbts.spark; using mbts.spark.filters; @@ -53,6 +54,8 @@ namespace bts.shell { public readonly FilterStates filters; [ProtoMember(4)] public GridSettings grid; + [ProtoMember(5)] + public SparkMenuDisplaySettings menu_display; public StartupData() { } diff --git a/src/client/spark/Modules/Market/TimeAndSales/Settings/TimeAndSalesFilterStates.cs b/src/client/spark/Modules/Market/TimeAndSales/Settings/TimeAndSalesFilterStates.cs new file mode 100644 index 000000000..6514c3bb6 --- /dev/null +++ b/src/client/spark/Modules/Market/TimeAndSales/Settings/TimeAndSalesFilterStates.cs @@ -0,0 +1,36 @@ +using mbts.spark.filters; +using mbts.ui; +using ProtoBuf; +using System; + +namespace bts.shell.time_and_sales { + [ProtoContract] + class FilterStates { + [ProtoMember(1)] + public TimeFilterTuple time; + [ProtoMember(2)] + public string security; + [ProtoMember(3)] + public DoubleMinMaxState price; + [ProtoMember(4)] + public UIntMinMaxState size; + // [ProtoMember(5)] + // ProtoMember 5 cannot be used further + [ProtoMember(6)] + public string security_key; + [ProtoMember(7)] + public co2.AggressorSide[] aggressor_sides; + } + + static class TimeAndSalesFilterStatesExtensions { + public static Func build_predicate(this FilterStates fs) { + var pb = new ColumnPredicateBuilder(); + pb.add_regex(fs.security, r => r.security.ToString()); + pb.add_time_filter(fs.time, r => r.time); + pb.add_price(fs.price, r => r.price, r => r.security); + pb.add_numeric(fs.size, r => r.size); + pb.add_discrete_values(fs.aggressor_sides, r => r.aggressor_side); + return pb.to_predicate(); + } + } +} diff --git a/src/client/spark/Modules/Market/TimeAndSales/Settings/TimeAndSalesSettings.cs b/src/client/spark/Modules/Market/TimeAndSales/Settings/TimeAndSalesSettings.cs new file mode 100644 index 000000000..f65e30875 --- /dev/null +++ b/src/client/spark/Modules/Market/TimeAndSales/Settings/TimeAndSalesSettings.cs @@ -0,0 +1,74 @@ +using mbts.spark; +using mbts.ui; +using mbts.ui.settings; +using ProtoBuf; +using System.Collections.Generic; +using System.Linq; +using static mbts.ui.controls.DIYGrid; +using Columns = bts.shell.time_and_sales.TimeAndSalesView.Columns; + +namespace bts.shell.time_and_sales { + [ProtoContract] + class TimeAndSalesSettings { + [ProtoMember(1)] + public readonly SecurityCriteria security_criteria; + [ProtoMember(2)] + List _sorting_criterion; + [ProtoMember(3)] + public FilterStates filters; + [ProtoMember(4)] + public GridSettings grid; + [ProtoMember(5)] + public SparkMenuDisplaySettings menu_display; + [ProtoMember(6)] + public bool use_defaults; + + public TimeAndSalesSettings() { } + + public TimeAndSalesSettings(SecurityCriteria security_criteria) : + this(security_criteria, new FilterStates(), null, null) { } + + public TimeAndSalesSettings(SecurityCriteria security_criteria, FilterStates filters, GridSettings grid = default, List sorting_criterion = null) { + this.security_criteria = security_criteria; + this.filters = filters; + this.grid = grid; + _sorting_criterion = sorting_criterion; + } + + public static GridSettings DefaultGridSettings => GridSettings.Default.with(DefaultColumns.all, DefaultColumns.default_sorting_criterion); + + public List sorting_criterion => _sorting_criterion ?? (_sorting_criterion = DefaultColumns.default_sorting_criterion.ToList()); + + public static TimeAndSalesSettings Default(SecurityCriteria security_criteria) => + new TimeAndSalesSettings(security_criteria, new FilterStates(), null, DefaultColumns.default_sorting_criterion.ToList()); + + public TimeAndSalesSettings with(SecurityCriteria security_criteria) => + new TimeAndSalesSettings(security_criteria, filters, grid); + + public static class DefaultColumns { + public static GridColumnSettings security => new GridColumnSettings(Columns.Security.col_id(), DefaultColumnHeaders.Security, width: DefaultColumnWidths.Security); + public static GridColumnSettings time => new GridColumnSettings(Columns.Time.col_id(), DefaultColumnHeaders.Time, width: DefaultColumnWidths.TimeOfDay); + public static GridColumnSettings price => new GridColumnSettings(Columns.Price.col_id(), DefaultColumnHeaders.Price, width: DefaultColumnWidths.Price, horizontal_alignment: System.Windows.HorizontalAlignment.Right); + public static GridColumnSettings size => new GridColumnSettings(Columns.Size.col_id(), DefaultColumnHeaders.Size, width: DefaultColumnWidths.Size, horizontal_alignment: System.Windows.HorizontalAlignment.Right); + public static GridColumnSettings aggressor => new GridColumnSettings(Columns.Aggressor.col_id(), DefaultColumnHeaders.Aggressor, width: DefaultColumnWidths.Aggressor); + public static GridColumnSettings security_key => new GridColumnSettings(Columns.SecurityKey.col_id(), DefaultColumnHeaders.SecurityKey, is_visible: false, width: DefaultColumnWidths.SecurityKey); + + public static IEnumerable default_sorting_criterion { + get { + yield return new SortingCriteria(time.id, false); + } + } + + public static IEnumerable all { + get { + yield return security; + yield return time; + yield return price; + yield return size; + yield return aggressor; + yield return security_key; + } + } + } + } +} diff --git a/src/client/spark/Modules/Market/TimeAndSales/TimeAndSalesModel.cs b/src/client/spark/Modules/Market/TimeAndSales/TimeAndSalesModel.cs index b0121b166..1cea3f5bd 100644 --- a/src/client/spark/Modules/Market/TimeAndSales/TimeAndSalesModel.cs +++ b/src/client/spark/Modules/Market/TimeAndSales/TimeAndSalesModel.cs @@ -1,27 +1,26 @@ using bts.api; using bts.co2; +using mbts; using mbts.co2; +using mbts.spark; using System; using System.Collections.Generic; using System.Linq; using System.Reactive.Linq; -namespace mbts.spark { +namespace bts.shell.time_and_sales { class TimeAndSalesModel : IDisposable { - internal readonly SecurityCriteria security_criteria; - static readonly TimeSpan _poll_interval = TimeSpan.FromSeconds(0.4); Lazy>> _trades; IDisposable _dispose; - public TimeAndSalesModel(IBus bus, MDConsumer consumer, SecurityCriteria security_criteria) { - this.security_criteria = security_criteria; - var curr_channels = new Dictionary(); + public TimeAndSalesModel(IBus bus, MDConsumer consumer, IObservable security_criteria) { + var curr_channels = new Dictionary(); _trades = new Lazy>>(() => Observable.Interval(_poll_interval).Select(_ => { var copy = curr_channels; return copy.Values.SelectMany(c => c.read_trades()).ToList(); })); - _dispose = security_criteria.subscribe_md_map(bus).Subscribe( + _dispose = security_criteria.SelectManyInSeries(sc =>sc.subscribe_md_map(bus)).Subscribe( md_map => { var copy = new Dictionary(curr_channels); copy.sync_with_demux(md_map, get_channel_key, get_channel_consumer, update_channel_consumer); @@ -95,4 +94,4 @@ namespace mbts.spark { } } } -} \ No newline at end of file +} diff --git a/src/client/spark/Modules/Market/TimeAndSales/TimeAndSalesRowVM.cs b/src/client/spark/Modules/Market/TimeAndSales/TimeAndSalesRowVM.cs new file mode 100644 index 000000000..b3a71b92d --- /dev/null +++ b/src/client/spark/Modules/Market/TimeAndSales/TimeAndSalesRowVM.cs @@ -0,0 +1,57 @@ +using bts.api; +using bts.co2; +using bts.utils; +using mbts; +using mbts.spark; +using mbts.ui.controls; +using mbts.ui.shell; +using mbts.utils; +using System; +using System.Collections.Generic; + +namespace bts.shell.time_and_sales { + class TimeAndSalesRowVM : ViewModelBase, DIYGrid.IRowVM, ISecurityRow, IEquatable { + // key comparer guarentees deterministic sorting + // if the rows in the collection have unique row_keys. + public static readonly IComparer key_comparer = + new ComparerBuilder(new[] { + Comparer.Default.wrap(r => r.time), + Comparer.Default.wrap(r => r.row_key) + }) + .to_comparer() + .to_safe(); + + readonly TradeMessageImmutable _trade; + + public TimeAndSalesRowVM(int row_key, SecurityImmutable security, TradeMessageImmutable trade) { + this.row_key = row_key; + this.security = security; + _trade = trade; + trade_key = trade.Key; + } + + public event Action invalidated; + + public int row_key { get; } + public uint trade_key { get; } + public uint security_key => security.Id; + public SecurityImmutable security { get; } + public DateTime time => ((ulong)_trade.Time).lldatetime().ToLocalTime(); + public double price => _trade.price(); + public uint size => _trade.Size; + public AggressorSide aggressor_side => _trade.AggressorSide; + + public void raise_invalidated() => + invalidated?.Invoke(); + + public bool Equals(TimeAndSalesRowVM other) => + other != null && + row_key == other.row_key; + + public override bool Equals(object obj) => + Equals(obj as TimeAndSalesRowVM); + + public override int GetHashCode() => + row_key; + } +} diff --git a/src/client/spark/Modules/Market/TimeAndSales/TimeAndSalesVM.cs b/src/client/spark/Modules/Market/TimeAndSales/TimeAndSalesVM.cs index e2b5b8139..9d7ed38b4 100644 --- a/src/client/spark/Modules/Market/TimeAndSales/TimeAndSalesVM.cs +++ b/src/client/spark/Modules/Market/TimeAndSales/TimeAndSalesVM.cs @@ -1,86 +1,363 @@ using bts.api; using bts.co2; using bts.collections; +using bts.utils; +using mbts; using mbts.persist; +using mbts.spark; using mbts.spark.filters; using mbts.ui; using mbts.ui.controls; using mbts.ui.settings; -using mbts.ui.spark; +using mbts.ui.shell; using mbts.ui.utility; +using mbts.utils; using System; using System.Collections.Generic; +using System.Collections.Immutable; using System.Collections.ObjectModel; +using System.Diagnostics; using System.Linq; using System.Reactive.Linq; -using System.Threading.Tasks; +using System.Threading; +using System.Windows.Controls; using System.Windows.Input; using System.Windows.Media; -using static bts.shell.TimeAndSalesWindowFactory; using static mbts.ui.controls.DIYGrid; -namespace mbts.spark { - class TimeAndSalesVM : SecurityGrid { - readonly IBus _bus; - readonly TimeAndSalesModel _model; - IWindowSettingsManager _settings_manager; +namespace bts.shell.time_and_sales { + class TimeAndSalesVM : DisposableViewModelBase, IHandleGridSorting, IHandleRowSelection { + const int _max_row_count = 1000; + static int _id_counter; + static IReadOnlyList>> _filter_getters = + ObjectSnapshot.property_delegates_of_type>(); + readonly ColumnSortManager _sort_manager; + readonly RowFactory _row_factory = new RowFactory(); + readonly LoggerContext _log; + readonly IWindowSettingsManager _settings_manager; + readonly DeferrableActionWrapper + _refresh_filter, + _refresh_sort, + _refresh_selected_rows; + IComparer _comparer_backing; + Func _filter_backing; + ImmutableHashSet _selected_rows = ImmutableHashSet.Empty; + ImmutableList _all_rows = ImmutableList.Empty; + ImmutableList _buffered_trades; + /// Although the sorting criteria can be obtained from the (), + /// a local copy is kept because the settings collector may call from a thread + /// other than the dispatcher thread associated with this instance as a viewmodel, + /// and the property is not thread-safe. + /// Therefore, returns this local copy, and thus avoids accessing the non-thread-safe property. + ImmutableList _sorting_criteria = ImmutableList.Empty; + TimeAndSalesRowVM _current_row; + bool _is_paused; + int + _load_settings_count, + _filter_change_count, + _sort_change_count; - public TimeAndSalesVM(IBus bus, IWindowSettingsManager settings_manager, TimeAndSalesModel model, StartupData startup_data) - : base(RXCollection.CreateBuffer(model.trades, 1000), Enumerable.Empty()) { - _bus = bus; - _model = model; + public TimeAndSalesVM(IWindowSettingsManager settings_manager) { + _sort_manager = new ColumnSortManager(columns.WrapSelector(c => c as ISortableDIYGridColumn, null), TimeAndSalesView.Columns.RowKey.ToString()); + _comparer_backing = _sort_manager.BuildComparer(_get_column_comparer); + _log = new LoggerContext(Log.Ui, $"Time And Sales VM ({Interlocked.Increment(ref _id_counter)})", null); _settings_manager = settings_manager; - show_ladder = DelegateCommandParamObserver.Create(current_row_observable, r => _show_ladder_async(r).ignore(), r => r != null); - security_filter = new RegexFilterVM(r => r.security.ToString(), nameof(Row.security)); - if (startup_data.filters is FilterStates filters) { + // deferrable filter/sort refresh + _refresh_filter = new DeferrableActionWrapper(_refresh_filter_impl); + _refresh_sort = new DeferrableActionWrapper(_refresh_sort_impl); + _refresh_selected_rows = new DeferrableActionWrapper(() => selected_rows_changed?.Invoke(_selected_rows)); + // grid settings + grid_settings_manager = new SimpleGridSettingsManager(columns, new Dictionary { }, rows); + grid_settings_manager.load_from(settings_manager.current_settings()); + // Columns + add_column( + TimeAndSalesView.Columns.Security, + r => r.security.ToString(), + DefaultColumnHeaders.Security, + DefaultColumnWidths.Security, + security_filter, + DataGridFilterKnownTemplates.Regex); + add_column( + TimeAndSalesView.Columns.Time, + r => r.time.ToString("h:mm:ss tt"), + DefaultColumnHeaders.Time, + DefaultColumnWidths.Time, + time_filter, + DataGridFilterKnownTemplates.TimeFilter); + add_column( + TimeAndSalesView.Columns.Price, + r => r.security.spec_or_default().format(r.price), + DefaultColumnHeaders.Price, + DefaultColumnWidths.Price, + price_filter, + DataGridFilterKnownTemplates.DoubleMinMax, + System.Windows.HorizontalAlignment.Right); + add_column( + TimeAndSalesView.Columns.Size, + r => r.size.ToString(), + DefaultColumnHeaders.Size, + DefaultColumnWidths.Size, + size_filter, + DataGridFilterKnownTemplates.UIntMinMax, + System.Windows.HorizontalAlignment.Right); + add_column( + TimeAndSalesView.Columns.Aggressor, + r => r.aggressor_side.ToString(), + DefaultColumnHeaders.Aggressor, + DefaultColumnWidths.Aggressor, + aggressor_filter, + DataGridFilterKnownTemplates.EnumValues); + add_column( + TimeAndSalesView.Columns.SecurityKey, + r => r.security_key.ToString(), + DefaultColumnHeaders.SecurityKey, + DefaultColumnWidths.SecurityKey, + security_key_filter, + DataGridFilterKnownTemplates.Regex); + + settings_manager.subscribe_current().OnDispatcher().Subscribe(grid_settings_manager); + // commands + show_ladder_cmd = new DelegateCommand(() => { + if (current_row != null) + request_show_ladder?.Invoke(current_row); + }); + // init IDisposable resources + var resources = new List(); + resources.AddRange(_filters.Select(f => { + f.filter_changed += _refresh_filter.execute; + return Disposable.Create(() => f.filter_changed -= _refresh_filter.execute); + })); + _sort_manager.active_sorting_changed += _refresh_sort.execute; + resources.Add(Disposable.Create(() => _sort_manager.active_sorting_changed -= _refresh_sort.execute)); + _dispose = Disposable.Create(resources.ToArray()); + // local methods + void add_column( + TimeAndSalesView.Columns col_key, + Func get_cell_text, + string header, + double width, + IDataGridColumnFilter filter, + string filter_template, + System.Windows.HorizontalAlignment h_alignment = System.Windows.HorizontalAlignment.Left) => + columns.Add(new RenderTextColumn( + col_key, get_cell_text, filter, filter_template, _get_aggressor_brush) { + id = col_key.col_id(), Header = header, Width = width, horizontal_alignment = h_alignment + } + ); + } + + public event Action> selected_rows_changed; + public event Action current_row_changed, request_show_ladder; + + public ObservableCollection columns { get; } = new ObservableCollection(); + public TimeAndSalesRowVM current_row { + get => _current_row; + set { + if (Set(ref _current_row, value)) + current_row_changed?.Invoke(value); + } + } + public ObservableCollection rows { get; } = new ObservableCollection(); + public ImmutableHashSet selected_rows => _selected_rows; + public int total_row_count => _all_rows.Count; + public SimpleGridSettingsManager grid_settings_manager { get; } + public bool is_paused { + get => _is_paused; + set { + if (_is_paused != value) { + _is_paused = value; + if (value) { + _buffered_trades = ImmutableList.Empty; + } else { + var resume = _buffered_trades; + _buffered_trades = null; + on_new_trades(resume); + } + } + } + } + // filters + public IDataGridColumnPersistentFilter time_filter { get; } = new TimeFilterVM(r => r.time); + public IDataGridColumnPersistentFilter security_filter { get; } = new RegexFilterVM(r => r.security.ToString(), nameof(TimeAndSalesRowVM.security)); + public IDataGridColumnPersistentFilter price_filter { get; } = new DoubleMinMax(r => r.price); + public IDataGridColumnPersistentFilter size_filter { get; } = new UIntMinMax(r => r.size, nameof(TimeAndSalesRowVM.size)); + public IDataGridColumnPersistentFilter aggressor_filter { get; } = DiscreteValuesFilterVM.Create(EnumHelper.get_values().ToArray(), r => r.aggressor_side); + public IDataGridColumnPersistentFilter security_key_filter { get; } = new RegexFilterVM(r => r.security_key.ToString()); + // commands + public ICommand show_ladder_cmd { get; } + + IComparer _comparer { + get => _comparer_backing; + set { + if (value == null) { + _log.warn("Comparer should not be set to null, will use the default comparer instead (based on trade time, then row key)."); + _comparer_backing = new ComparerBuilder(new[] { + Comparer.Default.wrap(r => r.time), + Comparer.Default.wrap(r => r.row_key) + }) + .to_comparer() + .to_safe(); + } else { + _comparer_backing = value; + } + var sorted_rows = rows.ToArray(); + var snapshot = _selected_rows; + Array.Sort(sorted_rows, _comparer_backing); + using (_refresh_selected_rows.defer_execution()) { + for (int i = 0; i < sorted_rows.Length; i++) { + if (rows[i].row_key != sorted_rows[i].row_key) + rows[i] = sorted_rows[i]; + } + } + } + } + + Func _filter { + get => _filter_backing; + set { + var old_filter = _filter_backing; + var new_filter = value; + _filter_backing = new_filter; + if (new_filter != null) { + for (int i = 0; i < rows.Count; i++) { + if (!new_filter(rows[i])) + rows.RemoveAt(i); + } + rows.RemoveWhere(r => !new_filter(r)); + if (old_filter != null) { + foreach (var r in _all_rows) { + if (!old_filter(r) && new_filter(r)) + rows.InsertSorted(r, _comparer); + } + } + } else if (old_filter != null) { + foreach (var r in _all_rows) { + if (!old_filter(r)) + rows.InsertSorted(r, _comparer); + } + } + } + } + + IEnumerable> _filters => + _filter_getters.Select(fn => fn(this)); + + public (FilterStates filters, IReadOnlyList sorting_criteria, GridSettings grid_settings) create() => + (_get_filter_states(), _sorting_criteria, grid_settings_manager.create()); + + public void load(FilterStates filters, IEnumerable sorting_criteria, GridSettings grid_settings) { + using (_refresh_filter.defer_execution()) + using (_refresh_sort.defer_execution()) { + _log.info($"begin load settings ({++_load_settings_count})..."); + var timer = new Stopwatch(); + timer.Start(); + grid_settings_manager.load_from(grid_settings); + _sort_manager.SortingCriteria = sorting_criteria; + // load filters time_filter.load_state(filters.time); security_filter.load_state(filters.security); price_filter.load_state(filters.price); size_filter.load_state(filters.size); aggressor_filter.load_state(filters.aggressor_sides); security_key_filter.load_state(filters.security_key); + // + timer.Stop(); + _log.info($"load settings ({_load_settings_count}) took {timer.ElapsedMilliseconds:0.00}ms."); } - // Columns - add_column(TimeAndSalesView.Columns.Security, DefaultColumnHeaders.Security, DefaultColumnWidths.Security, nameof(Row.security), security_filter, DataGridFilterKnownTemplates.Regex); - add_column(TimeAndSalesView.Columns.Time, DefaultColumnHeaders.Time, DefaultColumnWidths.Time, nameof(Row.time), time_filter, DataGridFilterKnownTemplates.TimeFilter); - add_column(TimeAndSalesView.Columns.Price, DefaultColumnHeaders.Price, DefaultColumnWidths.Price, nameof(Row.price), price_filter, DataGridFilterKnownTemplates.DoubleMinMax, System.Windows.HorizontalAlignment.Right); - add_column(TimeAndSalesView.Columns.Size, DefaultColumnHeaders.Size, DefaultColumnWidths.Size, nameof(Row.size), size_filter, DataGridFilterKnownTemplates.UIntMinMax, System.Windows.HorizontalAlignment.Right); - add_column(TimeAndSalesView.Columns.Aggressor, DefaultColumnHeaders.Aggressor, DefaultColumnWidths.Aggressor, nameof(Row.aggressor_side), aggressor_filter, DataGridFilterKnownTemplates.EnumValues); - add_column(TimeAndSalesView.Columns.SecurityKey, DefaultColumnHeaders.SecurityKey, DefaultColumnWidths.SecurityKey, nameof(Row.security_key), security_key_filter, DataGridFilterKnownTemplates.Regex); - void add_column(TimeAndSalesView.Columns col_key, string header, double width, string sort_member_path, IDataGridColumnFilter filter, string filter_template, System.Windows.HorizontalAlignment h_alignment = System.Windows.HorizontalAlignment.Left) => - columns.Add(new RenderTextColumn(col_key, r => r[col_key], filter, filter_template, r => _get_aggressor_brush(r)) - { id = col_id(col_key), Header = header, Width = width, sort_member_path = sort_member_path, horizontal_alignment = h_alignment } - ); - - // be sure to load GridSettings AFTER the columns collection has been populated, the grid settings manager looks columns by id to apply the appropriate settings, - // if the collection is not populated, the column settings will not be applied - grid_settings_manager = new SimpleGridSettingsManager(columns, new Dictionary { }, row_vms); - grid_settings_manager.load_from(settings_manager.current_settings()); - _resources.AddRange( - show_ladder, - DataGridFilterHelper.hook_filters( - rows_view, time_filter, security_filter, price_filter, size_filter, aggressor_filter, security_key_filter), - settings_manager.subscribe_current().OnDispatcher().Subscribe(grid_settings_manager) - ); - rows_view.set_sort_descriptions(startup_data.sorting_criterion, columns); } - public ObservableCollection columns { get; } = new ObservableCollection(); - public DelegateCommandParamObserver show_ladder { get; } - public SimpleGridSettingsManager grid_settings_manager { get; } - - public GridSettings get_grid_save_state() { - if (_settings_manager.instance_settings == null) - return null; - else - return grid_settings_manager.create(); + public void on_new_trades(IReadOnlyList trades) { + /// The total row count is limited by ; + /// trades are kept in a circular buffer (FIFO). + /// If paused, just need to add trades to . + if (is_paused) { + if (_buffered_trades == null) + _buffered_trades = ImmutableList.Empty; + if (trades.Count >= _max_row_count) { + _buffered_trades = _buffered_trades + .Clear() + .AddRange(ReadOnlyListSubRangeWrapper.Create(trades, trades.Count - _max_row_count, _max_row_count)); + } else { + int overflow_count = _buffered_trades.Count + trades.Count - _max_row_count; + if (overflow_count > 0) { + var rows_to_remove = _buffered_trades.WrapSubRange(0, overflow_count); + _buffered_trades = _buffered_trades.RemoveRange(0, overflow_count); + } + _buffered_trades = _buffered_trades.AddRange(trades); + } + return; + } + /// If not paused, update in the normal fasion: + /// add to and + if (trades.Count >= _max_row_count) { + trades = ReadOnlyListSubRangeWrapper.Create(trades, trades.Count - _max_row_count, _max_row_count); + _all_rows = _all_rows.Clear(); + rows.Clear(); + } else { + int overflow_count = _all_rows.Count + trades.Count - _max_row_count; + if (overflow_count > 0) { + var rows_to_remove = _all_rows.WrapSubRange(0, overflow_count); + _all_rows = _all_rows.RemoveRange(0, overflow_count); + rows.RemoveSorted(rows_to_remove, _comparer); + } + } + var all_rows_bd = _all_rows.ToBuilder(); + foreach (var t in trades) { + var r = _row_factory.create(t.security, t.trade); + all_rows_bd.Add(r); + if (_filter_backing == null || _filter_backing(r)) + rows.InsertSorted(r, _comparer); + } + _all_rows = all_rows_bd.ToImmutable(); + RaisePropertyChanged(nameof(total_row_count)); } - public StartupData create() => - new StartupData(_model.security_criteria, _get_filter_states(), get_grid_save_state(), rows_view.get_sorting_criteria(columns)); + public void on_sorting(object sender, DIYGridSortingEventArgs e) { + try { + if (e.Column is ISortableDIYGridColumn sc) { + _log.info($"handling sort event for column {sc.id}."); + _sort_manager.OnColumnClick(sc, KeyboardExtensions.IsShiftDown()); + var sorted_rows = rows.ToArray(); + var snapshot = _selected_rows; + _refresh_sort_impl(); + } else { + _log.warn($"ignoring sort event because column '{e.Column?.id}' does not implement {nameof(ISortableDIYGridColumn)}."); + } + } catch (Exception ex) { + _log.error($"error handling sort event: {ex}."); + } + } - private Brush _get_aggressor_brush(Row r) { + public void row_selection_changed(SelectionChangedEventArgs e) { + var bd = _selected_rows.ToBuilder(); + if (e.AddedItems != null) + bd.AddRange(e.AddedItems.OfType()); + if (e.RemovedItems != null) + bd.removeRange(e.RemovedItems.OfType()); + _selected_rows = bd.ToImmutable(); + _refresh_selected_rows.execute(); + } + + static IComparer _get_column_comparer(string column_name) => + _get_column_comparer(EnumHelper.parse(column_name)); + + static IComparer _get_column_comparer(TimeAndSalesView.Columns column) { + switch (column) { + case TimeAndSalesView.Columns.Aggressor: return wrap(r => r.aggressor_side); + case TimeAndSalesView.Columns.Time: return wrap(r => r.time); + case TimeAndSalesView.Columns.Security: return wrap(r => r.security); + case TimeAndSalesView.Columns.Price: return wrap(r => r.price); + case TimeAndSalesView.Columns.Size: return wrap(r => r.size); + case TimeAndSalesView.Columns.SecurityKey: return wrap(r => r.security_key); + case TimeAndSalesView.Columns.RowKey: return wrap(r => r.row_key); + default: throw ExceptionBuilder.Argument.unexpected_case(column, nameof(column)); + } + IComparer wrap(Func selector) => + Comparer.Default.wrap(selector); + } + + Brush _get_aggressor_brush(TimeAndSalesRowVM r) { BTSColor c; Brush b; if (r.aggressor_side == AggressorSide.Buy) c = BTSColors.MarketData.bid; @@ -90,14 +367,6 @@ namespace mbts.spark { return b; } - #region Filters - public IDataGridColumnPersistentFilter time_filter { get; } = new TimeFilterVM(r => r.time, nameof(Row.time)); - public IDataGridColumnPersistentFilter security_filter { get; } - public IDataGridColumnPersistentFilter price_filter { get; } = new DoubleMinMax(r => r.price, nameof(Row.price)); - public IDataGridColumnPersistentFilter size_filter { get; } = new UIntMinMax(r => r.size, nameof(Row.size)); - public IDataGridColumnPersistentFilter aggressor_filter { get; } = DiscreteValuesFilterVM.Create(EnumHelper.get_values().ToArray(), r => r.aggressor_side, nameof(Row.aggressor_side)); - public IDataGridColumnPersistentFilter security_key_filter { get; } = new RegexFilterVM(r => r.security_key.ToString(), nameof(Row.security_key)); - FilterStates _get_filter_states() => new FilterStates { time = time_filter.get_state(), @@ -107,73 +376,35 @@ namespace mbts.spark { security_key = security_key_filter.get_state(), aggressor_sides = aggressor_filter.get_state() }; - #endregion - protected override IEnumerable get_default_sorting() { - yield return new SortingCriteria(nameof(Row.time), false); + void _refresh_sort_impl() { + _log.info($"begin change sort ({++_sort_change_count})..."); + var timer = new Stopwatch(); + timer.Start(); + _comparer = _sort_manager.BuildComparer(_get_column_comparer, TimeAndSalesRowVM.key_comparer); + _sorting_criteria = ImmutableList.CreateRange(_sort_manager.SortingCriteria); + timer.Stop(); + _log.info($"sort change ({_sort_change_count}) took {timer.ElapsedMilliseconds:0.00}ms."); } - protected override Row row_factory(TradeInfo row_model) => - new Row(this, row_model.security, row_model.trade); - - - async Task _show_ladder_async(Row row) { - var smd_lookup = await SparkUtils.get_security_md_async(_bus, row.security.Id); - if (smd_lookup.success) _bus.post(SparkTags.ShowLadderTag, smd_lookup.result); + void _refresh_filter_impl() { + _log.info($"begin change filter ({++_filter_change_count})..."); + var timer = new Stopwatch(); + timer.Start(); + _filter = _get_filter_states().build_predicate(); + timer.Stop(); + _log.info($"filter change ({_filter_change_count}) took {timer.ElapsedMilliseconds:0.00}ms."); } - public class Row : SecurityRow, DIYGrid.IRowVM { - readonly uint _trade_key; + class RowFactory { + // the row key must be unique to each row in the collection + int _row_id_counter; - readonly string - _security_text, - _time_text, - _price_text, - _size_text, - _aggressor_text, - _trade_key_text, - _security_key_text; + public TimeAndSalesRowVM create(TradeInfo trade_info) => + new TimeAndSalesRowVM(_row_id_counter++, trade_info.security, trade_info.trade); - public Row(TimeAndSalesVM parent, SecurityImmutable security, TradeMessageImmutable trade) : base(security) { - _trade_key = trade.Key; - time = ((ulong)trade.Time).lldatetime().ToLocalTime(); - price = trade.price(); - size = trade.Size; - aggressor_side = trade.AggressorSide; - show_ladder = new DelegateCommand(() => parent._show_ladder_async(this).ignore()); - _security_text = security.ToString(); - _time_text = time.ToString("M/d h:mm:ss tt"); - _price_text = security.ContractSpec.format(price); - _size_text = size.ToString(); - _aggressor_text = aggressor_side.ToString(); - _trade_key_text = _trade_key.ToString(); - _security_key_text = security_key.ToString(); - } - - public event Action invalidated; - - public uint trade_key => _trade_key; - public DateTime time { get; } - public double price { get; } - public uint size { get; } - public AggressorSide aggressor_side { get; } - public ICommand show_ladder { get; } - - public string this[TimeAndSalesView.Columns col] { - get { - switch (col) { - case TimeAndSalesView.Columns.Security: return _security_text; - case TimeAndSalesView.Columns.Time: return _time_text; - case TimeAndSalesView.Columns.Price: return _price_text; - case TimeAndSalesView.Columns.Size: return _size_text; - case TimeAndSalesView.Columns.Aggressor: return _aggressor_text; - case TimeAndSalesView.Columns.SecurityKey: return _security_key_text; - default: return null; - } - } - } - - public void raise_invalidated() => invalidated?.Invoke(); + public TimeAndSalesRowVM create(SecurityImmutable security, TradeMessageImmutable trade) => + new TimeAndSalesRowVM(_row_id_counter++, security, trade); } } -} \ No newline at end of file +} diff --git a/src/client/spark/Modules/Market/TimeAndSales/TimeAndSalesView.xaml b/src/client/spark/Modules/Market/TimeAndSales/TimeAndSalesView.xaml index aa2fb3998..c9fae31a9 100644 --- a/src/client/spark/Modules/Market/TimeAndSales/TimeAndSalesView.xaml +++ b/src/client/spark/Modules/Market/TimeAndSales/TimeAndSalesView.xaml @@ -1,10 +1,10 @@  @@ -26,13 +26,14 @@ x:Name="_grid" Grid.Row="0" Columns="{Binding columns}" - Rows="{Binding rows_view}" + Rows="{Binding rows}" CurrentRow="{Binding current_row}" SelectionHighlight="{Binding grid_settings_manager.selection_highlight, Mode=OneWay}" - > + > - - + + + - + - + + + + + + diff --git a/src/client/spark/Modules/Market/TimeAndSales/TimeAndSalesView.xaml.cs b/src/client/spark/Modules/Market/TimeAndSales/TimeAndSalesView.xaml.cs index ab066f2dd..6d436185d 100644 --- a/src/client/spark/Modules/Market/TimeAndSales/TimeAndSalesView.xaml.cs +++ b/src/client/spark/Modules/Market/TimeAndSales/TimeAndSalesView.xaml.cs @@ -1,17 +1,21 @@ -using mbts.spark; -using mbts.ui.controls; +using mbts.ui.controls; using System.Windows.Controls; -namespace mbts.ui.spark { +namespace bts.shell.time_and_sales { /// /// Interaction logic for TimeAndSalesView.xaml /// partial class TimeAndSalesView : UserControl { - public enum Columns { Time, Security, Price, Size, OrderType, SecurityKey, Aggressor } + public enum Columns { Time, Security, Price, Size, SecurityKey, Aggressor, RowKey } public TimeAndSalesView() => InitializeComponent(); } - class TimeAndSalesRowView : DIYGrid.HighPerformanceRow { } -} \ No newline at end of file + class TimeAndSalesRowView : DIYGrid.HighPerformanceRow { } + + static class TimeAndSalesViewColumnsExtensions { + public static string col_id(this TimeAndSalesView.Columns column) => + column.ToString(); + } +} diff --git a/src/client/spark/Modules/Market/TimeAndSales/TimeAndSalesWindow.cs b/src/client/spark/Modules/Market/TimeAndSales/TimeAndSalesWindow.cs index 85938778a..5082f526c 100644 --- a/src/client/spark/Modules/Market/TimeAndSales/TimeAndSalesWindow.cs +++ b/src/client/spark/Modules/Market/TimeAndSales/TimeAndSalesWindow.cs @@ -1,125 +1,215 @@ -using bts; -using bts.api; -using bts.shell; +using bts.api; using bts.shell.fills; using bts.spark; +using bts.view; +using mbts; using mbts.co2; using mbts.persist; +using mbts.spark; using mbts.ui; using mbts.ui.settings; -using mbts.ui.shell; using mbts.ui.spark; using mbts.ui.utility; using mbts.utils; using System; using System.Collections.Generic; +using System.Collections.Immutable; using System.Linq; using System.Reactive.Linq; using System.Windows; using System.Windows.Media; -using static bts.shell.TimeAndSalesWindowFactory; -namespace mbts.spark { - class TimeAndSalesWindow : SparkWindow, ISharedWindow { +namespace bts.shell.time_and_sales { + class TimeAndSalesWindow : SparkWindow, ISharedWindow { const string _window_type = "TimeAndSales", _window_type_display_name = "Time And Sales"; readonly MDConsumer _consumer; readonly TimeAndSalesWindowFactory _factory; readonly IWindowSettingsManager _settings_manager; - SingleValuePump _vm; + readonly bool _can_pause_updates; + TimeAndSalesVM _vm; TimeAndSalesModel _model; - StartupData _state; + SecurityCriteria _security_criteria_backing; + TimeAndSalesSettings _state; TimeAndSalesView _view; SparkCommand[] _commands; + SparkMenuDisplayVM _menu_display_vm; IDisposable _subscriptions; - public TimeAndSalesWindow(TimeAndSalesWindowFactory factory, IBus bus, MDConsumer consumer, StartupData state, ImageSource icon, IWindowSettingsManager settings_manager) + public TimeAndSalesWindow(TimeAndSalesWindowFactory factory, IBus bus, MDConsumer consumer, TimeAndSalesSettings state, ImageSource icon, IWindowSettingsManager settings_manager, bool can_pause_updates) : base("Time And Sales", bus, factory, SparkCommands.ShowTimeAndSales.icon) { Log.assert(state != null); _consumer = consumer; _factory = factory; - _state = state; + _state = state ?? TimeAndSalesSettings.Default(new SecurityCriteria()); + if (_state.security_criteria == null) + _state = _state.with(new SecurityCriteria()); + _security_criteria_backing = _state.security_criteria; _settings_manager = settings_manager; + _can_pause_updates = can_pause_updates; + thread_id = mbts.config.Configuration.get().time_and_sales ? _window_type : null; Icon.Freeze(); } + event Action _security_criteria_changed; + public override string window_type => _window_type; public override IEnumerable Commands => _commands; public override UIElement Content => _view; - public override double MinWidth => StartupData.DefaultGridSettings.columns.Sum(gcs => gcs.width) + public override double MinWidth => TimeAndSalesSettings.DefaultGridSettings.columns.Sum(gcs => gcs.width) + SPARK_MENU_COLLAPSED_WIDTH + LAUNCHER_BUTTON_BORDER_WIDTH + EXTRA_FOR_NO_HORIZONTAL_SCROLLBAR_WIDTH; public string thread_id { get; } - public override StartupData SaveState => _state = _vm.value.create(); + public override TimeAndSalesSettings SaveState { + get { + _ensure_state(true); + return _state; + } + } + + SecurityCriteria _security_criteria { + get => _security_criteria_backing; + set { + _security_criteria_backing = value; + _state = null; + _security_criteria_changed?.Invoke(value); + } + } public override void Dispose() => _dispose_resources(); public void thread_init() { _dispose_resources(); - _vm = new SingleValuePump(); - var connectable_builder = new ConnectableSeriesBuilder(_vm.observable); + _ensure_state(); + if (!_state.use_defaults) + _settings_manager.instance_settings = _state.grid; + _menu_display_vm = new SparkMenuDisplayVM(); + _menu_display_vm.load_from(_state.menu_display); + _vm = new TimeAndSalesVM(_settings_manager); + var selected_rows_src = Observable.Create>(o => { + _vm.selected_rows_changed += o.OnNext; + return Disposable.Create(() => _vm.selected_rows_changed -= o.OnNext); + }); + var current_row_src = Observable.Create(o => { + if (_vm.current_row != null) + o.OnNext(_vm.current_row); + _vm.current_row_changed += o.OnNext; + return Disposable.Create(() => _vm.current_row_changed -= o.OnNext); + }); + var current_sec_key_src = current_row_src.Select(r => { + var result = ImmutableHashSet.Empty; + if (r != null) + result = result.Add(r.security_key); + return result; + }); var update_securities_cmd = SparkCommands.change_securities_callback(_window_type_display_name); - var current_smd_source = connectable_builder.create(vm => vm.current_security_md_observable(_bus)).OnDispatcher(); - var selected_secs_source = connectable_builder.create(vm => vm.selected_securities_observable()).OnDispatcher(); + var security_criteria_changed = new Action(sc => { }); + SparkCommand toggle_is_paused_cmd = null; + toggle_is_paused_cmd = new SparkCommandCommand(get_is_paused_cmd_title(), Icons.Pause, new DelegateCommand(() => { + _vm.is_paused = !_vm.is_paused; + toggle_is_paused_cmd.title = get_is_paused_cmd_title(); + })) { + show_in_toolbar = _can_pause_updates, + show_in_context_menu = _can_pause_updates + }; _commands = new SparkCommand[] { - SparkCommands.ShowLadder(SparkCommands.KeyGestures.ShowLadder).complete(current_smd_source, md => md.HasValue, ConvertUtils.ValueOrDefault), - SparkCommands.ShowOrderTicketFromSecurity(SparkCommands.KeyGestures.ShowOrderTicket).complete(current_smd_source, md => md.HasValue, ConvertUtils.ValueOrDefault), - SparkCommands.ShowFills(SparkCommands.KeyGestures.ShowFills).complete(selected_secs_source, always_true, get_fills_startup_data), - SparkCommands.ShowMarketView.complete(selected_secs_source, always_true, secs => secs.Count > 0 ? new SecurityCriteria(secs) : _state.security_criteria), - SparkCommands.change_securities_command(() => (update_securities_cmd, _state.security_criteria)), + // ladder + SparkCommands.ShowLadderAutoLookup(SparkCommands.KeyGestures.ShowLadder) + .complete(current_sec_key_src, sec_keys => sec_keys.Count > 0), + // ticket + SparkCommands.ShowOrderTicketAutoLookup(SparkCommands.KeyGestures.ShowOrderTicket) + .complete(current_sec_key_src, sec_keys => sec_keys.Count > 0), + // fills + SparkCommands.ShowFills(SparkCommands.KeyGestures.ShowFills) + .complete(selected_rows_src, always_true, get_fills_startup_data), + // mview + SparkCommands.ShowMarketView + .complete(selected_rows_src, always_true, rows => rows.Count > 0 ? new SecurityCriteria(rows.Select(r => r.security)) : _security_criteria), + // pause + toggle_is_paused_cmd, + // change securities + SparkCommands.change_securities_command(() => (update_securities_cmd, _security_criteria)), // wrap the grid settings view factory in a dialogCommand here since the vm is destroyed/recreated when the security criteria changes SparkCommands.window_settings_command(new DialogCommand(() => { var vm = new ShellSettingsDialogVM( _settings_manager, s => s.time_and_sales_grid, UserSettings.FileExtensions.GRID, - s => _vm.value.grid_settings_manager.create_vm( + s => _vm.grid_settings_manager.create_vm( // we need to get the most up to date GridSettings when launching b/c users may // have changed some settings on the grid directly, like column widths. - s.with(_vm.value.columns.Select(c => c.create())) + s.with(_vm.columns.Select(c => c.create())) ) ); vm.SubscribeDisposed(literal_title_source.OnDispatcher().Subscribe(t => vm.title = t)); var dialog = new ShellSettingsDialog { DataContext = vm }; vm.RequestClose += (s, e) => WindowUtilities.force_close(dialog); return dialog; - })) + })), + _menu_display_vm.spark_cmd }; - _subscriptions = Disposable.Create( - _bus.subscribe(update_securities_cmd.tag).OnDispatcher().Subscribe(update_criteria), - connectable_builder.connect_all()); - _initialize(); - + _vm.load(_state.filters, _state.sorting_criterion, _state.grid); + _vm.request_show_ladder += show_ladder; + var security_criteria_src = _bus.subscribe(update_securities_cmd.tag); + var subs = new List { + security_criteria_src.Subscribe(sc => _security_criteria = sc), + Disposable.Create(() => _vm.request_show_ladder -= show_ladder) + }; + _model = new TimeAndSalesModel(_bus, _consumer, Observable.Create(o => { + o.OnNext(_security_criteria); + return security_criteria_src.Subscribe(o); + })); + subs.Add(_model.trades.OnDispatcher().Subscribe(_vm.on_new_trades)); + _subscriptions = Disposable.Create(subs.ToArray()); + if (_view == null) + _view = new TimeAndSalesView(); + _view.DataContext = _vm; + // local methods bool always_true(T _) => true; - FillsSettings get_fills_startup_data(IReadOnlyList secs) => + + FillsSettings get_fills_startup_data(ImmutableHashSet rows) => new FillsSettings(new FillsFilterStates { - security = secs.Count > 0 ? new SecurityCriteria(secs) : _state.security_criteria + security = rows.Count > 0 ? new SecurityCriteria(rows.Select(r => r.security)) : _security_criteria }); - void update_criteria(SecurityCriteria c) { - _state = _vm.value.create().with(c); - _initialize(); + + string get_is_paused_cmd_title() => + $"{(_vm.is_paused ? "Resume" : "Pause")} Updates"; + + void show_ladder(TimeAndSalesRowVM row) { + if (row != null) + _bus.post(SparkTags.ShowLadderAutoLookupTag, ImmutableHashSet.Create(new[] { row.security_key })); } } + protected override void OnParentViewCreated(SparkWindowView parent_view) => + _menu_display_vm.safe_bind_to_view(parent_view); + void _dispose_resources() { Disposable.dispose(ref _subscriptions); - Disposable.dispose(ref _vm); - Disposable.dispose(ref _model); if (_commands != null) { _commands.OfType().DisposeAll(); _commands = null; } + Disposable.dispose(ref _model); + Disposable.dispose(ref _vm); } - void _initialize() { - Disposable.dispose(ref _model); - _model = new TimeAndSalesModel(_bus, _consumer, _state.security_criteria); - // the previous _vm.value is automatically disposed when _vm.value is set - no need to dispose it here - _vm.value = new TimeAndSalesVM(_bus, _settings_manager, _model, _state); - if (_view == null) - _view = new TimeAndSalesView(); - _view.DataContext = _vm.value; + void _ensure_state(bool force_recreate = false) { + if (_state == null || force_recreate) { + if (_vm == null) { + _state = TimeAndSalesSettings.Default(_security_criteria); + } else { + var (filters, sorting, grid) = _vm.create(); + _state = new TimeAndSalesSettings(_security_criteria, filters, grid, sorting.ToList()) { + use_defaults = _settings_manager.instance_settings == null + }; + } + // should be safe to assume _menu_display_vm and _vm will either both be null, or both be non null, + // but redundant null checks don't hurt, and just may prevent a crash. + if (_menu_display_vm != null) + _state.menu_display = _menu_display_vm.safe_create(); + } } } -} \ No newline at end of file +} diff --git a/src/client/spark/Modules/Market/TimeAndSalesWindowFactory.cs b/src/client/spark/Modules/Market/TimeAndSalesWindowFactory.cs index efb01ab83..52cc2a337 100644 --- a/src/client/spark/Modules/Market/TimeAndSalesWindowFactory.cs +++ b/src/client/spark/Modules/Market/TimeAndSalesWindowFactory.cs @@ -1,33 +1,32 @@ using bts.api; using bts.spark; +using bts.shell.time_and_sales; using mbts; using mbts.co2; using mbts.persist; using mbts.spark; -using mbts.spark.filters; using mbts.ui; using mbts.ui.settings; -using ProtoBuf; using System; using System.Collections.Generic; -using System.Linq; using System.Reactive.Linq; using System.Threading.Tasks; -using static mbts.ui.controls.DIYGrid; -using static mbts.ui.spark.TimeAndSalesView; +using Columns = bts.shell.time_and_sales.TimeAndSalesView.Columns; +using mbts.config; namespace bts.shell { - class TimeAndSalesWindowFactory : ShellWindowFactory { + class TimeAndSalesWindowFactory : ShellWindowFactory { readonly IBus _bus; readonly MDConsumer _consumer; readonly UserSettingsHub _settings_hub; + readonly TimeAndSalesConfig _time_and_sales_conf; IReadOnlyDictionary _securities = new Dictionary(); public TimeAndSalesWindowFactory(IShellModule module, IBus bus, MDConsumer consumer, UserSettingsHub settings_hub) : base(module, "TimeAndSales") { _bus = bus; _consumer = consumer; _settings_hub = settings_hub; - + _time_and_sales_conf = new TimeAndSalesConfig(Configuration.get()); _dispose = Disposable.Create( bus.subscribe(SparkTags.SecuritiesTag).Subscribe(s => _securities = s), bus.subscribe(SparkTags.ShowTimeAndSalesTag).OnDispatcher().Subscribe(show) @@ -36,91 +35,21 @@ namespace bts.shell { public static string col_id(Columns col) => col.ToString(); - public override Task load(StartupData state) => + public override Task load(TimeAndSalesSettings state) => Task.FromResult(new TimeAndSalesWindow(this, _bus, _consumer, state, SparkCommands.PickTimeAndSales.icon, - new WindowSettingsManager(_settings_hub, state.grid, s => s.time_and_sales_grid, (s, g) => s.with(time_and_sales:g)))); + new WindowSettingsManager(_settings_hub, state.grid, s => s.time_and_sales_grid, (s, g) => s.with(time_and_sales:g)), + _time_and_sales_conf.can_pause_updates)); public async void show(SecurityCriteria criteria) { - var w = await load(new StartupData(criteria)); + var w = await load(new TimeAndSalesSettings(criteria)); _bus.post(SparkTags.ShowWindow, w); } - [ProtoContract] - public class StartupData { - [ProtoMember(1)] - public readonly SecurityCriteria security_criteria; - [ProtoMember(2)] - List _sorting_criterion; - [ProtoMember(3)] - public FilterStates filters; - [ProtoMember(4)] - public GridSettings grid; + readonly struct TimeAndSalesConfig { + public readonly bool can_pause_updates; - public StartupData() { } - - public StartupData(SecurityCriteria security_criteria) : - this(security_criteria, new FilterStates(), null, null) { } - - public StartupData(SecurityCriteria security_criteria, FilterStates filters, GridSettings grid = default, List sorting_criterion = null) { - this.security_criteria = security_criteria; - this.filters = filters; - this.grid = grid; - _sorting_criterion = sorting_criterion; - } - - public static GridSettings DefaultGridSettings => GridSettings.Default.with(DefaultColumns.all, DefaultColumns.default_sorting_criterion); - - public List sorting_criterion => _sorting_criterion ?? (_sorting_criterion = DefaultColumns.default_sorting_criterion.ToList()); - - public static StartupData Default(SecurityCriteria security_criteria) => - new StartupData(security_criteria, new FilterStates(), null, DefaultColumns.default_sorting_criterion.ToList()); - - public StartupData with(SecurityCriteria security_criteria) => - new StartupData(security_criteria, filters, grid); - - public static class DefaultColumns { - public static GridColumnSettings security => new GridColumnSettings(col_id(Columns.Security), DefaultColumnHeaders.Security, width: DefaultColumnWidths.Security); - public static GridColumnSettings time => new GridColumnSettings(col_id(Columns.Time), DefaultColumnHeaders.Time, width: DefaultColumnWidths.Time); - public static GridColumnSettings price => new GridColumnSettings(col_id(Columns.Price), DefaultColumnHeaders.Price, width: DefaultColumnWidths.Price, horizontal_alignment: System.Windows.HorizontalAlignment.Right); - public static GridColumnSettings size => new GridColumnSettings(col_id(Columns.Size), DefaultColumnHeaders.Size, width: DefaultColumnWidths.Size, horizontal_alignment: System.Windows.HorizontalAlignment.Right); - public static GridColumnSettings aggressor => new GridColumnSettings(col_id(Columns.Aggressor), DefaultColumnHeaders.Aggressor, width: DefaultColumnWidths.Aggressor); - public static GridColumnSettings security_key => new GridColumnSettings(col_id(Columns.SecurityKey), DefaultColumnHeaders.SecurityKey, is_visible:false, width: DefaultColumnWidths.SecurityKey); - - public static IEnumerable default_sorting_criterion { - get { - yield return new SortingCriteria(time.id, false); - } - } - - public static IEnumerable all { - get { - yield return security; - yield return time; - yield return price; - yield return size; - yield return aggressor; - yield return security_key; - } - } - } - } - - [ProtoContract] - public class FilterStates { - [ProtoMember(1)] - public TimeFilterTuple time; - [ProtoMember(2)] - public string security; - [ProtoMember(3)] - public DoubleMinMaxState price; - [ProtoMember(4)] - public UIntMinMaxState size; - // [ProtoMember(5)] - // ProtoMember 5 cannot be used further - [ProtoMember(6)] - public string security_key; - [ProtoMember(7)] - public co2.AggressorSide[] aggressor_sides; + public TimeAndSalesConfig(bts.config.TimeAndSalesOptions options) => + can_pause_updates = options.can_pause_updates; } } -} \ No newline at end of file +} diff --git a/src/client/spark/Modules/Spreader/SyntheticManagementView.xaml.cs b/src/client/spark/Modules/Spreader/SyntheticManagementView.xaml.cs index e74b52c18..178c0c665 100644 --- a/src/client/spark/Modules/Spreader/SyntheticManagementView.xaml.cs +++ b/src/client/spark/Modules/Spreader/SyntheticManagementView.xaml.cs @@ -20,5 +20,5 @@ namespace mbts.ui.spark { InitializeComponent(); } - class SyntheticManagementRowView : DIYGrid.HighPerformanceRow { } + class SyntheticManagementRowView : DIYGrid.HighPerformanceRow { } } \ No newline at end of file diff --git a/src/client/spark/Modules/Spreader/SyntheticManagementWindow.cs b/src/client/spark/Modules/Spreader/SyntheticManagementWindow.cs index e7b449de9..40c515b61 100644 --- a/src/client/spark/Modules/Spreader/SyntheticManagementWindow.cs +++ b/src/client/spark/Modules/Spreader/SyntheticManagementWindow.cs @@ -3,6 +3,7 @@ using bts.api; using bts.shell; using bts.shell.spreader; using bts.spark; +using bts.view; using mbts.persist; using mbts.ui; using mbts.ui.settings; @@ -27,6 +28,7 @@ namespace mbts.spark { StartupData _state; OrdersModel _orders_model; SyntheticManagementView _view; + SparkMenuDisplayVM _menu_display_vm; IDisposable _subscriptions; IReadOnlyList _commands; readonly IWindowSettingsManager _settings_manager; @@ -43,7 +45,7 @@ namespace mbts.spark { public override string window_type => _window_type; public override UIElement Content => _view; public override IEnumerable Commands => _commands; - public override StartupData SaveState => _state = _vm.value.create(); + public override StartupData SaveState => _state = _vm.value.create().with(menu_display: _menu_display_vm.safe_create()); public override double MinWidth => StartupData.DefaultGridSettings.columns.Sum(gcs => gcs.width) + SPARK_MENU_COLLAPSED_WIDTH @@ -53,6 +55,8 @@ namespace mbts.spark { public void thread_init() { Log.notnull(_state); + _menu_display_vm = new SparkMenuDisplayVM(); + _menu_display_vm.load_from(_state.menu_display); var vm_connectable_builder = new ConnectableSeriesBuilder(_vm.observable); var current_row_source = vm_connectable_builder.create(vm => vm.current_row_observable); @@ -97,7 +101,8 @@ namespace mbts.spark { new SparkCommandCommand( "Import Synthetics...", Icons.Import, FileDialogCommand.open_file(import, extensions: SyntheticSecurityParser.file_extension)) { show_in_toolbar = false - } + }, + _menu_display_vm.spark_cmd }; _subscriptions = Disposable.Create( @@ -129,6 +134,9 @@ namespace mbts.spark { Commands.OfType().DisposeAll(); } + protected override void OnParentViewCreated(SparkWindowView parent_view) => + _menu_display_vm.safe_bind_to_view(parent_view); + struct RowModificationParams { public readonly SecurityImmutable security; public readonly bool has_working_orders; diff --git a/src/client/spark/Modules/Spreader/SyntheticManagementWindowFactory.cs b/src/client/spark/Modules/Spreader/SyntheticManagementWindowFactory.cs index 29125b873..a853bc73f 100644 --- a/src/client/spark/Modules/Spreader/SyntheticManagementWindowFactory.cs +++ b/src/client/spark/Modules/Spreader/SyntheticManagementWindowFactory.cs @@ -48,14 +48,28 @@ namespace bts.shell { public readonly FilterStates filters; [ProtoMember(3)] public readonly GridSettings grid; + [ProtoMember(4)] + public readonly SparkMenuDisplaySettings menu_display; public StartupData() : this(new List(), null, null) { } - public StartupData(List sorting_criteria, FilterStates filters, GridSettings grid = default) { + + public StartupData(List sorting_criteria, FilterStates filters, GridSettings grid = default) + : this(sorting_criteria, filters, grid, SparkMenuDisplaySettings.Default) { } + + public StartupData(List sorting_criteria, FilterStates filters, GridSettings grid, SparkMenuDisplaySettings menu_display) { this.sorting_criteria = sorting_criteria; this.filters = filters; this.grid = grid; + this.menu_display = menu_display; } + public StartupData with(List sorting_criteria = null, FilterStates filters = null, GridSettings grid = null, SparkMenuDisplaySettings? menu_display = null) => + new StartupData( + sorting_criteria ?? this.sorting_criteria, + filters ?? this.filters, + grid ?? this.grid, + menu_display ?? this.menu_display); + public static GridSettings DefaultGridSettings => GridSettings.Default.with(DefaultColumns.all, DefaultColumns.default_sorting_criterion); static class DefaultColumns { diff --git a/src/client/spark/Modules/Trading/AlgoStudio/AlgoStudioView.xaml b/src/client/spark/Modules/Trading/AlgoStudio/AlgoStudioView.xaml index 07fbecf35..2f579040a 100644 --- a/src/client/spark/Modules/Trading/AlgoStudio/AlgoStudioView.xaml +++ b/src/client/spark/Modules/Trading/AlgoStudio/AlgoStudioView.xaml @@ -25,6 +25,7 @@ 8 12 + @@ -130,22 +131,6 @@ - - - - - - - - - - - - - - - - @@ -153,13 +138,19 @@ + + + + @@ -173,275 +164,176 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Name: - - - - - - - Specify an abbreviation for this algo to use in ladder algo 'favorite' buttons. - - Hint: To add/remove algos from 'favorites', open the ladder settings dialog and select the 'Algo Favorites' tab. - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Select an existing algo to edit from the list to the left. + + Or click the + + button to create a new one. + + + + + + + + + + + + + + + - - - - + + + diff --git a/src/client/spark/Modules/Trading/AlgoStudio/AlgoStudioView.xaml.cs b/src/client/spark/Modules/Trading/AlgoStudio/AlgoStudioView.xaml.cs index f142e44a4..9a129679a 100644 --- a/src/client/spark/Modules/Trading/AlgoStudio/AlgoStudioView.xaml.cs +++ b/src/client/spark/Modules/Trading/AlgoStudio/AlgoStudioView.xaml.cs @@ -19,6 +19,17 @@ namespace mbts.ui.spark { Dispatcher.InvokeAsync(() => Keyboard.Focus(name_text_box)); } + void _on_badge_color_picker_activated(object sender, MouseButtonEventArgs e) => + _on_badge_color_picker_activated(); + + void _on_badge_color_picker_activated(object sender, KeyboardFocusChangedEventArgs e) => + _on_badge_color_picker_activated(); + + void _on_badge_color_picker_activated() { + if (DataContext is AlgoStudioVM vm && vm.selected_definition != null) + vm.selected_definition.custom_badge_color.enabled = true; + } + public static class VisualStateNames { public static class EditPane { public const string GroupName = nameof(EditPane); @@ -44,8 +55,7 @@ namespace mbts.ui.spark { public static readonly string Populated = $"{GroupName}{nameof(Populated)}", - Unpopulated = $"{GroupName}{nameof(Unpopulated)}", - NotSupportedForTemplates = $"{GroupName}{nameof(NotSupportedForTemplates)}"; + Unpopulated = $"{GroupName}{nameof(Unpopulated)}"; } public static class BadgeSelector { diff --git a/src/client/spark/Modules/Trading/AlgoStudio/AlgoStudioWindow.cs b/src/client/spark/Modules/Trading/AlgoStudio/AlgoStudioWindow.cs index 3edb390a9..bcc023fdd 100644 --- a/src/client/spark/Modules/Trading/AlgoStudio/AlgoStudioWindow.cs +++ b/src/client/spark/Modules/Trading/AlgoStudio/AlgoStudioWindow.cs @@ -9,6 +9,7 @@ using System.Collections.Generic; using System.Linq; using System.Reactive.Disposables; using System.Reactive.Linq; +using System.Threading.Tasks; using System.Windows; using StartupData = bts.shell.AlgoStudioWindowFactory.StartupData; @@ -68,23 +69,12 @@ namespace mbts.spark { .Subscribe(sec_map => _view.Resources[ResourceKeys.Securities] = sec_map)); // add definition _commands.Add(new SparkCommandCommand("Add Algo", Icons.AddBoxes, _vm.add_definition_cmd)); - // clone definition - var clone_selected_definition_spark_cmd = new SparkCommandCommand(string.Empty, Icons.DocumentCopy, _vm.clone_selected_definition_cmd); - _commands.Add(clone_selected_definition_spark_cmd); - _resources.Add(_vm.subscribe_definition().OnDispatcher().Subscribe( - def => clone_selected_definition_spark_cmd.title = def == null ? $"Clone (None Selected)" : $"Clone '{def.name}'")); - // save - if (_ui_configuration.can_save_specific) { - var content_is_dirty_src = _vm.subscribe_definition().SelectManyInSeries(def => def?.subscribe_is_definition_dirty() ?? Observable.Return(false)); - _commands.Add(new ReactiveSparkCommand(_vm.subscribe_definition().OnDispatcher().Select(c => $"Save '{c?.name}'"), Icons.DiskFile, () => { - if (_vm.selected_definition is AlgoDefinitionVM d) - _vm.save_definition(d).ignore(); - }, content_is_dirty_src)); - } - // save all - var save_all_cmd = new ObservantAsyncCommand(_vm.save_all); - _commands.Add(new SparkCommandCommand("Save All", Icons.Disk, save_all_cmd)); - _resources.Add(_vm.subscribe_dirty().OnDispatcher().Subscribe(save_all_cmd)); + _commands.Add(new SparkCommandCommand("Clone Algo", Icons.CopyBoxes, _vm.clone_selected_definition_cmd)); + _commands.Add(new SparkCommandCommand("Save Algo", Icons.DiskFile, _vm.save_cmd) { + show_in_toolbar = _ui_configuration.can_save_specific + }); + _commands.Add(new SparkCommandCommand("Save All", Icons.Disk, ObservantAsyncCommand.create(_vm.save_all, out var save_all_observer))); + _resources.Add(_vm.subscribe_dirty().OnDispatcher().Subscribe(save_all_observer)); // undo/redo if (_ui_configuration.can_undo_redo) { // undo @@ -117,30 +107,11 @@ namespace mbts.spark { _resources.Add(can_redo_source.Subscribe(redo_cmd)); } // remove - var remove_spark_cmd = new ObservantSparkCommandCommand(Icons.Trash, v => $"Remove '{v?.name}'", v => v != null, value => { - if (value is AlgoDefinitionVM d) { - string prompt; MessageBoxImage icon; - if (d.key.mode == AlgoKey.Mode.Persisted) { - prompt = $"Are you sure you want to delete '{d.name}?'"; - icon = MessageBoxImage.Question; - } else { - // algo hasn't even been created yet (just an unsaved placeholder item), no need to get user confirmation in this case. - prompt = null; - icon = default; - } - if (prompt != null) { - var resp = BTSMessageBox.Show(prompt, "Algo Studio", BTSMessageBoxButtons.Yes | BTSMessageBoxButtons.No, icon); - switch (resp) { - case BTSMessageBoxButtons.Yes: break; - case BTSMessageBoxButtons.No: - default: return; - } - } - _vm.remove_definition(d).ignore(); - } - }); - _commands.Add(remove_spark_cmd); - _resources.Add(_vm.subscribe_definition().OnDispatcher().Subscribe(remove_spark_cmd)); + _commands.Add(new SparkCommandCommand("Remove Algo", Icons.Trash, ObservantAsyncCommand.create( + vm => BTSMessageBox.Confirm($"Are you sure you want to delete '{vm.name}?'", Title) ? _vm.remove_definition(vm) : Task.CompletedTask, + vm => vm != null, + out var remove_cmd_observer))); + _resources.Add(_vm.subscribe_definition().OnDispatcher().Subscribe(remove_cmd_observer)); } void _dispose_core() { @@ -149,4 +120,4 @@ namespace mbts.spark { Disposable.dispose(ref _vm); } } -} \ No newline at end of file +} diff --git a/src/client/spark/Modules/Trading/AlgoStudio/Model/AlgoStudioFlatDefinitionModel.cs b/src/client/spark/Modules/Trading/AlgoStudio/Model/AlgoStudioFlatDefinitionModel.cs index aec98c8cd..5702a504f 100644 --- a/src/client/spark/Modules/Trading/AlgoStudio/Model/AlgoStudioFlatDefinitionModel.cs +++ b/src/client/spark/Modules/Trading/AlgoStudio/Model/AlgoStudioFlatDefinitionModel.cs @@ -6,7 +6,6 @@ using mbts.utils; using System; using System.Collections.Generic; using System.ComponentModel.Composition; -using System.Reactive.Linq; using System.Threading.Tasks; namespace mbts.spark { @@ -16,7 +15,6 @@ namespace mbts.spark { readonly AdminModel _admin_model; readonly ErrorReporter _error_reporter; IReadOnlyDictionary _algos = DictionaryHelper.empty(); - IReadOnlyDictionary _algo_templates = DictionaryHelper.empty(); IDisposable _dispose; [ImportingConstructor] @@ -34,17 +32,13 @@ namespace mbts.spark { } public IObservable> definitions { get; } - public IObservable> templates => Observable.Empty>(); public IAlgoDefinitionMetadataService metadata_service { get; } public bts.config.AlgoStudioOptions ui_configuration { get; } = config.Configuration.get(); - public IObservable> subscribe_definition_templates(AlgoKey definition_key) => - Observable.Return(TableUpdate.mk_empty(t => t.key)); - public async Task save_definition(AlgoData definition_data) { var (value, success) = await _error_reporter.safe_execute(() => _service.save_algo_definition_async( - _with_key(new AlgoDefinitionUpdateRequest { UserId = _admin_model.user.id, Algo = _template(definition_data) }, definition_data.key)), - r => r.Success, r => r.ErrorMessage, "saving template"); + _with_key(new AlgoDefinitionUpdateRequest { UserId = _admin_model.user.id, Algo = _api_definition(definition_data) }, definition_data.key)), + r => r.Success, r => r.ErrorMessage, "saving definition"); if (success) return _definition_data(new AlgoDefinitionRecordImmutable(value.Record)); return null; @@ -53,23 +47,22 @@ namespace mbts.spark { public async Task remove_definition(AlgoKey definition_key) { var req = new AlgoDefinitionRemoveRequest(); _set_key(ref req, definition_key); - (AlgoDefinitionRemoveResponse resp, bool success) = await _error_reporter.safe_execute(() => _service.remove_algo_definition_async(req), r => r.Success, r => r.ErrorMessage, "remove template"); + (AlgoDefinitionRemoveResponse resp, bool success) = await _error_reporter.safe_execute( + () => _service.remove_algo_definition_async(req), + r => r.Success, + r => r.ErrorMessage, + "remove definition"); return success; } - public Task save_template(AlgoTemplateData template_data) => Task.FromResult((AlgoTemplateData?)null); - - public Task remove_template(AlgoKey key) => - Task.FromResult(false); - public void Dispose() => Disposable.dispose(ref _dispose); - static AlgoDefinition _template(AlgoData definition_data) => + static AlgoDefinition _api_definition(AlgoData definition_data) => new AlgoDefinition { Name = definition_data.name, Definition = definition_data.value.CloneToMutable() }; - static AlgoDefinitionImmutable _templatei(AlgoData definition_data) => - new AlgoDefinitionImmutable(_template(definition_data)); + static AlgoDefinitionImmutable _api_definitioni(AlgoData definition_data) => + new AlgoDefinitionImmutable(_api_definition(definition_data)); static AlgoData _definition_data(AlgoDefinitionRecordImmutable recordi) => AlgoData.from_record(recordi); @@ -99,11 +92,5 @@ namespace mbts.spark { default: throw ExceptionBuilder.Argument.unexpected_case(key.mode, nameof(key)); } } - - void _report_error(string present_progressive_desc, string msg) => - _error_reporter.report_error($"Error {present_progressive_desc}: {msg}", AlgoStudioWindow.NAME, System.Windows.MessageBoxImage.Warning); - - void _report_no_user_id(string desc) => - _error_reporter.report_error($"{desc} failed: did not find current user id"); } } \ No newline at end of file diff --git a/src/client/spark/Modules/Trading/AlgoStudio/Model/IAlgoStudioModel.cs b/src/client/spark/Modules/Trading/AlgoStudio/Model/IAlgoStudioModel.cs index acbcdffb5..39633e8a8 100644 --- a/src/client/spark/Modules/Trading/AlgoStudio/Model/IAlgoStudioModel.cs +++ b/src/client/spark/Modules/Trading/AlgoStudio/Model/IAlgoStudioModel.cs @@ -7,13 +7,9 @@ using System.Threading.Tasks; namespace mbts.spark { interface IAlgoStudioModel { IObservable> definitions { get; } - IObservable> templates { get; } - IObservable> subscribe_definition_templates(AlgoKey definition_key); IAlgoDefinitionMetadataService metadata_service { get; } Task save_definition(AlgoData definition_data); - Task save_template(AlgoTemplateData template_data); Task remove_definition(AlgoKey definition_key); - Task remove_template(AlgoKey template_key); bts.config.AlgoStudioOptions ui_configuration { get; } } diff --git a/src/client/spark/Modules/Trading/AlgoStudio/VM/AlgoDefinitionVM.cs b/src/client/spark/Modules/Trading/AlgoStudio/VM/AlgoDefinitionVM.cs index 6c29af115..dd8563fa0 100644 --- a/src/client/spark/Modules/Trading/AlgoStudio/VM/AlgoDefinitionVM.cs +++ b/src/client/spark/Modules/Trading/AlgoStudio/VM/AlgoDefinitionVM.cs @@ -68,7 +68,13 @@ namespace mbts.spark { editing_permissions_mask ^= (AlgoEditingPermissions.AllowEditStructure | AlgoEditingPermissions.AllowSaveStructure); key = def_data.key; algos_view = ObservableAutoWrapper.create_sorted_wrapper(_algo_roots, AlgoCollectionHelper.algo_vm_comparer); - custom_badge_color_palettes.AddRange(ColorPalette.all_presets(model.factory).Select(p => new ColorPaletteVM(p))); + // badge color picker palettes + custom_badge_color_palettes.AddRange(ColorPalette.all_presets().Select(p => new ColorPaletteVM(p))); + var root_algo_color_item = new NamedColorVM(new NamedColor { name = "(Root Algo Type)" }, false); + var algo_type_color_palette = new ColorPaletteVM(ColorPalette.factory_order_colors_palette(model.factory)); + algo_type_color_palette.named_colors.Insert(0, root_algo_color_item); + custom_badge_color_palettes.Insert(0, algo_type_color_palette); + // _version = new VersionContainer(_snapshot); var conf = _model.algo_model.ui_configuration; // init backing props @@ -91,6 +97,7 @@ namespace mbts.spark { _can_undo = backing(nameof(can_undo), () => _edit_stack.get_can_undo(_version.value)); _can_redo.Changed += on_can_redo_changed; _can_undo.Changed += on_can_undo_changed; + custom_badge_color.enabled_changed += on_use_custom_badge_color_changed; _refresh_on_local_changes = new DeferrableActionWrapper(on_local_changed); // load initial state // visible_algo_root is selected_template.algo_root if user can add templates, otherwise algo_root @@ -103,16 +110,13 @@ namespace mbts.spark { as_demuxer().subscribe_many(_refresh_on_local_changes.execute, nameof(this.name), nameof(abbreviation), nameof(badge_fill)), _edit_pane_vs_model.add_source(VisualStateNames.BadgeSelector.GroupName, custom_badge_color.observe_nullable(true).Select(t => t.HasValue ? VisualStateNames.BadgeSelector.Active : VisualStateNames.BadgeSelector.Inactive)), _edit_pane_vs_model.add_source(VisualStateNames.Abbreviation.GroupName, _abbreviation.observe_current(true).Select(a => string.IsNullOrEmpty(a) ? VisualStateNames.Abbreviation.Unpopulated : VisualStateNames.Abbreviation.Populated)), - _algo_root.observe_current(true).SubscribeEach(vm => - vm == null ? null : - Disposable.Create( - vm.subscribe_is_dirty().Subscribe(v => { - if (!v) { - _version.increment_version(); - _on_committed_changed(); - } - }), - vm.subscribe_definition().Subscribe(_ => _refresh_on_local_changes.execute()))), + _algo_root.observe_current(true).SubscribeEach(vm => { + if (vm != null) { + root_algo_color_item.assign_color(vm.meta.Color.argb_color()); + return vm.subscribe_definition().Subscribe(_ => _refresh_on_local_changes.execute()); + } + return null; + }), ObservableAutoWrapper.connect_item_hooks(algo_roots, a => a as IDisposable ?? Disposable.empty, true), Disposable.Create(() => { _can_redo.Changed -= on_can_redo_changed; @@ -153,6 +157,10 @@ namespace mbts.spark { // local methods void on_can_redo_changed(bool oldval, bool newval) => can_redo_changed?.Invoke(); void on_can_undo_changed(bool oldval, bool newval) => can_undo_changed?.Invoke(); + void on_use_custom_badge_color_changed() { + if (!custom_badge_color.enabled && algo_root != null) + custom_badge_color.value = algo_root.meta.Color.argb_color(); + } void on_local_changed() { _version.increment_version(); if (algo_root != null) @@ -190,6 +198,7 @@ namespace mbts.spark { public AlgoDisplayGroup group => key.display_group(); public bool can_redo => _can_redo.Value; public bool can_undo => _can_undo.Value; + //public bool use_custom_badge_color public EnabledValueVM custom_badge_color { get; } = new EnabledValueVM(); public ObservableCollection custom_badge_color_palettes { get; } = new ObservableCollection(); public Brush badge_fill => _badge_fill; diff --git a/src/client/spark/Modules/Trading/AlgoStudio/VM/AlgoStudioVM.cs b/src/client/spark/Modules/Trading/AlgoStudio/VM/AlgoStudioVM.cs index d2ff6af6b..ef817d6cc 100644 --- a/src/client/spark/Modules/Trading/AlgoStudio/VM/AlgoStudioVM.cs +++ b/src/client/spark/Modules/Trading/AlgoStudio/VM/AlgoStudioVM.cs @@ -13,7 +13,6 @@ using System.Linq; using System.Reactive.Disposables; using System.Reactive.Linq; using System.Threading.Tasks; -using System.Windows; using System.Windows.Input; using StartupData = bts.shell.AlgoStudioWindowFactory.StartupData; @@ -82,18 +81,19 @@ namespace mbts.spark { _persisted_meta = meta; definitions_view.Refresh(); }), - ObservableAutoWrapper.connect(subscribe_definition().Select(def => def?.edit_pane_visual_states ?? new ObservableCollection()), content_visual_states), subscribe_definition().SelectManyInSeries(def => def?.subscribe_is_definition_dirty() ?? Observable.Return(false)).OnDispatcher() - .Subscribe(new CompositeObserver(save_cmd, revert_cmd) { val => { - _save_cmd_tooltip.refresh(); - _revert_cmd_tooltip.refresh(); - } }), + .Subscribe(new CompositeObserver(save_cmd, revert_cmd) { + val => { + _save_cmd_tooltip.refresh(); + _revert_cmd_tooltip.refresh(); + } + }), ObservableAutoWrapper.connect_item_hooks(definitions, d => new CompositeDisposable(_any_dirty_monitor.join(d), d), true)); // local methods string get_revert_tooltip() { var def = selected_definition; return def != null && def.key.mode == AlgoKey.Mode.Persisted ? - (def.is_dirty ? $"Revert changes to '{def.name}' templates" : "No changes to revert") : + (def.is_dirty ? $"Revert changes to '{def.name}'" : "No changes to revert") : null; } async Task save_async(IAlgoStudioContentVM content) { @@ -105,7 +105,7 @@ namespace mbts.spark { if (def != null) { switch (def.key.mode) { case AlgoKey.Mode.Unpersisted: return def.is_dirty ? $"Save '{def.name}'" : $"Cannot Save '{def.name}'"; - case AlgoKey.Mode.Persisted: return def.is_dirty ? $"Save changes to '{def.name}' templates" : "No changes to save"; + case AlgoKey.Mode.Persisted: return def.is_dirty ? $"Save changes to '{def.name}'" : "No changes to save"; } } return null; diff --git a/src/client/spark/Modules/Trading/Fills/FillsView.xaml.cs b/src/client/spark/Modules/Trading/Fills/FillsView.xaml.cs index 9e34bc3e9..16324ad77 100644 --- a/src/client/spark/Modules/Trading/Fills/FillsView.xaml.cs +++ b/src/client/spark/Modules/Trading/Fills/FillsView.xaml.cs @@ -31,5 +31,5 @@ namespace mbts.ui.spark { InitializeComponent(); } - class FillsRowView : DIYGrid.HighPerformanceRow { } + class FillsRowView : DIYGrid.HighPerformanceRow { } } \ No newline at end of file diff --git a/src/client/spark/Modules/Trading/Fills/FillsWindow.cs b/src/client/spark/Modules/Trading/Fills/FillsWindow.cs index 1b2b66464..8b1e6b35f 100644 --- a/src/client/spark/Modules/Trading/Fills/FillsWindow.cs +++ b/src/client/spark/Modules/Trading/Fills/FillsWindow.cs @@ -3,6 +3,7 @@ using bts.api; using bts.shell; using bts.shell.fills; using bts.spark; +using bts.view; using mbts.persist; using mbts.ui; using mbts.ui.settings; @@ -24,6 +25,7 @@ namespace mbts.spark { FillsVM _vm; FillsView _view; FillsSettings _state; + SparkMenuDisplayVM _menu_display_vm; IReadOnlyList _commands; public FillsWindow(FillsWindowFactory factory, IBus bus, OrdersModel orders_model, FillsSettings state, WindowSettingsManager settings_manager) @@ -38,7 +40,10 @@ namespace mbts.spark { public override UIElement Content => _view; public override IEnumerable Commands => _commands; - public override FillsSettings SaveState => _state = new FillsSettings(_state.orders, _vm.get_sorting_criterion().ToList(), _vm.get_filters(), _vm.get_grid_save_state()); + public override FillsSettings SaveState => _state = new FillsSettings(_state.orders, _vm.get_sorting_criterion().ToList(), _vm.get_filters(), _vm.get_grid_save_state()) { + menu_display = _menu_display_vm.safe_create() + }; + public override double MinWidth => FillsSettings.DefaultGridSettings.columns.Sum(gcs => gcs.width) + SPARK_MENU_COLLAPSED_WIDTH @@ -50,6 +55,8 @@ namespace mbts.spark { public void thread_init() { _init_guard.check_access(); Log.notnull(_state); + _menu_display_vm = new SparkMenuDisplayVM(); + _menu_display_vm.load_from(_state.menu_display); _vm = new FillsVM(_bus, _orders_model, _state, _settings_manager); _view = new FillsView { DataContext = _vm }; @@ -70,7 +77,8 @@ namespace mbts.spark { var dialog = new ShellSettingsDialog { DataContext = vm }; vm.RequestClose += (s, e) => WindowUtilities.force_close(dialog); return dialog; - })) + })), + _menu_display_vm.spark_cmd }; } @@ -78,5 +86,8 @@ namespace mbts.spark { Disposable.dispose(ref _vm); Commands.OfType().DisposeAll(); } + + protected override void OnParentViewCreated(SparkWindowView parent_view) => + _menu_display_vm.safe_bind_to_view(parent_view); } } diff --git a/src/client/spark/Modules/Trading/Fills/Settings/FillsSettings.cs b/src/client/spark/Modules/Trading/Fills/Settings/FillsSettings.cs index d6a24363d..877fc7483 100644 --- a/src/client/spark/Modules/Trading/Fills/Settings/FillsSettings.cs +++ b/src/client/spark/Modules/Trading/Fills/Settings/FillsSettings.cs @@ -21,6 +21,8 @@ namespace bts.shell.fills { public FillsFilterStates filters; [ProtoMember(4)] public GridSettings grid; + [ProtoMember(5)] + public SparkMenuDisplaySettings menu_display; public FillsSettings() { } public FillsSettings(uint[] orders) : this(orders, null, null) { } diff --git a/src/client/spark/Modules/Trading/Ladder/LadderSettings.cs b/src/client/spark/Modules/Trading/Ladder/LadderSettings.cs index fcb66670d..6b9e9c4b5 100644 --- a/src/client/spark/Modules/Trading/Ladder/LadderSettings.cs +++ b/src/client/spark/Modules/Trading/Ladder/LadderSettings.cs @@ -1,15 +1,18 @@ using bts.api.orderman; -using mbts.ui; +using bts.collections; +using bts.persist.algo; +using bts.proto; using bts.utils; +using mbts.ui; +using mbts.ui.settings; +using mbts.ui.spark; using ProtoBuf; using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.ComponentModel; using System.Linq; using System.Windows; -using bts.proto; -using mbts.ui.spark; -using System.Collections.Generic; -using System.ComponentModel; -using mbts.ui.settings; namespace mbts.spark { // IMPORTANT: BE SURE TO ADD ANY NEW PROPERTIES TO THE EQUALS FUNCTION! @@ -182,33 +185,97 @@ namespace mbts.spark { _type_hash; } + [Flags] + enum LadderFavoriteAlgoFlags { + Sticky = 1, + AutoRevert = 2, + } + + /// + /// This struct contains properties for a single algo favorite item. + /// The various arrays in , + /// can be used to create a collection of s. + /// In fact, the method does just that. + /// + readonly struct LadderFavoriteAlgoItem : IEquatable { + public readonly AlgoKey key; + public readonly int sort_index; + public readonly LadderFavoriteAlgoFlags flags; + + public LadderFavoriteAlgoItem(AlgoKey key, int sort_index, LadderFavoriteAlgoFlags flags) { + this.key = key; + this.sort_index = sort_index; + this.flags = flags; + } + + public bool Equals(LadderFavoriteAlgoItem other) => + key == other.key && + flags == other.flags; + + public override bool Equals(object obj) => + obj is LadderFavoriteAlgoItem other && Equals(other); + + public override int GetHashCode() => + key.GetHashCode(); + } + [ProtoContract] struct LadderFavoriteAlgosSettings : IEquatable { [ProtoMember(1)] - readonly bts.persist.algo.AlgoPersistedKey[] _favorite_algos; + readonly AlgoPersistedKey[] _favorite_algos; [ProtoMember(2)] public readonly int column_count; [ProtoMember(3)] - readonly bts.persist.algo.AlgoPersistedKey[] _stickied_algos; + readonly AlgoPersistedKey[] _stickied_algos; + [ProtoMember(4)] + readonly AlgoPersistedKey[] _auto_revert_algos; - public LadderFavoriteAlgosSettings(AlgoKey[] favorite_algos, int column_count, AlgoKey[] stickied_algos) - : this(ArrayHelper.safe_convert(favorite_algos, k => new bts.persist.algo.AlgoPersistedKey(k.persisted)), - column_count, - ArrayHelper.safe_convert(stickied_algos, k => new bts.persist.algo.AlgoPersistedKey(k.persisted))) { } + public LadderFavoriteAlgosSettings(AlgoKey[] favorite_algos, int column_count, AlgoKey[] stickied_algos, AlgoKey[] auto_revert_algos) + : this(ArrayHelper.safe_convert(favorite_algos, k => new AlgoPersistedKey(k.persisted)), + ArrayHelper.safe_convert(stickied_algos, k => new AlgoPersistedKey(k.persisted)), + ArrayHelper.safe_convert(auto_revert_algos, k => new AlgoPersistedKey(k.persisted)), + column_count) { } - LadderFavoriteAlgosSettings(bts.persist.algo.AlgoPersistedKey[] favorite_algos, int column_count, bts.persist.algo.AlgoPersistedKey[] stickied_algos) { + LadderFavoriteAlgosSettings(AlgoPersistedKey[] favorite_algos, AlgoPersistedKey[] stickied_algos, AlgoPersistedKey[] auto_revert_algos, int column_count) { _favorite_algos = favorite_algos; - this.column_count = column_count; _stickied_algos = stickied_algos; + _auto_revert_algos = auto_revert_algos; + this.column_count = column_count; } - public IReadOnlyList favorite_algos => ArrayHelper.safe_convert(_favorite_algos, k => k.to_algo_key()); - public IReadOnlyList stickied_algos => ArrayHelper.safe_convert(_stickied_algos, k => k.to_algo_key()); + public IReadOnlyList favorite_algos => _favorite_algos?.WrapSelectorRO(pk => pk.to_algo_key()) ?? Array.Empty(); + public IReadOnlyList stickied_algos => _stickied_algos?.WrapSelectorRO(pk => pk.to_algo_key()) ?? Array.Empty(); + public IReadOnlyList auto_revert_algos => _auto_revert_algos?.WrapSelectorRO(pk => pk.to_algo_key()) ?? Array.Empty(); + + /// + /// A more sane representation of the data contained in this proto, + /// so callers don't need to join the various key lists together to determine which algos are sticky, auto revert, etc. + /// + /// An immutable dictionary of favorite algo data. + public ImmutableDictionary build_map() { + var map = ImmutableDictionary.CreateBuilder(); + if (_favorite_algos != null) { + var stickied_algo_set = new HashSet(stickied_algos); + var auto_revert_algo_set = new HashSet(auto_revert_algos); + for (int i = 0; i < _favorite_algos.Length; i++) { + var pk = _favorite_algos[i]; + var k = pk.to_algo_key(); + var flags = (LadderFavoriteAlgoFlags)0; + if (stickied_algo_set.Contains(k)) + flags |= LadderFavoriteAlgoFlags.Sticky; + if (auto_revert_algo_set.Contains(k)) + flags |= LadderFavoriteAlgoFlags.AutoRevert; + map[k] = new LadderFavoriteAlgoItem(k, i, flags); + } + } + return map.ToImmutable(); + } public bool Equals(LadderFavoriteAlgosSettings other) => column_count == other.column_count && favorite_algos.SequenceEqual(other.favorite_algos) && - stickied_algos.SequenceEqual(other.stickied_algos); + stickied_algos.SequenceEqual(other.stickied_algos) && + auto_revert_algos.SequenceEqual(other.auto_revert_algos); public override bool Equals(object obj) => EqualityComparer.equals_obj(this, obj); @@ -217,7 +284,8 @@ namespace mbts.spark { EqualityComparer.aggregate_hash( column_count, EqualityComparer.aggregate_hash_limited(favorite_algos), - EqualityComparer.aggregate_hash_limited(stickied_algos)); + EqualityComparer.aggregate_hash_limited(stickied_algos), + EqualityComparer.aggregate_hash_limited(auto_revert_algos)); public static bool operator ==(LadderFavoriteAlgosSettings a, LadderFavoriteAlgosSettings b) => a.Equals(b); public static bool operator !=(LadderFavoriteAlgosSettings a, LadderFavoriteAlgosSettings b) => !a.Equals(b); @@ -281,7 +349,7 @@ namespace mbts.spark { order_entry_panel_initial_width = _default_order_entry_panel_width; zoom_factor = _default_zoom_factor; use_defaults = true; - favorite_algos = new LadderFavoriteAlgosSettings(null, 2, null); + favorite_algos = new LadderFavoriteAlgosSettings(null, 2, null, null); show_warn_on_cross = _default_show_warn_on_cross; enforce_max_clip = _default_enforce_max_clip; status_message_visible = true; diff --git a/src/client/spark/Modules/Trading/Ladder/LadderWindowFactory.cs b/src/client/spark/Modules/Trading/Ladder/LadderWindowFactory.cs index 2f3b64e92..37b363142 100644 --- a/src/client/spark/Modules/Trading/Ladder/LadderWindowFactory.cs +++ b/src/client/spark/Modules/Trading/Ladder/LadderWindowFactory.cs @@ -70,7 +70,11 @@ namespace bts.shell { if (version < _version_where_stickied_algos_introduced) { // We want to assign any existing favorite algos to stickied algos upon setting upgrade var favorite_algos_array = state.settings.favorite_algos.favorite_algos.ToArray(); - state.settings.favorite_algos = new LadderFavoriteAlgosSettings(favorite_algos_array, state.settings.favorite_algos.column_count, favorite_algos_array); + state.settings.favorite_algos = new LadderFavoriteAlgosSettings( + favorite_algos_array, + state.settings.favorite_algos.column_count, + favorite_algos_array, + state.settings.favorite_algos.auto_revert_algos.ToArray()); } return load(state); } diff --git a/src/client/spark/Modules/Trading/Ladder/VM/LadderOrderVM.cs b/src/client/spark/Modules/Trading/Ladder/VM/LadderOrderVM.cs index 60f1ea13a..c6b296309 100644 --- a/src/client/spark/Modules/Trading/Ladder/VM/LadderOrderVM.cs +++ b/src/client/spark/Modules/Trading/Ladder/VM/LadderOrderVM.cs @@ -268,14 +268,15 @@ namespace mbts.spark { } } + // on Stop/Limit order updates + // When not triggered, allow for modification to StopPrice + // else treat modification as normal (Price) public async void try_set_price(OrderRecordImmutable order, double new_price) { - // don't change stop or stop_limits => server crash - if (order.order_type() == bts.api.orderman.CustomOrderDefinition.CustomOneofCase.Stop || order.order_type() == bts.api.orderman.CustomOrderDefinition.CustomOneofCase.StopLimit) return; if (order.working_quantity() <= 0) return; _phantom_price = new_price; RaisePropertyChanged(nameof(price)); ++_n_active_price_change_ops; - if (await _owner.model.order_gateway.update_order(order, new_price, order.State.Quantity)) { + if (await _owner.model.order_gateway.update_order(order, new_price, order.State.Quantity, null)) { // wait 3 secs, then give up if price change still hasn't taken effect await Task.Delay(3000); } diff --git a/src/client/spark/Modules/Trading/Ladder/VM/LadderSettingsVM.cs b/src/client/spark/Modules/Trading/Ladder/VM/LadderSettingsVM.cs index 48bb1ed72..9cca67ba1 100644 --- a/src/client/spark/Modules/Trading/Ladder/VM/LadderSettingsVM.cs +++ b/src/client/spark/Modules/Trading/Ladder/VM/LadderSettingsVM.cs @@ -15,6 +15,7 @@ using mbts.ui.utility; using mbts.utils; using System; using System.Collections.Generic; +using System.Collections.Immutable; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.ComponentModel; @@ -746,15 +747,17 @@ namespace mbts.spark { readonly IObservableCollection _algo_definitions; readonly ObservableCollection _raw_items = new ObservableCollection(); int _column_count = 2; - HashSet _sticky_algo_keys; - IDisposable _sticky_algos_hook; + ImmutableHashSet + _sticky_algo_keys, + _auto_revert_algo_keys; + IDisposable _algo_data_hook; public FavoriteAlgosVM(IObservableCollection algo_definitions) { _algo_definitions = algo_definitions; items = new ObservableAggregateCollection(_raw_items, new ObservableCollection { FavoriteAlgoItem.AddButtonPlaceholderItem }); add_item_cmd = new DelegateCommand(() => _raw_items.Add(_item_factory())); remove_item_cmd = new DelegateCommand(fai => _raw_items.Remove(fai)); - _dispose = Disposable.Create(() => Disposable.dispose(ref _sticky_algos_hook)); + _dispose = Disposable.Create(() => Disposable.dispose(ref _algo_data_hook)); } public ObservableCollection items { get; } @@ -771,32 +774,47 @@ namespace mbts.spark { fai.selector.try_select(k); return fai; })); - _sticky_algo_keys = new HashSet(value.stickied_algos.Where(k => k.is_persisted).Select(x => new AlgoPersistedKey(x.persisted))); - Disposable.replace(ref _sticky_algos_hook, - ObservableAutoWrapper.connect_item_hooks(_raw_items, x => - x.selector.subscribe_value().Subscribe(algo => { - if (algo != null && - algo.key.is_persisted && - (x.is_sticky = _sticky_algo_keys.Remove(new AlgoPersistedKey(algo.key.persisted))) && - _sticky_algo_keys.Count == 0) - // - Disposable.dispose(ref _sticky_algos_hook); - }))); + _algo_data_hook?.Dispose(); + _sticky_algo_keys = ImmutableHashSet.CreateRange(value.stickied_algos.Where(k => k.is_persisted).Select(x => new AlgoPersistedKey(x.persisted))); + _auto_revert_algo_keys = ImmutableHashSet.CreateRange(value.auto_revert_algos.Where(k => k.is_persisted).Select(x => new AlgoPersistedKey(x.persisted))); + var sticky_algos = _sticky_algo_keys; + var auto_revert_algos = _auto_revert_algo_keys; + _algo_data_hook = ObservableAutoWrapper.connect_item_hooks(_raw_items, x => + x.selector.subscribe_value().Subscribe(algo => { + if (algo != null && algo.key.is_persisted) { + var pk = new AlgoPersistedKey(algo.key.persisted); + // sticky + x.is_sticky = _sticky_algo_keys.Contains(pk); + sticky_algos = sticky_algos.Remove(pk); + // auto revert + x.auto_revert = _auto_revert_algo_keys.Contains(pk); + auto_revert_algos = auto_revert_algos.Remove(pk); + if (sticky_algos.Count == 0 && auto_revert_algos.Count == 0) + Disposable.dispose(ref _algo_data_hook); + } + })); } - public LadderFavoriteAlgosSettings create() => - new LadderFavoriteAlgosSettings(_raw_items + public LadderFavoriteAlgosSettings create() { + return new LadderFavoriteAlgosSettings(_raw_items .Select(fai => fai.algo_definition?.key ?? fai.selector.desired_key) .Where(k => k.HasValue && k.Value.is_persisted) .Select(k => k.Value) .ToArray(), column_count, + // sticky + build_filtered_algo_array(fai => fai.is_sticky), + // auto revert + build_filtered_algo_array(fai => fai.auto_revert)); + + AlgoKey[] build_filtered_algo_array(Func filter) => _raw_items - .Where(fai => fai.is_sticky) + .Where(filter) .Select(fai => fai.algo_definition?.key ?? fai.selector.desired_key) .Where(k => k.HasValue && k.Value.is_persisted) .Select(k => k.Value) - .ToArray()); + .ToArray(); + } FavoriteAlgoItem _item_factory() => new FavoriteAlgoItem(_algo_definitions, new ListCollectionView(_algo_definitions) { @@ -809,7 +827,9 @@ namespace mbts.spark { public static readonly FavoriteAlgoItem AddButtonPlaceholderItem = new _AddButtonPlaceholderItem(); internal readonly KeyedItemSelector selector; - bool _is_sticky; + bool + _auto_revert, + _is_sticky; protected FavoriteAlgoItem() { } @@ -820,6 +840,7 @@ namespace mbts.spark { public ICollectionView algo_definitions_view { get; } public AlgoDefinitionVM algo_definition { get => selector.value; set => selector.value = value; } + public bool auto_revert { get => _auto_revert; set => Set(ref _auto_revert, value); } public bool is_sticky { get => _is_sticky; set => Set(ref _is_sticky, value); } class _AddButtonPlaceholderItem : FavoriteAlgoItem, ITemplateSelectorKey { diff --git a/src/client/spark/Modules/Trading/Ladder/VM/LadderVM.cs b/src/client/spark/Modules/Trading/Ladder/VM/LadderVM.cs index 6538b59c7..78c72133c 100644 --- a/src/client/spark/Modules/Trading/Ladder/VM/LadderVM.cs +++ b/src/client/spark/Modules/Trading/Ladder/VM/LadderVM.cs @@ -11,6 +11,7 @@ using mbts.ui.shell; using mbts.utils; using System; using System.Collections.Generic; +using System.Collections.Immutable; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.Linq; @@ -34,7 +35,6 @@ namespace mbts.spark { _show_tif, _show_order_type, _show_size_preset, _show_auto_clear, _show_clear, _show_cancel_buys, _show_cancel_sells, _show_cancel_all, _show_zoom, _show_status_message; readonly PropertyAutoWrapper _bid_background, _bid_foreground, _ask_background, _ask_foreground; - readonly HashSet _sticky_algos = new HashSet(); double _position, _day_position, @@ -49,6 +49,7 @@ namespace mbts.spark { IEqualityComparer _equality; Dictionary _slot_price_vs_orders; IReadOnlyDictionary _cache = DictionaryHelper.empty(); + ImmutableDictionary _favorite_algo_map = ImmutableDictionary.Empty; public static LadderVM create(IBus bus, LadderModel model, LadderSettings init, IObservable settings) => new LadderVM(bus, model, init, settings, new OrderPropertiesEditorVM(model.order_gateway, Observable.Return(model.security_md), settings.Select(s => new InlineOrderProperties(model.order_gateway, s)))); @@ -168,17 +169,9 @@ namespace mbts.spark { foreach (var os in _cache.Values) { var wo = os.order; - var slot_price_target = wo.price(); + var slot_price_target = wo.ui_price(); var order_type = wo.order_type(); var filled = wo.filled(); - if (order_type == CustomOrderDefinition.CustomOneofCase.Stop) { - // if the stop order has been submitted but hasn't been triggered - // we draw the badge at the stop/trigger price, else the price price - if (filled == 0) { slot_price_target = wo.stop_price(); } - } else if (order_type == CustomOrderDefinition.CustomOneofCase.StopLimit) { - // consistent behavior as Stop order above. - if (filled == 0) { slot_price_target = wo.stop_limit_price(); } - } if (_slot_price_vs_orders.TryGetValue(slot_price_target, out LadderOrderVM slot_vm)) { slot_vm.add_order((wo, os.piq, os.algo, os.meta)); @@ -239,8 +232,8 @@ namespace mbts.spark { .Select(table => table.state.Values.FirstOrDefault(pos => pos.Item2.Account == a, tup => tup.Item2, (bts.api.position.PositionUnitImmutable?)null))); return Disposable.Create( settings.OnDispatcher().Subscribe(s => { - _sticky_algos.SetItems(s.favorite_algos.stickied_algos); - order_properties_vm.on_favorite_algos(s.favorite_algos); + _favorite_algo_map = s.favorite_algos.build_map(); + order_properties_vm.on_favorite_algos(_favorite_algo_map, s.favorite_algos.column_count); }), order_properties_vm, position_src.OnDispatcher().Subscribe(pos => { @@ -409,9 +402,9 @@ namespace mbts.spark { internal OrderRecordImmutable get_root_at_price((OrderRecordImmutable order, uint? _, AlgoData? __, AlgoDefinitionMetadata? meta) op) { var order = op.order; - double p = order.price(); + double p = order.ui_price(); foreach (var o in lineage(order.ParentKey)) { - if (_equality.Equals(p, o.price())) + if (_equality.Equals(p, o.ui_price())) order = o; } return order; @@ -510,10 +503,16 @@ namespace mbts.spark { if (auto_clear) size_calculator.value = 0; var fav_algo = order_properties_vm.selected_favorite_algo_definition; - if (fav_algo != null && !_sticky_algos.Contains(fav_algo.key) && !order_properties_vm.try_pop_selected_algo_definition()) { - var key = new AlgoKey(OrderDataHelper.get_default_algo(OrderDataHelper.get_algo_format(security.ContractCase))); - if (order_properties_vm.try_get_algo_definition(key, out var r)) { - order_properties_vm.selected_algo_definition = r; + if (fav_algo != null) { + if (_favorite_algo_map.TryGetValue(fav_algo.key, out var d)) { + if (!d.flags.HasFlag(LadderFavoriteAlgoFlags.Sticky) && !order_properties_vm.try_pop_selected_algo_definition()) { + var key = new AlgoKey(OrderDataHelper.get_default_algo(OrderDataHelper.get_algo_format(security.ContractCase))); + if (order_properties_vm.try_get_algo_definition(key, out var r)) { + order_properties_vm.selected_algo_definition = r; + } + } + if (d.flags.HasFlag(LadderFavoriteAlgoFlags.AutoRevert)) + fav_algo.algo_root.revert_all_params(); } } } diff --git a/src/client/spark/Modules/Trading/Ladder/View/LadderGridHost.cs b/src/client/spark/Modules/Trading/Ladder/View/LadderGridHost.cs index 7a51bc6d2..f165f5813 100644 --- a/src/client/spark/Modules/Trading/Ladder/View/LadderGridHost.cs +++ b/src/client/spark/Modules/Trading/Ladder/View/LadderGridHost.cs @@ -28,7 +28,8 @@ using System.Windows.Media.Animation; namespace mbts.spark { partial class LadderGridHost : Control { - const int _min_row_count = 501, _max_row_count = 2001, _column_min_width = 8; + const int _min_row_count = 501, _max_row_count = 2001; + int _row_count = _min_row_count; readonly VisualHost _visualHost = new VisualHost(); @@ -108,6 +109,8 @@ namespace mbts.spark { public event Action visible_columns_changed; + public static double ColumnMinWidth => 6; + public IEnumerable visible_column_types => columns.Where(c => c.settings.show) .Select(c => c.column_type); @@ -572,7 +575,7 @@ namespace mbts.spark { case ColumnType.Price: new_col_width = (int)price_column_width; break; case ColumnType.Ask: new_col_width = (int)ask_column_width; break; case ColumnType.Volume: new_col_width = (int)VolumeColumnWidth; break; - default: new_col_width = (int)Math.Max((double)column.settings.width + adjustment, _column_min_width); break; + default: new_col_width = (int)Math.Max((double)column.settings.width + adjustment, ColumnMinWidth); break; } int true_adj = new_col_width - (int)column.settings.width; column.settings.width = (uint)new_col_width; diff --git a/src/client/spark/Modules/Trading/Ladder/View/LadderSettingsView.xaml b/src/client/spark/Modules/Trading/Ladder/View/LadderSettingsView.xaml index 21d19bb24..50fa950bf 100644 --- a/src/client/spark/Modules/Trading/Ladder/View/LadderSettingsView.xaml +++ b/src/client/spark/Modules/Trading/Ladder/View/LadderSettingsView.xaml @@ -828,6 +828,7 @@ +