diff --git a/doc/user/content/release_notes/_index.md b/doc/user/content/release_notes/_index.md index 4b447d088..dcf3fbb3c 100644 --- a/doc/user/content/release_notes/_index.md +++ b/doc/user/content/release_notes/_index.md @@ -4,6 +4,23 @@ weight = 3 sort_by = "weight" insert_anchor_links = "right" +++ +## 2.9.0 +### User Visible Changes + - Improved Workspace management User Interface + - Added the ability to change grid background colors + - The Spark UI Window group now has a title in the Windows task bar + - Added sound alerts for trade events, see Launcher -> Settings -> Alerts +### Bug Fixes + - Fixed the settings action menu (Load/Save/Reset to Factory) +### API Changes + - Fixed an issue in the Client SDK that could lead to occasional failures to connect to the spark server as well as excessive memory usage. +### Internal Changes + - Changed how we packaged certain third-party components + - Added logging of entitlement status +## 2.8.3 +### Bug Fixes + - Fixed a bug that could cause an OrderBook's Security column filter to be blank + - Fixed a bug that could cause a UI failure when clearing a filter selection on a filtering widget ## 2.8.2 ### Bug Fixes - Added proper display factors for SOM spreads diff --git a/src/client/spark/Daemons/GlobalAlertsDaemon.cs b/src/client/spark/Daemons/GlobalAlertsDaemon.cs new file mode 100644 index 000000000..7cc191ea9 --- /dev/null +++ b/src/client/spark/Daemons/GlobalAlertsDaemon.cs @@ -0,0 +1,68 @@ +using bts.api; +using bts.shell; +using mbts; +using mbts.persist; +using mbts.spark; +using mbts.ui; +using mbts.ui.spark; +using mbts.ui.utilities; +using System; +using System.ComponentModel.Composition; +using System.Linq; +using System.Reactive.Disposables; +using System.Reactive.Linq; +using System.Windows; +using Disposable = mbts.Disposable; + +namespace bts { + [Export(typeof(IShellDaemon))] + class GlobalAlertsDaemon : IShellDaemon, IDisposable { + const string + // used for logging/diagnostic purposes + _window_name = "Global Alerts Dialog", + // actual window title + _window_title = "Alerts"; + + readonly ThreadedWindowLauncher _launcher; + readonly UserSettingsHub _hub; + readonly IBus _bus; + readonly INotificationService _notification_service; + IDisposable _dispose; + + [ImportingConstructor] + public GlobalAlertsDaemon(IBus bus, UserSettingsHub hub, INotificationService notification_service) { + _bus = bus; + _hub = hub; + _notification_service = notification_service; + _launcher = new ThreadedWindowLauncher(_window_name); + _dispose = Disposable.Create( + bus.subscribe(SparkTags.ShowGlobalAlertsTag) + .Subscribe(_ => _launcher.show(_view_factory)), + _hub.subscribe_default_settings() + .SubscribeEach(s => new CompositeDisposable( + s.alerts.trade_alerts.Where(t => t.is_enabled).Select( + a => _notification_service.link_to_trades( + a.predicate.security_criteria, a.predicate.create(), a.sound))))); + } + + Window _view_factory() { + var vm = new GlobalAlertsVM(); + vm.load_from(_hub.current.alerts); + vm.request_commit += commit; + var sec_sub = _bus.subscribe(SparkTags.SecuritiesTag).OnDispatcher().Subscribe(m => vm.security_map = m); + var win = new GlobalAlertsDialog { + Title = "Alerts", + DataContext = vm + }; + win.Closed += (s, e) => Disposable.dispose(ref sec_sub); + return win; + void commit() { + var s = _hub.current.with(alerts: vm.create()); + _hub.save_default(s).ignore(); + } + } + + public void Dispose() => + Disposable.dispose(ref _dispose); + } +} \ No newline at end of file diff --git a/src/client/spark/Images/Icons.cs b/src/client/spark/Images/Icons.cs index 3cc17164d..6e7087128 100644 --- a/src/client/spark/Images/Icons.cs +++ b/src/client/spark/Images/Icons.cs @@ -40,6 +40,7 @@ namespace mbts.ui { EditDocumentAltGeometryKey = nameof(EditDocumentAltGeometryKey), EditDocumentGeometryKey = nameof(EditDocumentGeometryKey), GearGeometryKey = nameof(GearGeometryKey), + HornGeometryKey = nameof(HornGeometryKey), LetterAKey = nameof(LetterAKey), LetterDKey = nameof(LetterDKey), OrdersGeometryKey = nameof(OrdersGeometryKey), @@ -48,6 +49,7 @@ namespace mbts.ui { PlayGeometryKey = nameof(PlayGeometryKey), ProhibitedGeometryKey = nameof(ProhibitedGeometryKey), RubberStampGeometryKey = nameof(RubberStampGeometryKey), + SpeakerGeometryKey = nameof(SpeakerGeometryKey), StarGeometryKey = nameof(StarGeometryKey), ToolsGeometryKey = nameof(ToolsGeometryKey), TrashGeometryKey = nameof(TrashGeometryKey), @@ -168,6 +170,7 @@ namespace mbts.ui { public static ImageSource FilterActive { get { return load_resource_and_freeze("FilterActive"); } } public static ImageSource FilterError { get { return load_resource_and_freeze("FilterError"); } } public static ImageSource Gear => create_icon(GearGeometryKey); + public static ImageSource Horn => create_icon(HornGeometryKey); public static ImageSource Import => load_resource_and_freeze("Import"); public static ImageSource Knight { get { return load_resource_and_freeze("Knight"); } } public static ImageSource Payment => create_icon(PaymentGeometryKey); @@ -176,6 +179,7 @@ namespace mbts.ui { public static ImageSource RubberStamp => create_icon(RubberStampGeometryKey); public static ImageSource RedoCircular => create_icon(UndoCircularGeometryKey, Brushes.Black, null, new ScaleTransform(-1, 1)); public static ImageSource Spawn { get { return load_resource_and_freeze("Spawn"); } } + public static ImageSource Speaker => create_icon(SpeakerGeometryKey); public static ImageSource Star => create_icon(StarGeometryKey); public static ImageSource Target { get { return load_resource_and_freeze("Target"); } } public static ImageSource Tetris { get { return load_resource_and_freeze("Tetris"); } } diff --git a/src/client/spark/Images/Vector/Icons.xaml b/src/client/spark/Images/Vector/Icons.xaml index a0ce61363..e44d4267a 100644 --- a/src/client/spark/Images/Vector/Icons.xaml +++ b/src/client/spark/Images/Vector/Icons.xaml @@ -274,6 +274,10 @@ M16.000015,9.6000061C12.500012,9.6000061 9.5999844,12.5 9.5999844,16 9.5999844,19.5 12.500012,22.399994 16.000015,22.399994 19.500019,22.399994 22.400015,19.5 22.400015,16 22.400015,12.5 19.500019,9.6000061 16.000015,9.6000061z M14.199995,0L17.800005,0C18.199999,0,18.599993,0.29998779,18.599993,0.79998779L18.599993,4.7999878C19.900013,5.1000061,21.000019,5.6000061,22.099997,6.2999878L25.000023,3.3999939C25.099999,3.2999878 25.300011,3.1999817 25.500025,3.1999817 25.700007,3.1999817 25.900019,3.2999878 26.000025,3.3999939L28.600033,6C28.900021,6.2999878,28.900021,6.7999878,28.600033,7.1000061L25.700007,10C26.400019,11.100006,26.900019,12.299988,27.200007,13.5L31.20001,13.5C31.600037,13.5,31.999998,13.799988,31.999998,14.299988L31.999998,17.899994C31.999998,18.299988,31.700012,18.699982,31.20001,18.699982L27.200007,18.699982C26.900019,20,26.400019,21.100006,25.700007,22.199982L28.600033,25.100006C28.700009,25.199982 28.799984,25.399994 28.799984,25.600006 28.799984,25.799988 28.700009,26 28.600033,26.100006L26.000025,28.600006C25.900019,28.699982 25.700007,28.799988 25.500025,28.799988 25.300011,28.799988 25.099999,28.699982 25.000023,28.600006L22.099997,25.699982C21.000019,26.399994,19.800007,26.899994,18.599993,27.199982L18.599993,31.199982C18.599993,31.600006,18.300005,32,17.800005,32L14.199995,32C13.8,32,13.400006,31.699982,13.400006,31.199982L13.400006,27.199982C12.099987,26.899994,11.000011,26.399994,9.9000027,25.699982L7.0000064,28.600006C6.9000003,28.699982 6.6999881,28.799988 6.5000059,28.799988 6.2999937,28.799988 6.099981,28.699982 6.0000054,28.600006L3.3999967,26C3.0999784,25.699982,3.0999784,25.199982,3.3999967,24.899994L6.2999937,22C5.5999805,20.899994,5.0999801,19.699982,4.7999923,18.5L0.79998828,18.5C0.39999409,18.5,-1.933513E-07,18.199982,0,17.699982L0,14.100006C-1.933513E-07,13.699982,0.2999879,13.299988,0.79998828,13.299988L4.7999923,13.299988C5.0999801,12,5.5999805,10.899994,6.2999937,9.7999878L3.3999967,7C3.2999908,6.8999939 3.1999845,6.6999817 3.1999845,6.5 3.1999845,6.2999878 3.2999908,6.1000061 3.3999967,6L6.0000054,3.3999939C6.099981,3.2999878 6.2999937,3.1999817 6.5000059,3.1999817 6.6999881,3.1999817 6.9000003,3.2999878 7.0000064,3.3999939L9.9000027,6.2999878C11.000011,5.6000061,12.199993,5.1000061,13.400006,4.7999878L13.400006,0.79998779C13.400006,0.29998779,13.8,0,14.199995,0z + + M4.0499969,7.0870913C2.9519978,7.0870913 2.0249984,8.4780906 2.0249987,10.125091 2.0249984,11.771091 2.9519978,13.162091 4.0499969,13.162091 5.1479961,13.162091 6.0749954,11.771091 6.0749955,10.125091 6.0749954,8.4780906 5.1479961,7.0870913 4.0499969,7.0870913z M29.975016,3.316155C23.883831,8.2016557,11.829888,8.9691842,8.1184387,9.0896781L8.0151367,9.0928462 8.0175586,9.1059306C8.0716033,9.4352315 8.0999939,9.7760909 8.0999942,10.125091 8.0999939,10.473966 8.0716033,10.814716 8.0175586,11.143921L8.0098858,11.185364 8.193316,11.195448C12.163719,11.420399,23.994581,12.458921,29.975016,17.005057z M31.176758,0.00019051835C31.280359,-0.0022594665 31.391857,0.01889403 31.514975,0.065146674 31.908983,0.21413228 31.999985,0.59114302 31.999985,1.0121596L31.999985,19.236969C31.999985,19.653958 31.913988,20.028956 31.525991,20.179955 31.405998,20.226952 31.450981,20.250023 31.32699,20.250023 31.050991,20.250023 30.778992,20.13601 30.583986,19.925928 25.229074,14.140572 9.6001122,13.269665 7.2865356,13.172559L7.2813506,13.172345 7.1739591,13.343056C6.4304952,14.468533 5.3060585,15.187091 4.0499969,15.187091 1.8169985,15.187091 0,12.916091 0,10.125091 0,7.3330911 1.8169985,5.0620912 4.0499969,5.0620912 5.3060585,5.0620912 6.4304952,5.78065 7.1739591,6.9063042L7.2852713,7.0832756 7.3087114,7.0828188C9.6077337,7.036146 25.141474,6.4939421 30.567997,0.34315929 30.75913,0.12521249 30.948835,0.005580858 31.176758,0.00019051835z + + 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 @@ -327,6 +331,11 @@ M33.5,4h-6v10h6V4z M31.5,12h-2V6h2V12z + + + M18,12.839666L18,19.159448 18.029955,19.131576C18.848108,18.314159 19.332083,17.192702 19.332083,15.999873 19.332083,14.806357 18.848108,13.684685 18.029955,12.867527z M21.738388,4.748316C21.868353,4.7515661 21.999973,4.7804414 22.126221,4.8376924 26.511095,6.8177201 29.344013,11.199782 29.344013,15.999849 29.344013,20.799915 26.511095,25.181977 22.126221,27.162004 21.992224,27.223004 21.853228,27.251006 21.715233,27.251006 21.333244,27.251006 20.970255,27.032003 20.803259,26.662997 20.575266,26.15899 20.799259,25.566981 21.302244,25.339978 24.973139,23.681956 27.34407,20.015905 27.34407,15.999849 27.34407,11.983792 24.973139,8.3177406 21.302244,6.6597177 20.799259,6.4327146 20.575266,5.8407065 20.803259,5.3366992 20.973503,4.9594442 21.348494,4.7385656 21.738388,4.748316z M16,3.1854247L6.6530151,11.257323C6.4719848,11.414303,6.2399902,11.500301,6,11.500301L1.9999998,11.500301 1.9999998,21.500148 6,21.500148C6.2219848,21.500148,6.4370117,21.573144,6.6110229,21.709129L16,28.964023z M17.000252,1.186163E-08C17.141373,-2.1778678E-05 17.283264,0.02997845 17.416016,0.091477852 17.770996,0.25450047 18,0.60843792 18,1.0004608L18,10.368904 18.170259,10.465408C20.111607,11.612996 21.331976,13.716092 21.331976,15.999873 21.331976,18.282748 20.111607,20.38576 18.170259,21.53334L18,21.629842 18,31.000003C18,31.382016 17.78302,31.728995 17.440002,31.896962 17.301025,31.965991 17.150024,31.99999 17,31.99999 16.78302,31.99999 16.567017,31.929982 16.388977,31.791007L5.65802,23.500117 0.99999966,23.500117C0.44702145,23.500117,-3.9348969E-08,23.053104,3.5527137E-15,22.500133L3.5527137E-15,10.500316C-3.9348969E-08,9.9473459,0.44702145,9.5003311,0.99999966,9.5003311L5.6279907,9.5003311 16.346985,0.24345344C16.531998,0.083467316,16.765053,3.6392792E-05,17.000252,1.186163E-08z + + M1540.22,2082.07L1546.95,2102.78 1568.73,2102.78 1551.11,2115.58 1557.84,2136.29 1540.22,2123.49 1522.6,2136.29 1529.33,2115.58 1511.71,2102.78 1533.49,2102.78 1540.22,2082.07z diff --git a/src/client/spark/Modules/Market/MarketView/MarketViewVM.cs b/src/client/spark/Modules/Market/MarketView/MarketViewVM.cs index 73581518c..b8257083e 100644 --- a/src/client/spark/Modules/Market/MarketView/MarketViewVM.cs +++ b/src/client/spark/Modules/Market/MarketView/MarketViewVM.cs @@ -1,5 +1,6 @@ using bts.api; using bts.collections; +using bts.proto; using bts.utils; using mbts.persist; using mbts.spark.filters; @@ -46,8 +47,8 @@ namespace mbts.spark { add_col(Columns.BidImpliedSize, implied_size_col_header, r => r.bid_implied_size.ToString(), nameof(Row.bid_implied_size), DefaultColumnWidths.ImpliedDirectMergedSize, bid_implied_size_filter, DataGridFilterKnownTemplates.UIntMinMax, font_color: BTSColors.MarketData.bid, h_alignment: System.Windows.HorizontalAlignment.Right); add_col(Columns.BidDirectSize, direct_size_col_header, r => r.bid_direct_size.ToString(), nameof(Row.bid_direct_size), DefaultColumnWidths.ImpliedDirectMergedSize, bid_direct_size_filter, DataGridFilterKnownTemplates.UIntMinMax, font_color: BTSColors.MarketData.bid, h_alignment: System.Windows.HorizontalAlignment.Right); add_hl_merged_size_col(Columns.BidMergedSize, merged_size_col_header, nameof(Row.bid_merged_size), nameof(Row.bid_merged_size_text), nameof(Row.bid_merged_size_click), bid_merged_size_filter, BTSColors.MarketData.bid, h_alignment: System.Windows.HorizontalAlignment.Right); - add_hl_price_col(Columns.Bid, "Bid", nameof(Row.bid_price), nameof(Row.bid_price_click), bid_price_filter, BTSColors.header_text, BTSColors.MarketData.bid_brush, h_alignment: System.Windows.HorizontalAlignment.Right); - add_hl_price_col(Columns.Ask, "Ask", nameof(Row.ask_price), nameof(Row.ask_price_click), ask_price_filter, BTSColors.header_text, BTSColors.MarketData.ask_brush, h_alignment: System.Windows.HorizontalAlignment.Right); + add_hl_price_col(Columns.Bid, "Bid", nameof(Row.bid_price), nameof(Row.bid_price_click), bid_price_filter, BTSColors.header_text, BTSColors.MarketData.bid, h_alignment: System.Windows.HorizontalAlignment.Right); + add_hl_price_col(Columns.Ask, "Ask", nameof(Row.ask_price), nameof(Row.ask_price_click), ask_price_filter, BTSColors.header_text, BTSColors.MarketData.ask, h_alignment: System.Windows.HorizontalAlignment.Right); add_hl_merged_size_col(Columns.AskMergedSize, merged_size_col_header, nameof(Row.ask_merged_size), nameof(Row.ask_merged_size_text), nameof(Row.ask_merged_size_click), ask_merged_size_filter, BTSColors.MarketData.ask, h_alignment: System.Windows.HorizontalAlignment.Right); add_col(Columns.AskDirectSize, direct_size_col_header, r => r.ask_direct_size.ToString(), nameof(Row.ask_direct_size), DefaultColumnWidths.ImpliedDirectMergedSize, ask_direct_size_filter, DataGridFilterKnownTemplates.UIntMinMax, font_color: BTSColors.MarketData.ask, h_alignment: System.Windows.HorizontalAlignment.Right); add_col(Columns.AskImpliedSize, implied_size_col_header, r => r.ask_implied_size.ToString(), nameof(Row.ask_implied_size), DefaultColumnWidths.ImpliedDirectMergedSize, ask_implied_size_filter, DataGridFilterKnownTemplates.UIntMinMax, font_color: BTSColors.MarketData.ask, h_alignment: System.Windows.HorizontalAlignment.Right); @@ -77,18 +78,18 @@ namespace mbts.spark { horizontal_alignment = h_alignment }); - void add_hl_price_col(Columns col_key, string header, string prop, string command_prop, IDataGridColumnFilter filter, Color foreground, Brush background, System.Windows.HorizontalAlignment h_alignment) => - add_hl_col(col_key, header, price_binding(prop), prop, command_prop, filter, DataGridFilterKnownTemplates.DoubleMinMax, DefaultColumnWidths.MViewPrice, foreground, background, DefaultSelectionHighlight, h_alignment); + void add_hl_price_col(Columns col_key, string header, string prop, string command_prop, IDataGridColumnFilter filter, Color foreground, Color? background, System.Windows.HorizontalAlignment h_alignment) => + add_hl_col(col_key, header, price_binding(prop), prop, command_prop, filter, DataGridFilterKnownTemplates.DoubleMinMax, DefaultColumnWidths.MViewPrice, foreground, background, h_alignment); void add_hl_merged_size_col(Columns col_key, string header, string sort_prop, string text_prop, string command_prop, IDataGridColumnFilter filter, Color foreground, System.Windows.HorizontalAlignment h_alignment) => - add_hl_col(col_key, header, new Binding(text_prop), sort_prop, command_prop, filter, DataGridFilterKnownTemplates.UIntMinMax, DefaultColumnWidths.ImpliedDirectMergedSize, foreground, null, null, h_alignment); + add_hl_col(col_key, header, new Binding(text_prop), sort_prop, command_prop, filter, DataGridFilterKnownTemplates.UIntMinMax, DefaultColumnWidths.ImpliedDirectMergedSize, foreground, null, h_alignment); void add_hl_working_orders_col(Columns col_key, string header, string text_prop, string sort_prop, string command_prop, IDataGridColumnFilter filter, Color foreground, System.Windows.HorizontalAlignment h_alignment) => - add_hl_col(col_key, header, new Binding(text_prop), sort_prop, command_prop, filter, DataGridFilterKnownTemplates.IntMinMax, working_orders_col_width, foreground, null, null, h_alignment); + add_hl_col(col_key, header, new Binding(text_prop), sort_prop, command_prop, filter, DataGridFilterKnownTemplates.IntMinMax, working_orders_col_width, foreground, null, h_alignment); void add_hl_col( Columns col_key, string header, BindingBase binding, string prop, string command_prop, - IDataGridColumnFilter filter, string filter_template, double width, Color foreground, Brush background, Brush background_overlay, System.Windows.HorizontalAlignment h_alignment = System.Windows.HorizontalAlignment.Left) => + IDataGridColumnFilter filter, string filter_template, double width, Color foreground, Color? background, System.Windows.HorizontalAlignment h_alignment = System.Windows.HorizontalAlignment.Left) => columns.Add(new HyperlinkElementColumn( col_key, binding, new Binding(command_prop), filter, filter_template) { // it's necessary to have this id populated for grid settings @@ -96,8 +97,7 @@ namespace mbts.spark { Header = header, sort_member_path = prop, font_color_override = foreground, - background = background, - background_overlay = background_overlay, + background_color_override = background, Width = DefaultColumnWidths.Price, horizontal_alignment = h_alignment }); @@ -111,14 +111,8 @@ namespace mbts.spark { // // make font-color immutable for Side, Size, (the font-color rule is hard-coded: MarketData.bid for Buy orders, MarketData.ask for Sells) var col_settings_flags = new Dictionary { - { Columns.Bid.ToString(), GridColumnSettingsFeatureFlags.ImmutableFontColor }, - { Columns.Ask.ToString(), GridColumnSettingsFeatureFlags.ImmutableFontColor }, - { Columns.BidImpliedSize.ToString(), GridColumnSettingsFeatureFlags.ImmutableFontColor }, - { Columns.BidDirectSize.ToString(), GridColumnSettingsFeatureFlags.ImmutableFontColor }, - { Columns.BidMergedSize.ToString(), GridColumnSettingsFeatureFlags.ImmutableFontColor }, - { Columns.AskImpliedSize.ToString(), GridColumnSettingsFeatureFlags.ImmutableFontColor }, - { Columns.AskDirectSize.ToString(), GridColumnSettingsFeatureFlags.ImmutableFontColor }, - { Columns.AskMergedSize.ToString(), GridColumnSettingsFeatureFlags.ImmutableFontColor }, + { Columns.Bid.ToString(), GridColumnSettingsFeatureFlags.ImmutableFontColor | GridColumnSettingsFeatureFlags.ImmutableBackgroundColor }, + { Columns.Ask.ToString(), GridColumnSettingsFeatureFlags.ImmutableFontColor | GridColumnSettingsFeatureFlags.ImmutableBackgroundColor}, { Columns.WorkingAsks.ToString(), GridColumnSettingsFeatureFlags.ImmutableFontColor }, { Columns.WorkingBids.ToString(), GridColumnSettingsFeatureFlags.ImmutableFontColor } }; diff --git a/src/client/spark/Modules/Market/MarketView/MarketViewWindow.cs b/src/client/spark/Modules/Market/MarketView/MarketViewWindow.cs index 35f22e89c..da46e6c8d 100644 --- a/src/client/spark/Modules/Market/MarketView/MarketViewWindow.cs +++ b/src/client/spark/Modules/Market/MarketView/MarketViewWindow.cs @@ -153,7 +153,7 @@ namespace mbts.spark { 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.columns.Select(c => c.create())) + MarketViewWindowFactory.StartupData.sanitize(s).with(_vm.columns.Select(c => c.create())) ) ); vm.SubscribeDisposed(literal_title_source.OnDispatcher().Subscribe(t => vm.title = t)); diff --git a/src/client/spark/Modules/Market/MarketView/MarketViewWindowFactory.cs b/src/client/spark/Modules/Market/MarketView/MarketViewWindowFactory.cs index 38931a3eb..c28013d6b 100644 --- a/src/client/spark/Modules/Market/MarketView/MarketViewWindowFactory.cs +++ b/src/client/spark/Modules/Market/MarketView/MarketViewWindowFactory.cs @@ -1,4 +1,5 @@ using bts.api; +using bts.proto; using mbts.persist; using mbts.spark; using mbts.spark.filters; @@ -36,9 +37,9 @@ namespace bts.shell { _bus.post(SparkTags.ShowWindow, _create(StartupData.Default(criteria))); IShellWindow _create(StartupData state) { - var settings_manager = new WindowSettingsManager(_settings_hub, - state.grid, - get: us => us.market_view_grid, + var settings_manager = new WindowSettingsManager(_settings_hub, + StartupData.sanitize(state.grid), + get: us => StartupData.sanitize(us.market_view_grid), set: (us, gs) => us.with(provided_market_view_gridsettings: gs)); return new MarketViewWindow(this, _bus, _orders_model, state, settings_manager); } @@ -68,7 +69,29 @@ namespace bts.shell { _sorting_criteria = sort; } - public static GridSettings DefaultGridSettings => GridSettings.Default.with(DefaultColumns.all, DefaultColumns.default_sorting_criterion); + public static GridSettings sanitize(GridSettings s) { + if (s == null) { + return null; + } + + // column upgrade + var columns = s.columns.ToList(); + var bid_col_index = columns.FindIndex(x => x.id == col_id(Columns.Bid)); + var ask_col_index = columns.FindIndex(x => x.id == col_id(Columns.Ask)); + if (bid_col_index > -1 && ask_col_index > -1) { + if (!columns[bid_col_index].background_color_override.HasValue) { + columns[bid_col_index] = columns[bid_col_index].with(background_color_override: new NullableColorProto(BTSColors.MarketData.bid.ToUint())); + } + if (!columns[ask_col_index].background_color_override.HasValue) { + columns[ask_col_index] = columns[ask_col_index].with(background_color_override: new NullableColorProto(BTSColors.MarketData.ask.ToUint())); + } + } + // and enable background color upgrade + return s.with(columns, enable_background_color: true); + } + + + public static GridSettings DefaultGridSettings => GridSettings.Default.with(DefaultColumns.all, DefaultColumns.default_sorting_criterion, enable_background_color: true); public IReadOnlyList sorting_criterion => _sorting_criteria ?? (_sorting_criteria = DefaultColumns.default_sorting_criterion.ToList()); @@ -86,8 +109,8 @@ namespace bts.shell { public static GridColumnSettings bid_implied_size => new GridColumnSettings(col_id(Columns.BidImpliedSize), DefaultColumnHeaders.ImpliedSize, font_color_override: BTSColors.MarketData.bid, width: DefaultColumnWidths.ImpliedDirectMergedSize, horizontal_alignment: System.Windows.HorizontalAlignment.Right); public static GridColumnSettings bid_direct_size => new GridColumnSettings(col_id(Columns.BidDirectSize), DefaultColumnHeaders.DirectSize, font_color_override: BTSColors.MarketData.bid, width: DefaultColumnWidths.ImpliedDirectMergedSize, horizontal_alignment: System.Windows.HorizontalAlignment.Right); public static GridColumnSettings bid_merged_size => new GridColumnSettings(col_id(Columns.BidMergedSize), DefaultColumnHeaders.MergedSize, font_color_override: BTSColors.MarketData.bid, width: DefaultColumnWidths.ImpliedDirectMergedSize, horizontal_alignment: System.Windows.HorizontalAlignment.Right); - public static GridColumnSettings bid => new GridColumnSettings(col_id(Columns.Bid), DefaultColumnHeaders.Bid, font_color_override: BTSColors.header_text, width:DefaultColumnWidths.MViewPrice, horizontal_alignment: System.Windows.HorizontalAlignment.Right); - public static GridColumnSettings ask => new GridColumnSettings(col_id(Columns.Ask), DefaultColumnHeaders.Ask, font_color_override: BTSColors.header_text, width: DefaultColumnWidths.MViewPrice, horizontal_alignment: System.Windows.HorizontalAlignment.Right); + public static GridColumnSettings bid => new GridColumnSettings(col_id(Columns.Bid), DefaultColumnHeaders.Bid, font_color_override: BTSColors.header_text, width:DefaultColumnWidths.MViewPrice, horizontal_alignment: System.Windows.HorizontalAlignment.Right, background_color_override: BTSColors.MarketData.bid); + public static GridColumnSettings ask => new GridColumnSettings(col_id(Columns.Ask), DefaultColumnHeaders.Ask, font_color_override: BTSColors.header_text, width: DefaultColumnWidths.MViewPrice, horizontal_alignment: System.Windows.HorizontalAlignment.Right, background_color_override: BTSColors.MarketData.ask); public static GridColumnSettings ask_merged_size => new GridColumnSettings(col_id(Columns.AskMergedSize), DefaultColumnHeaders.MergedSize, font_color_override: BTSColors.MarketData.ask, width: DefaultColumnWidths.ImpliedDirectMergedSize, horizontal_alignment: System.Windows.HorizontalAlignment.Right); public static GridColumnSettings ask_direct_size => new GridColumnSettings(col_id(Columns.AskDirectSize), DefaultColumnHeaders.DirectSize, font_color_override: BTSColors.MarketData.ask, width: DefaultColumnWidths.ImpliedDirectMergedSize, horizontal_alignment: System.Windows.HorizontalAlignment.Right); public static GridColumnSettings ask_implied_size => new GridColumnSettings(col_id(Columns.AskImpliedSize), DefaultColumnHeaders.ImpliedSize, font_color_override: BTSColors.MarketData.ask, width: DefaultColumnWidths.ImpliedDirectMergedSize, horizontal_alignment: System.Windows.HorizontalAlignment.Right); diff --git a/src/client/spark/Modules/Market/TimeAndSales/TimeAndSalesModel.cs b/src/client/spark/Modules/Market/TimeAndSales/TimeAndSalesModel.cs index 2b17345e6..b0121b166 100644 --- a/src/client/spark/Modules/Market/TimeAndSales/TimeAndSalesModel.cs +++ b/src/client/spark/Modules/Market/TimeAndSales/TimeAndSalesModel.cs @@ -7,16 +7,6 @@ using System.Linq; using System.Reactive.Linq; namespace mbts.spark { - struct TradeInfo { - public readonly SecurityImmutable security; - public readonly TradeMessageImmutable trade; - - public TradeInfo(SecurityImmutable security, TradeMessageImmutable trade) { - this.security = security; - this.trade = trade; - } - } - class TimeAndSalesModel : IDisposable { internal readonly SecurityCriteria security_criteria; diff --git a/src/client/spark/Modules/Market/TimeAndSales/TimeAndSalesVM.cs b/src/client/spark/Modules/Market/TimeAndSales/TimeAndSalesVM.cs index 11a3a44ee..e2b5b8139 100644 --- a/src/client/spark/Modules/Market/TimeAndSales/TimeAndSalesVM.cs +++ b/src/client/spark/Modules/Market/TimeAndSales/TimeAndSalesVM.cs @@ -137,7 +137,7 @@ namespace mbts.spark { public Row(TimeAndSalesVM parent, SecurityImmutable security, TradeMessageImmutable trade) : base(security) { _trade_key = trade.Key; time = ((ulong)trade.Time).lldatetime().ToLocalTime(); - price = trade.Mantissa * Math.Pow(10, trade.Exponent); + price = trade.price(); size = trade.Size; aggressor_side = trade.AggressorSide; show_ladder = new DelegateCommand(() => parent._show_ladder_async(this).ignore()); diff --git a/src/client/spark/Modules/Settings/SettingsShellModule.cs b/src/client/spark/Modules/Settings/SettingsShellModule.cs index 005dd648b..ce995d025 100644 --- a/src/client/spark/Modules/Settings/SettingsShellModule.cs +++ b/src/client/spark/Modules/Settings/SettingsShellModule.cs @@ -26,7 +26,10 @@ namespace bts.ui { public SettingsShellModule(IBus bus, UserSettingsHub settings_hub, WorkspacesModel ws) { // todo: settings dialog ws_model = ws; - var actions_list = new List(2) { SparkCommands.ShowWorkspaces }; + var actions_list = new List(2) { + SparkCommands.ShowGlobalAlerts, + SparkCommands.ShowWorkspaces + }; if (Configuration.get().enabled) { actions_list.Add(SparkCommands.ShowSettings); } diff --git a/src/client/spark/Modules/Trading/Ladder/VM/LadderSettingsVM.cs b/src/client/spark/Modules/Trading/Ladder/VM/LadderSettingsVM.cs index 97db476d3..a1bd3fc6f 100644 --- a/src/client/spark/Modules/Trading/Ladder/VM/LadderSettingsVM.cs +++ b/src/client/spark/Modules/Trading/Ladder/VM/LadderSettingsVM.cs @@ -137,7 +137,7 @@ namespace mbts.spark { c.PropertyChanged -= on_prop_changed; } AccountTuple? account_factory(KeyValuePair kv) => new AccountTuple(kv.Key, kv.Value); - AlgoDefinitionVM algo_factory(AlgoData data) => AlgoDefinitionVM.create(_model, data); + AlgoDefinitionVM algo_factory(AlgoData data) => AlgoDefinitionVM.create(_model, data, is_synthetic ? AlgoFormats.Spreader : AlgoFormats.Exchange); } public event Action result_changed; diff --git a/src/client/spark/Notifications/INotificationService.cs b/src/client/spark/Notifications/INotificationService.cs index bb9437610..47e61a63a 100644 --- a/src/client/spark/Notifications/INotificationService.cs +++ b/src/client/spark/Notifications/INotificationService.cs @@ -4,6 +4,7 @@ using bts.api.orderman; using bts.collections; using bts.spark; using mbts; +using mbts.co2; using mbts.collections; using mbts.spark; using mbts.ui; @@ -13,6 +14,7 @@ using System.Collections.Generic; using System.ComponentModel.Composition; using System.Linq; using System.Reactive.Linq; +using System.Reactive.Subjects; namespace bts.shell { interface INotificationService { @@ -22,25 +24,48 @@ namespace bts.shell { IDisposable link_to_activity(INotificationPredicate toast_notification_predicate); IDisposable link_to_order(IPredicate predicate, SoundNotification sound); IDisposable link_to_order(INotificationPredicate toast_notification_predicate); + // Note: security criteria should not be incorporated in the predicate's 'trigger' impl. + // It is easier/cleaner if the INotificationService incorporates the criteria internally. + IDisposable link_to_trades(SecurityCriteria security_criteria, IPredicate predicate, SoundNotification sound); } [Export(typeof(INotificationService))] partial class NotificationService : INotificationService, IDisposable { + // activity notifications readonly NotificationProcessor _activity_notifications; + // order notifications readonly NotificationProcessor _order_notifications; + // trade notifications + readonly NotificationProcessor _trade_notifications; + readonly MDConsumer _consumer; + readonly Subject> _trade_criteria_subject = new Subject>(); + readonly RefCountMap _trade_criteria_refs = new RefCountMap(); + readonly object _trade_lock = new object(); + // readonly DataCache _data_cache = new DataCache(); + readonly LoggerContext _log = new LoggerContext(Log.Ui, "Notification Service ", null); IDisposable _dispose; [ImportingConstructor] - public NotificationService(IBus bus, INotifier notifier, OrdersModel orders_model) { + public NotificationService(IBus bus, INotifier notifier, OrdersModel orders_model, MDConsumer consumer) { this.notifier = notifier; _activity_notifications = new NotificationProcessor(notifier); _order_notifications = new NotificationProcessor(notifier); + _trade_notifications = new NotificationProcessor(notifier); + _consumer = consumer; _dispose = Disposable.Create( bus.subscribe(SparkTags.LogActivity).Subscribe(_on_activity), - orders_model.on_orders.Subscribe(_on_orders) - ); + orders_model.on_orders.Subscribe(_on_orders), + TradesSource.create( + consumer, + bus.subscribe(SparkTags.SecuritiesTag).BufferLatest(TimeSpan.FromSeconds(2)) + .Table(s => s.security.Id) + .Where(t => t.has_changes()) + .Select(m => MappedDictionary.create(m.state, smd => smd.security)), + _trade_criteria_subject, + TimeSpan.FromSeconds(0.2)) + .Subscribe(_trade_notifications.process_items)); } [Export(typeof(INotificationServiceDataCache))] @@ -51,8 +76,42 @@ namespace bts.shell { public IDisposable link_to_activity(INotificationPredicate toast_notification_predicate) => _activity_notifications.link(toast_notification_predicate); public IDisposable link_to_order(IPredicate predicate, SoundNotification sound) => _order_notifications.link(predicate, sound); public IDisposable link_to_order(INotificationPredicate toast_notification_predicate) => _order_notifications.link(toast_notification_predicate); + + public IDisposable link_to_trades(SecurityCriteria security_criteria, IPredicate predicate, SoundNotification sound) { + if (predicate == null) { + _log.warn("cannot create trade alert sound because the specified predicate is null."); + return Disposable.empty; + } + if (!security_criteria.is_defined()) { + // there are simply too many trades to support universal-product predicates, therefor a product filter must be specified (aka SecrityCriteria). + _log.warn("cannot create trade alert sound because the specified security criteria is not defined."); + return Disposable.empty; + } + // This criteria predicate may be redundant, but it safe guards against a case + // where the criteria has not been incorporated into the predicate, + // as there doesn't seem to be a great way to require this in the interface. + // Note: verifying the criteria twice (instead of once) should not hurt on perf at all. + predicate = predicate.and(PredicateBuilder.create(t => ContractPickerModel.security_in_criteria(security_criteria, t.security))); + var link = _trade_notifications.link(predicate, sound); + lock (_trade_lock) { + if (_trade_criteria_refs.increment_adds_key(security_criteria)) + _reset_trade_readers(); + } + return Disposable.Create(() => { + Disposable.dispose(ref link); + lock (_trade_lock) { + if (_trade_criteria_refs.decrement_removes_key(security_criteria)) + _reset_trade_readers(); + } + }); + } + public void Dispose() => Disposable.dispose(ref _dispose); + /// should only call this within a locked scope () + void _reset_trade_readers() => + _trade_criteria_subject.OnNext(_trade_criteria_refs.Keys); + void _on_activity(Activity activity) => _activity_notifications.process_item(activity); @@ -128,6 +187,31 @@ namespace bts.shell { if (sounds.Count > 0 || toast.Count > 0) _notifier.notify(toast, sounds); } + + public void process_items(IEnumerable source) { + var sounds = new HashSet(); + var toast = new HashSet(); + var temp_sound_triggers = _sound_trigger_refs; + if (temp_sound_triggers.Count > 0) { + foreach (var v in source) { + foreach (var trigger_kv in temp_sound_triggers) { + if (trigger_kv.Key.trigger(v)) + sounds.AddRange(trigger_kv.Value.Keys); + } + } + } + var temp_toast_triggers = _toast_trigger_refs; + if (temp_toast_triggers.Count > 0) { + foreach (var v in source) { + foreach (var trigger_kv in temp_toast_triggers) { + if (trigger_kv.Key.trigger(v) is IToastNotification tn && tn.pass) + toast.Add(tn); + } + } + } + if (sounds.Count > 0 || toast.Count > 0) + _notifier.notify(toast, sounds); + } } } } \ No newline at end of file diff --git a/src/client/spark/Notifications/SoundNotification.cs b/src/client/spark/Notifications/SoundNotification.cs index 4125b3d95..b496317c8 100644 --- a/src/client/spark/Notifications/SoundNotification.cs +++ b/src/client/spark/Notifications/SoundNotification.cs @@ -1,9 +1,7 @@ -using mbts; -using mbts.ui.utility; +using bts.utils; using ProtoBuf; using System; using System.ComponentModel; -using System.Text; namespace bts.shell { enum LicenseType { @@ -33,7 +31,7 @@ namespace bts.shell { } [ProtoContract] - class SoundNotification { + class SoundNotification : IEquatable { SystemSound? _system_sound; string _uri_sound; @@ -81,6 +79,19 @@ namespace bts.shell { [ProtoMember(2)] public string uri_sound { get => _uri_sound; set => _set_ref_type(ref _uri_sound, value); } + public bool Equals(SoundNotification other) => + other != null && + _system_sound == other._system_sound && + _uri_sound == other._uri_sound; + + public override bool Equals(object obj) => + Equals(obj as SoundNotification); + + public override int GetHashCode() => + EqualityComparer.auto_phase( + _system_sound.GetHashCode(), + _uri_sound?.GetHashCode() ?? 0); + void _set(ref T? field, T? value) where T : struct { if (value != null) { _clear_values(); diff --git a/src/client/spark/Orders/OrderUtils.cs b/src/client/spark/Orders/OrderUtils.cs index 090939148..e109fcdd4 100644 --- a/src/client/spark/Orders/OrderUtils.cs +++ b/src/client/spark/Orders/OrderUtils.cs @@ -1,5 +1,6 @@ using bts.api; using bts.api.orderman; +using bts.co2; using bts.spark; using bts.utils; using mbts.spark.utilities; @@ -328,5 +329,13 @@ namespace mbts.spark { return string.Empty; } } + + public static AggressorSide to_aggressor(this Side side) { + switch (side) { + case Side.Buy: return AggressorSide.Buy; + case Side.Sell: return AggressorSide.Sell; + default: return AggressorSide.None; + } + } } } diff --git a/src/client/spark/Predicates/Data/Primitive/DoublePredicate.cs b/src/client/spark/Predicates/Data/Primitive/DoublePredicate.cs index 814ba0b54..997e45b85 100644 --- a/src/client/spark/Predicates/Data/Primitive/DoublePredicate.cs +++ b/src/client/spark/Predicates/Data/Primitive/DoublePredicate.cs @@ -61,6 +61,17 @@ namespace mbts { } } + public static DoublePredicate create(PredicateTypeOneofCase type, double min, double max) { + var rv = new DoublePredicate(); + switch (type) { + case PredicateTypeOneofCase.GreaterThan: rv.greater_than = min; break; + case PredicateTypeOneofCase.LessThan: rv.less_than = max; break; + case PredicateTypeOneofCase.InsideRange: rv.inside_range = new DoubleRange(min, max); break; + case PredicateTypeOneofCase.OutsideRange: rv.outside_range = new DoubleRange(min, max); break; + } + return rv; + } + public IPredicate create() { switch (predicate_type_case) { case PredicateTypeOneofCase.GreaterThan: return PredicateBuilder.greater_than(_greater_than.Value); diff --git a/src/client/spark/Predicates/IPredicate.cs b/src/client/spark/Predicates/IPredicate.cs index bd881c697..c5ae09899 100644 --- a/src/client/spark/Predicates/IPredicate.cs +++ b/src/client/spark/Predicates/IPredicate.cs @@ -2,6 +2,7 @@ using System; using System.Collections.Generic; using System.ComponentModel; +using System.Linq; namespace mbts { interface IPredicate { @@ -34,9 +35,15 @@ namespace mbts { public static IPredicate greater_than(T value) => new GreaterThanTrigger(value, Comparer.Default); + public static IPredicate greater_than_or_equal_to(T value) => + new GreaterThanOrEqualToTrigger(value, Comparer.Default); + public static IPredicate less_than(T value) => greater_than(value).negate(); + public static IPredicate less_than_or_equal_to(T value) => + greater_than_or_equal_to(value).negate(); + public static IPredicate inside_range(T minimum, T maximum) => greater_than(minimum).and(less_than(maximum)); @@ -67,6 +74,14 @@ namespace mbts { public static IPredicate not_in_set(ISet set) => in_set(set).negate(); + public static IPredicate and_safe(this IPredicate first, IPredicate second) { + if (first == null) + return second; + if (second == null) + return first; + return and(first, second); + } + public static IPredicate and(this IPredicate first, IPredicate second) => new AndTrigger(first, second); @@ -88,7 +103,7 @@ namespace mbts { public static IPredicate state_transition(Func predicate) { // avoid false-positive in the first callback bool last_result = true; - return new AnonymousMutableTrigger(v => { + return new AnonymousTrigger(v => { bool curr_result = predicate(v); if (last_result == curr_result) { return false; @@ -97,7 +112,7 @@ namespace mbts { } #region Implementation - class EqualsTrigger : IPredicate { + class EqualsTrigger : IPredicate, IEquatable> { readonly T _value; readonly IEqualityComparer _eq_comparer; @@ -106,12 +121,26 @@ namespace mbts { _eq_comparer = eq_comparer; } - public bool trigger(T value) => _eq_comparer.Equals(value, _value); + public bool trigger(T value) => + _eq_comparer.Equals(value, _value); - public override string ToString() => $"EqualsTrigger ({typeof(T)})"; + public override string ToString() => + $"EqualsTrigger ({typeof(T)})"; + + public bool Equals(EqualsTrigger other) => + other != null && + // check equality with both IEqualityComparers + _eq_comparer.Equals(_value, other._value) && + other._eq_comparer.Equals(_value, other._value); + + public override bool Equals(object obj) => + Equals(obj as EqualsTrigger); + + public override int GetHashCode() => + _eq_comparer.GetHashCode(_value); } - class AndTrigger : IPredicate { + class AndTrigger : IPredicate, IEquatable> { readonly IPredicate _first, _second; public AndTrigger(IPredicate first, IPredicate second) { @@ -119,18 +148,28 @@ namespace mbts { _second = second; } - public bool trigger(T value) => _first.trigger(value) && _second.trigger(value); + public bool trigger(T value) => + _first.trigger(value) && + _second.trigger(value); - public override string ToString() => $"AndTrigger ({_first}, {_second})"; + public bool Equals(AndTrigger other) => + other != null && + _first.Equals(other._first) && + _second.Equals(other._second); + + public override string ToString() => + $"AndTrigger ({_first}, {_second})"; public override bool Equals(object obj) => - obj is AndTrigger t && _first.Equals(t._first) && _second.Equals(t._second); + Equals(obj as AndTrigger); public override int GetHashCode() => - EqualityComparer.aggregate_hash(_first.GetHashCode(), _second.GetHashCode()); + EqualityComparer.aggregate_hash( + _first.GetHashCode(), + _second.GetHashCode()); } - class AndTrigger : IPredicate<(T1, T2)> { + class AndTrigger : IPredicate<(T1, T2)>, IEquatable> { readonly IPredicate _first; readonly IPredicate _second; @@ -139,18 +178,28 @@ namespace mbts { _second = second; } - public bool trigger((T1, T2) value) => _first.trigger(value.Item1) && _second.trigger(value.Item2); + public bool trigger((T1, T2) value) => + _first.trigger(value.Item1) && + _second.trigger(value.Item2); + + public bool Equals(AndTrigger other) => + other != null && + _first.Equals(other._first) && + _second.Equals(other._second); public override bool Equals(object obj) => - obj is AndTrigger t && _first.Equals(t._first) && _second.Equals(t._second); + Equals(obj as AndTrigger); public override int GetHashCode() => - EqualityComparer.aggregate_hash(_first.GetHashCode(), _second.GetHashCode()); + EqualityComparer.aggregate_hash( + _first.GetHashCode(), + _second.GetHashCode()); - public override string ToString() => $"AndTrigger ({_first}, {_second})"; + public override string ToString() => + $"AndTrigger ({_first}, {_second})"; } - class OrTrigger : IPredicate { + class OrTrigger : IPredicate, IEquatable> { readonly IPredicate _first, _second; public OrTrigger(IPredicate first, IPredicate second) { @@ -160,16 +209,24 @@ namespace mbts { public bool trigger(T value) => _first.trigger(value) || _second.trigger(value); + public bool Equals(OrTrigger other) => + other != null && + _first.Equals(other._first) && + _second.Equals(other._second); + public override bool Equals(object obj) => - obj is OrTrigger t && _first.Equals(t._first) && _second.Equals(t._second); + Equals(obj is OrTrigger); public override int GetHashCode() => - EqualityComparer.aggregate_hash(_first.GetHashCode(), _second.GetHashCode()); + EqualityComparer.aggregate_hash( + _first.GetHashCode(), + _second.GetHashCode()); - public override string ToString() => $"OrTrigger ({_first}, {_second})"; + public override string ToString() => + $"OrTrigger ({_first}, {_second})"; } - class OrTrigger : IPredicate<(T1, T2)> { + class OrTrigger : IPredicate<(T1, T2)>, IEquatable> { readonly IPredicate _first; readonly IPredicate _second; @@ -178,15 +235,25 @@ namespace mbts { _second = second; } - public bool trigger((T1, T2) value) => _first.trigger(value.Item1) || _second.trigger(value.Item2); + public bool trigger((T1, T2) value) => + _first.trigger(value.Item1) || + _second.trigger(value.Item2); + + public bool Equals(OrTrigger other) => + other != null && + _first.Equals(other._first) && + _second.Equals(other._second); public override bool Equals(object obj) => - obj is OrTrigger t && _first.Equals(t._first) && _second.Equals(t._second); + Equals(obj as OrTrigger); public override int GetHashCode() => - EqualityComparer.aggregate_hash(_first.GetHashCode(), _second.GetHashCode()); + EqualityComparer.aggregate_hash( + _first.GetHashCode(), + _second.GetHashCode()); - public override string ToString() => $"OrTrigger ({_first}, {_second})"; + public override string ToString() => + $"OrTrigger ({_first}, {_second})"; } class GreaterThanTrigger : IPredicate { @@ -198,57 +265,109 @@ namespace mbts { _comparer = comparer; } - public bool trigger(T value) => _comparer.Compare(value, _value) > 0; + public bool trigger(T value) => + _comparer.Compare(value, _value) > 0; - public override string ToString() => $"GreaterThanTrigger ({_value})"; + public override string ToString() => + $"GreaterThanTrigger ({_value})"; } - class InSetTrigger: IPredicate { + class GreaterThanOrEqualToTrigger : IPredicate, IEquatable> { + readonly T _value; + readonly IComparer _comparer; + + public GreaterThanOrEqualToTrigger(T value, IComparer comparer) { + _value = value; + _comparer = comparer; + } + + public bool trigger(T value) => + _comparer.Compare(value, _value) >= 0; + + public bool Equals(GreaterThanOrEqualToTrigger other) => + other != null && + _comparer.Equals(other._comparer) && + _comparer.Compare(_value, other._value) == 0; + + public override bool Equals(object obj) => + Equals(obj as GreaterThanOrEqualToTrigger); + + public override int GetHashCode() => + _value.GetHashCode(); + + public override string ToString() => + $"GreaterThanTrigger ({_value})"; + } + + class InSetTrigger : IPredicate, IEquatable> { readonly ISet _set; public InSetTrigger(ISet set) => _set = set; - public bool trigger(T value) => _set.Contains(value); + public bool trigger(T value) => + _set.Contains(value); + + public bool Equals(InSetTrigger other) => + other != null && + // check SetEquals with both sets (IEqualityComparers may differ) + _set.SetEquals(other._set) && + other._set.SetEquals(_set); public override bool Equals(object obj) => obj is InSetTrigger t && _set.SetEquals(t._set); public override int GetHashCode() => - _set.GetHashCode(); + EqualityComparer.auto_phase(_set.Take(8)); - public override string ToString() => $"InSetTrigger (Count: {_set.Count}, type: {typeof(T)})"; + public override string ToString() => + $"InSetTrigger (Count: {_set.Count}, type: {typeof(T)})"; } - class WrapperTrigger : IPredicate { + class WrapperTrigger : IPredicate, IEquatable> { readonly IPredicate _inner_trigger; - readonly Func _selector; + readonly Func _selector; - public WrapperTrigger(IPredicate inner_trigger, Func selector) { + public WrapperTrigger(IPredicate inner_trigger, Func selector) { _inner_trigger = inner_trigger; _selector = selector; } - public bool trigger(TOutter value) => _inner_trigger.trigger(_selector(value)); + public bool trigger(TOuter value) => + _inner_trigger.trigger(_selector(value)); + + public bool Equals(WrapperTrigger other) => + other != null && + _selector.Equals(other._selector) && + _inner_trigger.Equals(other._inner_trigger); public override bool Equals(object obj) => - obj is WrapperTrigger t && _inner_trigger.Equals(t._inner_trigger) && _selector.Equals(t._selector); + Equals(obj as WrapperTrigger); public override int GetHashCode() => - EqualityComparer.aggregate_hash(_inner_trigger.GetHashCode(), _selector.GetHashCode()); + EqualityComparer.aggregate_hash( + _inner_trigger.GetHashCode(), + _selector.GetHashCode()); - public override string ToString() => $"WrapperTrigger (outter-type {typeof(TOutter)}, inner-trigger: {_inner_trigger})"; + public override string ToString() => + $"WrapperTrigger (outer-type {typeof(TOuter)}, inner-trigger: {_inner_trigger})"; } - class NegateTrigger : IPredicate { + class NegateTrigger : IPredicate, IEquatable> { readonly IPredicate _trigger; + public NegateTrigger(IPredicate trigger) => _trigger = trigger; - public bool trigger(T value) => !_trigger.trigger(value); + public bool trigger(T value) => + !_trigger.trigger(value); + + public bool Equals(NegateTrigger other) => + other != null && + _trigger.Equals(other._trigger); public override bool Equals(object obj) => - obj is NegateTrigger t && _trigger.Equals(t._trigger); + Equals(obj as NegateTrigger); public override int GetHashCode() => -_trigger.GetHashCode(); @@ -256,22 +375,22 @@ namespace mbts { public override string ToString() => $"NegateTrigger ({_trigger})"; } - class AnonymousTrigger : IPredicate { + class AnonymousTrigger : IPredicate, IEquatable> { readonly Func _trigger; public AnonymousTrigger(Func trigger) => _trigger = trigger; - public bool trigger(T value) => _trigger(value); + public bool Equals(AnonymousTrigger other) => + other != null && + _trigger.Equals(other._trigger); - public override string ToString() => $"AnonymousTrigger ({typeof(T)})"; - } + public bool trigger(T value) => + _trigger(value); - class AnonymousMutableTrigger : IPredicate { - public AnonymousMutableTrigger(Func predicate) => this.predicate = predicate; - public Func predicate { get; set; } - public bool trigger(T value) => predicate(value); + public override string ToString() => + $"AnonymousTrigger ({typeof(T)})"; } #endregion } -} \ No newline at end of file +} diff --git a/src/client/spark/Predicates/VM/DoublePredicateVM.cs b/src/client/spark/Predicates/VM/DoublePredicateVM.cs new file mode 100644 index 000000000..b386192e8 --- /dev/null +++ b/src/client/spark/Predicates/VM/DoublePredicateVM.cs @@ -0,0 +1,33 @@ +using bts.proto; +using mbts.ui.shell; + +namespace mbts.spark { + class DoublePredicateVM : ViewModelBase, IValueFactory { + double _minimum, _maximum; + DoublePredicate.PredicateTypeOneofCase _type; + + public DoublePredicate.PredicateTypeOneofCase type { get => _type; set => Set(ref _type, value); } + public double minimum { get => _minimum; set => Set(ref _minimum, value); } + public double maximum { get => _maximum; set => Set(ref _maximum, value); } + + public DoublePredicate create() => + DoublePredicate.create(type, minimum, maximum); + + public void load_from(DoublePredicate value) { + if (value == null) + return; + type = value.predicate_type_case; + switch (type) { + case DoublePredicate.PredicateTypeOneofCase.GreaterThan: minimum = value.greater_than.Value; break; + case DoublePredicate.PredicateTypeOneofCase.LessThan: maximum = value.less_than.Value; break; + case DoublePredicate.PredicateTypeOneofCase.InsideRange: _load_range(value.inside_range.Value); break; + case DoublePredicate.PredicateTypeOneofCase.OutsideRange: _load_range(value.outside_range.Value); break; + } + } + + void _load_range(DoubleRange range) { + minimum = range.minimum; + maximum = range.maximum; + } + } +} \ No newline at end of file diff --git a/src/client/spark/Themes/generic.xaml b/src/client/spark/Themes/generic.xaml index 52e66ff7d..8038e6b0b 100644 --- a/src/client/spark/Themes/generic.xaml +++ b/src/client/spark/Themes/generic.xaml @@ -338,7 +338,7 @@ - + diff --git a/src/client/spark/Trades/TradeInfo.cs b/src/client/spark/Trades/TradeInfo.cs new file mode 100644 index 000000000..e1ee23f7a --- /dev/null +++ b/src/client/spark/Trades/TradeInfo.cs @@ -0,0 +1,14 @@ +using bts.api; +using bts.co2; + +namespace mbts.spark { + struct TradeInfo { + public readonly SecurityImmutable security; + public readonly TradeMessageImmutable trade; + + public TradeInfo(SecurityImmutable security, TradeMessageImmutable trade) { + this.security = security; + this.trade = trade; + } + } +} \ No newline at end of file diff --git a/src/client/spark/Trades/TradeMessageExtensions.cs b/src/client/spark/Trades/TradeMessageExtensions.cs new file mode 100644 index 000000000..f01a273d9 --- /dev/null +++ b/src/client/spark/Trades/TradeMessageExtensions.cs @@ -0,0 +1,9 @@ +using bts.co2; +using System; + +namespace mbts.spark { + static class TradeMessageExtensions { + public static double price(this TradeMessageImmutable trade) => + trade.Mantissa * Math.Pow(10, trade.Exponent); + } +} \ No newline at end of file diff --git a/src/client/spark/Trades/TradesSource.cs b/src/client/spark/Trades/TradesSource.cs new file mode 100644 index 000000000..032fbecfc --- /dev/null +++ b/src/client/spark/Trades/TradesSource.cs @@ -0,0 +1,94 @@ +using bts.api; +using bts.api.core; +using bts.co2; +using bts.utils; +using mbts.co2; +using mbts.utils; +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Linq; +using System.Reactive.Linq; + +namespace mbts.spark { + readonly struct Product : IEquatable { + public readonly string symbol; + public readonly SecurityType type; + public readonly Venue exchange; + + public Product(string symbol, SecurityType type, Venue exchange) { + this.symbol = symbol; + this.type = type; + this.exchange = exchange; + } + + public static Product from_security(SecurityImmutable security) => + new Product(security.Symbol, security.security_type(), security.Exchange); + + public bool Equals(Product other) => + symbol == other.symbol && + type == other.type && + exchange == other.exchange; + + public override bool Equals(object obj) => + obj is Product other && Equals(other); + + public override int GetHashCode() => + EqualityComparer.auto_phase( + symbol?.GetHashCode() ?? 0, + type.GetHashCode(), + exchange.GetHashCode()); + + public static bool operator ==(Product a, Product b) => a.Equals(b); + public static bool operator !=(Product a, Product b) => !a.Equals(b); + } + + static class TradesSource { + public static IEnumerable aggregate_security_criteria(IEnumerable securities, IEnumerable security_criterion) => + securities.Where(s => security_criterion.Any(sc => ContractPickerModel.security_in_criteria(sc, s))) + .Select(Product.from_security) + .Distinct(); + + public static IObservable> create(MDConsumer consumer, IObservable> security_map, IObservable> security_criterion, TimeSpan poll_interval) => + security_criterion.CombineLatest(security_map, (criterion, map) => (criterion, map)) + .Scan((channels: ImmutableDictionary.Empty, active: new List(0)), (channel_data, data) => { + var (criterion, map) = data; + var (channels, active) = channel_data; + var products = aggregate_security_criteria(map.Values, criterion); + active = new List(); + foreach (var p in products) { + if (!channels.TryGetValue(p, out var c)) { + c = new ChannelConsumer(consumer.get_channel(p.symbol, p.type, p.exchange), map.Values.Where(s => Product.from_security(s).Equals(p))); + channels = channels.Add(p, c); + } + active.Add(c); + } + return (channels, active); + }).SelectManyInSeries(channel_data => { + var (channels, active) = channel_data; + return Observable.Interval(poll_interval) + .Select(_ => active.SelectMany(c => c.read_trades()).ToList()); + }); + + class ChannelConsumer { + readonly MDConsumerChannel _channel; + readonly Dictionary _securities; + long _cursor = 0; + + public ChannelConsumer(MDConsumerChannel channel) => + _channel = channel; + + public ChannelConsumer(MDConsumerChannel channel, IEnumerable securities) { + _channel = channel; + _securities = securities.ToDictionaryCrushed(s => s.Id); + } + + public IEnumerable read_trades() { + foreach (var tm in _channel.read_trades(ref _cursor)) { + if (tm != null && _securities.TryGetValue(tm.Key, out SecurityImmutable sec)) + yield return new TradeInfo(sec, new TradeMessageImmutable(tm)); + } + } + } + } +} \ No newline at end of file diff --git a/src/client/spark/core/Bus/SparkCommands.cs b/src/client/spark/core/Bus/SparkCommands.cs index 726eff24a..9ed6fa67b 100644 --- a/src/client/spark/core/Bus/SparkCommands.cs +++ b/src/client/spark/core/Bus/SparkCommands.cs @@ -107,6 +107,9 @@ namespace bts.spark { public static SparkCommand ShowActivityLog => SparkCommand.create("Activity Log", Icons.Wrench, SparkTags.ShowActivityLog); + public static SparkCommand ShowGlobalAlerts => + SparkCommand.create("Alerts", Icons.Speaker, SparkTags.ShowGlobalAlertsTag); + public static PartialCommand ShowReportIssue => SparkCommand.create("Report a Problem", Icons.Support, SparkTags.Support); diff --git a/src/client/spark/core/Bus/SparkTags.cs b/src/client/spark/core/Bus/SparkTags.cs index eef9c6d4e..bf009631b 100644 --- a/src/client/spark/core/Bus/SparkTags.cs +++ b/src/client/spark/core/Bus/SparkTags.cs @@ -81,6 +81,8 @@ namespace mbts.spark public static ITag SyntheticDeleteTag { get; } = new SparkTag(nameof(SyntheticDeleteTag)); + public static ITag ShowGlobalAlertsTag { get; } = new SparkTag(nameof(ShowGlobalAlertsTag)); + public class Nothing { Nothing() { } } internal class SparkTag : ITag { diff --git a/src/client/spark/core/ShellInterface/UserSettings/Alerts/GlobalAlertSettings.cs b/src/client/spark/core/ShellInterface/UserSettings/Alerts/GlobalAlertSettings.cs new file mode 100644 index 000000000..839049584 --- /dev/null +++ b/src/client/spark/core/ShellInterface/UserSettings/Alerts/GlobalAlertSettings.cs @@ -0,0 +1,29 @@ +using bts.utils; +using ProtoBuf; +using System; +using System.Collections.Generic; +using System.Linq; + +namespace mbts.spark { + [ProtoContract] + class GlobalAlertSettings : IEquatable { + [ProtoMember(1)] + TradeAlert[] _trade_alerts; + + public GlobalAlertSettings() { } + public GlobalAlertSettings(IEnumerable trade_alerts) => + _trade_alerts = trade_alerts.ToArray(); + + public IReadOnlyList trade_alerts => _trade_alerts ?? Array.Empty(); + + public bool Equals(GlobalAlertSettings other) => + other != null && + trade_alerts.SequenceEqual(other.trade_alerts); + + public override bool Equals(object obj) => + Equals(obj as GlobalAlertSettings); + + public override int GetHashCode() => + EqualityComparer.auto_phase(trade_alerts); + } +} \ No newline at end of file diff --git a/src/client/spark/core/ShellInterface/UserSettings/Alerts/TradeAlertSettings.cs b/src/client/spark/core/ShellInterface/UserSettings/Alerts/TradeAlertSettings.cs new file mode 100644 index 000000000..6892fdfa0 --- /dev/null +++ b/src/client/spark/core/ShellInterface/UserSettings/Alerts/TradeAlertSettings.cs @@ -0,0 +1,121 @@ +using bts.api; +using bts.shell; +using bts.utils; +using ProtoBuf; +using System; +using System.Collections.Generic; + +namespace mbts.spark { + [ProtoContract] + readonly struct TradeAlert : IEquatable { + [ProtoMember(1)] + public readonly TradeAlertPredicate predicate; + [ProtoMember(2)] + public readonly SoundNotification sound; + [ProtoMember(3)] + public readonly bool is_enabled; + + public TradeAlert( + TradeAlertPredicate predicate, + SoundNotification sound = null, + bool is_enabled = false) { + this.predicate = predicate; + this.sound = sound; + this.is_enabled = is_enabled; + } + + public TradeAlert with( + TradeAlertPredicate? predicate = null, + SoundNotification sound = null, + bool? is_enabled = null) => + // + new TradeAlert( + predicate ?? this.predicate, + sound ?? this.sound, + is_enabled ?? this.is_enabled); + + public bool Equals(TradeAlert other) => + predicate.Equals(other.predicate) && + sound.safe_equals(other.sound) && + is_enabled == other.is_enabled; + + public override bool Equals(object obj) => + obj is TradeAlert other && Equals(other); + + public override int GetHashCode() => + EqualityComparer.auto_phase( + predicate.GetHashCode(), + sound?.GetHashCode() ?? 0, + is_enabled.GetHashCode()); + + public static bool operator ==(TradeAlert a, TradeAlert b) => a.Equals(b); + public static bool operator !=(TradeAlert a, TradeAlert b) => !a.Equals(b); + } + + [ProtoContract] + readonly struct TradeAlertPredicate : IEquatable { + [ProtoMember(1)] + public readonly SecurityCriteria security_criteria; + [ProtoMember(2)] + public readonly DoublePredicate quantity; + [ProtoMember(3)] + public readonly DoublePredicate price; + [ProtoMember(4)] + readonly Side[] _side; + + public TradeAlertPredicate( + SecurityCriteria security_criteria = null, + DoublePredicate quantity = null, + DoublePredicate price = null, + Side[] side = null) { + this.security_criteria = security_criteria; + this.quantity = quantity; + this.price = price; + this._side = side; + } + + public IReadOnlyList side => _side ?? Array.Empty(); + + public IPredicate create() { + IPredicate p = null; + // security criteria + var criteria = security_criteria; + if (criteria.is_defined()) { + p = p.and_safe(PredicateBuilder.create(t => ContractPickerModel.security_in_criteria(criteria, t.security))); + } + // quantity + var qpred = quantity?.create(); + if (qpred != null) + p = p.and_safe(PredicateBuilder.wrap(qpred, t => t.trade.Size)); + // price + var ppred = price?.create(); + if (ppred != null) + p = p.and_safe(PredicateBuilder.wrap(ppred, t => t.trade.price())); + // side + if (_side != null && _side.Length == 1) { + var agg_side = _side[0].to_aggressor(); + p = p.and_safe(PredicateBuilder.create(t => agg_side == t.trade.AggressorSide)); + } + return p; + } + + public bool Equals(TradeAlertPredicate other) => + security_criteria.safe_equals(other.security_criteria) && + quantity == other.quantity && + price == other.price && + EqualityComparer.safe_sequence_equals(_side, other._side); + + public override bool Equals(object obj) => + obj is TradeAlertPredicate other && Equals(other); + + public override int GetHashCode() => + EqualityComparer.auto_phase( + security_criteria?.GetHashCode() ?? 0, + quantity.GetHashCode(), + price.GetHashCode(), + _side != null && _side.Length == 1 ? (int)_side[0] : 0); + + public static bool operator ==(TradeAlertPredicate a, TradeAlertPredicate b) => a.Equals(b); + public static bool operator !=(TradeAlertPredicate a, TradeAlertPredicate b) => !a.Equals(b); + } +} \ No newline at end of file diff --git a/src/client/spark/core/ShellInterface/UserSettings/UserSettings.cs b/src/client/spark/core/ShellInterface/UserSettings/UserSettings.cs index 6dbe4c73d..45f018859 100644 --- a/src/client/spark/core/ShellInterface/UserSettings/UserSettings.cs +++ b/src/client/spark/core/ShellInterface/UserSettings/UserSettings.cs @@ -56,6 +56,11 @@ namespace mbts.spark { GridSettings _pnl_grid; [ProtoMember(10)] bts.shell.orderbook.OrderBookGridSettings _order_book_grid; + // Placeholder for PNLSettings (will be merged to master soon) + // [ProtoMember(13)] + // PNLSettings _pnl; + [ProtoMember(14)] + GlobalAlertSettings _alerts; public UserSettings() { } @@ -73,6 +78,8 @@ namespace mbts.spark { public GridSettings pnl_grid => _pnl_grid ?? (_pnl_grid = bts.shell.PAndLWindowFactory.PAndLStartupData.DefaultGridSettings); public bts.shell.orderbook.OrderBookGridSettings order_book_grid => _order_book_grid ?? (_order_book_grid = bts.shell.orderbook.OrderBookStartupData.Default.grid_settings_wrapper()); + public GlobalAlertSettings alerts => _alerts ?? (_alerts = new GlobalAlertSettings()); + public UserSettings with(LadderSettings ladder = null, LadderSettingsProfile[] ladder_profiles = null, NotificationSettings notification = null, @@ -81,7 +88,8 @@ namespace mbts.spark { GridSettings provided_fills_gridsettings = null, GridSettings provided_synthetic_management_gridsettings = null, GridSettings provided_pnl_gridsettings = null, - bts.shell.orderbook.OrderBookGridSettings order_book_grid = null) { + bts.shell.orderbook.OrderBookGridSettings order_book_grid = null, + GlobalAlertSettings alerts = null) { var us = new UserSettings(ladder_profiles ?? _ladder_profiles) { _ladder = ladder ?? _ladder, _notification = notification ?? _notification, @@ -89,8 +97,9 @@ namespace mbts.spark { _time_and_sales_grid = time_and_sales ?? _time_and_sales_grid, _fills_grid = provided_fills_gridsettings ?? _fills_grid, _synthetic_management_grid = provided_synthetic_management_gridsettings ?? _synthetic_management_grid, - _pnl_grid = provided_pnl_gridsettings ?? _pnl_grid, + _pnl_grid = provided_pnl_gridsettings ?? _pnl_grid, _order_book_grid = order_book_grid ?? _order_book_grid, + _alerts = alerts ?? _alerts }; us._last_ladder_profile_id = Math.Max(_last_ladder_profile_id, us.ladder_profiles.Select(p => p.id).MaxOrDefault()); return us; @@ -98,8 +107,9 @@ namespace mbts.spark { public static class FileExtensions { public const string + GRID = "grid", LADDER = "ladder", - GRID = "grid"; + PNL = "pnl"; } } diff --git a/src/client/spark/core/Utility/IPropertyWrapperVM.cs b/src/client/spark/core/Utility/IPropertyWrapperVM.cs index 7db97a542..b8cd8b8da 100644 --- a/src/client/spark/core/Utility/IPropertyWrapperVM.cs +++ b/src/client/spark/core/Utility/IPropertyWrapperVM.cs @@ -59,6 +59,22 @@ namespace mbts.spark { interface ITemplatedPropertyWrapperVM : IPropertyWrapperVM, ITemplateSelectorKey { } + static class ValueFactoryUtils { + public static void sync_with_models(this IList target, IEnumerable models) where TValueFactory : IValueFactory, new() { + target.sync_with_models( + models, + m => { + var vf = new TValueFactory(); + vf.load_from(m); + return vf; + }, + (vf, m) => { + vf.load_from(m); + return vf; + }); + } + } + static class PropertyWrapperVMUtils { public static T create_assigned(this IPropertyWrapperVM vm) where T : new() => vm.create_assigned(() => new T()); diff --git a/src/client/spark/core/data/Proto/ColorOpacityProto.cs b/src/client/spark/core/data/Proto/ColorOpacityProto.cs index c67e51d37..b5d69b2d6 100644 --- a/src/client/spark/core/data/Proto/ColorOpacityProto.cs +++ b/src/client/spark/core/data/Proto/ColorOpacityProto.cs @@ -22,6 +22,7 @@ namespace bts.proto { } public Color color => _color.rgb_color(); + public Color argb_color => Color.FromArgb((byte)(MathUtils.within_range(0, 1, _opacity) * 255.0), color.R, color.G, color.B); public double opacity => _opacity; public ColorOpacityProto with(uint? color = null, double? opacity = null) => diff --git a/src/client/spark/core/data/Proto/NullableColorProto.cs b/src/client/spark/core/data/Proto/NullableColorProto.cs index 3fa15eba3..2fb827d08 100644 --- a/src/client/spark/core/data/Proto/NullableColorProto.cs +++ b/src/client/spark/core/data/Proto/NullableColorProto.cs @@ -16,14 +16,8 @@ namespace bts.proto { public NullableColorProto(uint value) => _value = value; - - public Color? value { - get { - if (_value.HasValue) - return _value.Value.rgb_color(); - return null; - } - } + public Color? value => _value?.rgb_color(); + public Color? argb => _value?.argb_color(); public bool Equals(NullableColorProto other) => EqualityComparer.nullable_equals(_value, other._value); diff --git a/src/client/spark/view/Colors.xaml b/src/client/spark/view/Colors.xaml index 300d3b647..8843b2151 100644 --- a/src/client/spark/view/Colors.xaml +++ b/src/client/spark/view/Colors.xaml @@ -105,6 +105,9 @@ + + #FF4182F6 + #3D25A0DA #FF26A0DA diff --git a/src/client/spark/view/Controls/Adorners/RowSelectionAdorner.cs b/src/client/spark/view/Controls/Adorners/RowSelectionAdorner.cs new file mode 100644 index 000000000..e6079090d --- /dev/null +++ b/src/client/spark/view/Controls/Adorners/RowSelectionAdorner.cs @@ -0,0 +1,98 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Documents; +using System.Windows.Input; +using System.Windows.Media; +using bts.utils; +using mbts.ui.extensions; + +namespace mbts.ui.controls.adorners { + public class RowSelectionAdorner : Adorner, DIYGrid.ISelectionHighlightListener, IDisposable { + Brush _fill = DIYGrid.DefaultSelectionHighlight; + Pen _stroke = DIYGrid.DefaultSelectionStroke; + + DIYGridRowsPresenter _diy_rp; + ScrollViewer _diy_scroll; + ScrollContentPresenter _diy_scp; + List _disposables = new List(); + + #region Fill + public static readonly DependencyProperty FillProperty = + WPFHelper.create_dp( + nameof(Fill), + FrameworkPropertyMetadataOptions.AffectsRender, + (o, v) => o._fill = v, + DIYGrid.DefaultSelectionHighlight); + + public SolidColorBrush Fill { + get => GetValue(FillProperty) as SolidColorBrush; + set => SetValue(FillProperty, value); + } + #endregion + #region Stroke + public static readonly DependencyProperty StrokeProperty = + WPFHelper.create_dp( + nameof(Stroke), + FrameworkPropertyMetadataOptions.AffectsRender, + (o, v) => o._stroke = v, + DIYGrid.DefaultSelectionStroke); + + public Pen Stroke { + get => GetValue(StrokeProperty) as Pen; + set => SetValue(StrokeProperty, value); + } + #endregion + + internal RowSelectionAdorner(DIYGridRowsPresenter adorned_element, ScrollViewer scroll_viewer) : base(adorned_element) { + // we want our clicks to go through to the underlying grid + IsHitTestVisible = false; + + _diy_rp = adorned_element; + _diy_scroll = scroll_viewer; + _diy_scp = _diy_rp.descendants_of_type().empty_if_null().FirstOrDefault(); + + // We actually don't need mouse up/down or key up/down when we can just respond to selection changes + _disposables.Add(((System.Windows.Controls.Primitives.Selector)_diy_rp).SubscribeSelectionChanged((s, e) => InvalidateVisual())); + // so that we update the highlight as the grid scrolls + _disposables.Add(_diy_scroll.SubscribeScrollChanged((s, e) => InvalidateVisual())); + } + + + protected override void OnRender(DrawingContext drawingContext) { + base.OnRender(drawingContext); + if (AdornedElement is ListBox lb && lb.SelectedItems != null && lb.SelectedItems.Count > 0) { + foreach(var lbi in lb.SelectedItems) { + if (_diy_rp.ItemContainerGenerator.ContainerFromItem(lbi) is FrameworkElement row && row.IsVisible) { + var top_left = lb.GetChildTopLeft(row); + var top_is_within_bounds = top_left.Y >= 0; + + // Note that the top of the row can still technically be visible but we wont show + // the adorner rectangle b/c the bottom of the row will be obscured by the scrollbar + var bottom_is_within_bounds = lb.GetChildBounds(row).BottomRight.Y <= _diy_scroll.ActualHeight; + if (top_is_within_bounds && bottom_is_within_bounds) { + // we use the scroll content presenter in the X point calculation instead of the row + // because of the OB which has a right side panel that takes up some space over + // row width + drawingContext.DrawRectangle(_fill, + _stroke, + new Rect(top_left, new Point(top_left.X + _diy_scp.ActualWidth, top_left.Y + row.ActualHeight))); + } + } + } + } + } + + public void on_selection_fill(SolidColorBrush selection_fill) { + Fill = selection_fill; + Stroke = new Pen(selection_fill.Color.to_solid_brush(), 1); + InvalidateVisual(); + } + + public void Dispose() { + _disposables.DisposeAll(); + } + } +} \ No newline at end of file diff --git a/src/client/spark/view/Controls/ColorPicker/ColorPickerPopup.xaml.cs b/src/client/spark/view/Controls/ColorPicker/ColorPickerPopup.xaml.cs index e893b053c..a55734853 100644 --- a/src/client/spark/view/Controls/ColorPicker/ColorPickerPopup.xaml.cs +++ b/src/client/spark/view/Controls/ColorPicker/ColorPickerPopup.xaml.cs @@ -1,7 +1,9 @@ using bts.proto; +using bts.utils; using mbts.spark; using mbts.ui.controls.color_picker; using mbts.ui.shell; +using System; using System.Collections.ObjectModel; using System.Linq; using System.Windows; @@ -38,16 +40,42 @@ namespace mbts.ui.controls { class ColorPickerPopupVM : ViewModelBase, IValueFactory { readonly Property _color; readonly Property _opacity; + ObservableCollection _palettes; + bool _bind_opacity_to_alpha; + IDisposable _opacity_alpha_binding; public ColorPickerPopupVM() { _color = backing(nameof(color), Colors.Black); _opacity = backing(nameof(opacity), 1.0); - palettes = new ObservableCollection(ColorPalette.all_presets().Select(p => new ColorPaletteVM(p))); } public Color color { get => _color.Value; set => _color.set(value); } public double opacity { get => _opacity.Value; set => _opacity.set(value); } - public ObservableCollection palettes { get; } + public ObservableCollection palettes => _palettes ?? (_palettes = new ObservableCollection(ColorPalette.all_presets().Select(p => new ColorPaletteVM(p)))); + public bool bind_opacity_to_alpha { + get => _bind_opacity_to_alpha; + set { + if (_bind_opacity_to_alpha != value) { + Disposable.dispose(ref _opacity_alpha_binding); + _bind_opacity_to_alpha = value; + if (value) { + _opacity.Changed += opacity_changed; + _color.Changed += color_changed; + color_changed(default, color); + void opacity_changed(double oldval, double newval) { + _color.Changed -= color_changed; + _color.set(color.with((byte)(MathUtils.within_range(0, 1, newval) * 255.0))); + _color.Changed += color_changed; + } + void color_changed(Color oldval, Color newval) { + _opacity.Changed -= opacity_changed; + _opacity.set(newval.A / 255.0); + _opacity.Changed += opacity_changed; + } + } + } + } + } public SolidColorBrush create() => new SolidColorBrush(color) { Opacity = opacity }.frozen(); public void load_from(SolidColorBrush brush) { diff --git a/src/client/spark/view/Controls/DIYGrid/CellRender/HyperlinkCell.cs b/src/client/spark/view/Controls/DIYGrid/CellRender/HyperlinkCell.cs index 8d9e326cb..e9e5ae634 100644 --- a/src/client/spark/view/Controls/DIYGrid/CellRender/HyperlinkCell.cs +++ b/src/client/spark/view/Controls/DIYGrid/CellRender/HyperlinkCell.cs @@ -304,11 +304,6 @@ namespace mbts.ui.controls { } drawingContext.Pop(); } - if (bg != null) { - var bgo = GetBackgroundOverlay(this); - if (bgo != null) - drawingContext.DrawRectangle(bgo, null, rect); - } } bool _point_horizontally_over_text(double x) { diff --git a/src/client/spark/view/Controls/DIYGrid/Columns/ColumnBase.cs b/src/client/spark/view/Controls/DIYGrid/Columns/ColumnBase.cs index 3d3e1e1f6..c6ce09a3d 100644 --- a/src/client/spark/view/Controls/DIYGrid/Columns/ColumnBase.cs +++ b/src/client/spark/view/Controls/DIYGrid/Columns/ColumnBase.cs @@ -1,9 +1,8 @@ -using mbts.spark; +using bts; +using mbts.spark; using mbts.spark.filters; using mbts.ui.settings; -using mbts.ui.shell; using System; -using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Reflection; @@ -11,7 +10,7 @@ using System.Windows; using System.Windows.Controls; using System.Windows.Media; -namespace mbts.ui.controls { +namespace mbts.ui.controls { // Column types are nested inside the DIYGrid partial class DIYGrid { public static class DefaultColumnWidths { @@ -165,7 +164,7 @@ namespace mbts.ui.controls { } public interface ISelectionHighlightListener { - void on_selection_fill(Brush selection_fill); + void on_selection_fill(SolidColorBrush selection_fill); } // To include extra data with your column type you are encouraged to derive from DIYGridColumn @@ -173,16 +172,19 @@ namespace mbts.ui.controls { //readonly ExternalProperty _font_weigh FontWeight _fallback_font_weight; Color _fallback_font_color; + Color _fallback_background_color; double _fallback_font_size; FontFamily _fallback_font_family; FontWeight? _font_weight_override; Color? _font_color_override; + Color? _background_color_override; object _header_copy; protected ColumnBase() { var gs = GridSettings.Default; _fallback_font_weight = gs.font_weight; _fallback_font_color = gs.font_color.rgb_color(); + _fallback_background_color = gs.background_color.argb_color(); _fallback_font_size = gs.font_size; _fallback_font_family = new FontFamily(gs.font_family); original_width = double.NaN; @@ -215,6 +217,9 @@ namespace mbts.ui.controls { public FontWeight font_weight => font_weight_override ?? _fallback_font_weight; public Color font_color => font_color_override ?? _fallback_font_color; public Brush font_brush => new SolidColorBrush(font_color); + public Color? background_color_override { get => _background_color_override; set => _set_font_param(ref _background_color_override, value); } + public Color? background_color => background_color_override ?? _fallback_background_color; + public Brush background_brush => background_color?.to_brush(); // TODO: find a better way to store the header-property in a thread-safe manner - a value for GridSettings.display_name, more specifically. // Since save_state is called from a different thread in IShared/SlowWindows, it is not safe to access the DependencyProperty store from that method. // By updating a local _header_copy field in the Header setter, the DependencyProperty lookup may be bypassed when appropriate (see create method below). @@ -224,7 +229,7 @@ namespace mbts.ui.controls { } public GridColumnSettings create() => - new GridColumnSettings(id, _header_copy?.ToString(), is_visible, is_collapsed, font_weight_override, font_color_override, ActualWidth, horizontal_alignment, horizontal_offset); + new GridColumnSettings(id, _header_copy?.ToString(), is_visible, is_collapsed, font_weight_override, font_color_override, ActualWidth, horizontal_alignment, horizontal_offset, background_color_override); void _set_font_param(ref T field, T value) { field = value; @@ -235,7 +240,7 @@ namespace mbts.ui.controls { if (settings == null) return; using (ReflectionHelper.detect_property_changes(this, _raise_prop_changed, nameof(is_visible), nameof(is_collapsed), nameof(font_weight_override), nameof(font_weight), - nameof(font_color_override), nameof(font_color), nameof(font_brush), nameof(font_family), nameof(font_size), nameof(horizontal_alignment), nameof(horizontal_offset))) { + nameof(font_color_override), nameof(font_color), nameof(font_brush), nameof(font_family), nameof(font_size), nameof(horizontal_alignment), nameof(horizontal_offset), nameof(background_color_override), nameof(background_color), nameof(background_brush))) { // id = settings.id; if (!string.IsNullOrEmpty(settings.display_name)) @@ -246,6 +251,7 @@ namespace mbts.ui.controls { font_color_override = settings.font_color_override; horizontal_alignment = settings.horizontal_alignment; horizontal_offset = settings.horizontal_offset; + background_color_override = settings.background_color_override; } if (original_width != settings.width) { original_width = settings.width; @@ -255,11 +261,12 @@ namespace mbts.ui.controls { } // 'fallback' font-params (aka 'grid-level' font-params) - public void set_fallback_font_params(FontFamily font_family, double font_size, Color font_color, FontWeight font_weight) { - using (ReflectionHelper.detect_property_changes(this, _raise_prop_changed, nameof(font_family), nameof(font_size), nameof(font_color), nameof(font_weight))) { + public void set_fallback_font_params(FontFamily font_family, double font_size, Color font_color, FontWeight font_weight, Color background_color) { + using (ReflectionHelper.detect_property_changes(this, _raise_prop_changed, nameof(font_family), nameof(font_size), nameof(font_color), nameof(font_weight), nameof(background_color), nameof(background_brush))) { _fallback_font_family = font_family; _fallback_font_size = font_size; _fallback_font_color = font_color; + _fallback_background_color = background_color; _fallback_font_weight = font_weight; } font_params_changed?.Invoke(); @@ -273,9 +280,25 @@ namespace mbts.ui.controls { } internal abstract class ColumnBase : ColumnBase, IKeyedColumn, IGridColumn { + TColKey _key; + bool _key_initialized; + // need a default constructor to support declaration in xaml + protected ColumnBase() { } protected ColumnBase(TColKey key) => this.key = key; - public TColKey key { get; } + public TColKey key { + get => _key; + set { + if (Equals(_key, value)) + return; + Log.assert(!_key_initialized, "Column key already initialized."); + _key_initialized = true; + _key = value; + on_key_initialized(value); + } + } + + protected virtual void on_key_initialized(TColKey key) { } } } -} \ No newline at end of file +} diff --git a/src/client/spark/view/Controls/DIYGrid/Columns/FrameworkElementColumns/HyperlinkColumn.cs b/src/client/spark/view/Controls/DIYGrid/Columns/FrameworkElementColumns/HyperlinkColumn.cs index 258740e29..2b6b62bf0 100644 --- a/src/client/spark/view/Controls/DIYGrid/Columns/FrameworkElementColumns/HyperlinkColumn.cs +++ b/src/client/spark/view/Controls/DIYGrid/Columns/FrameworkElementColumns/HyperlinkColumn.cs @@ -7,7 +7,7 @@ using System.Windows.Media; namespace mbts.ui.controls { partial class DIYGrid { - internal class HyperlinkElementColumn : FrameworkElementColumnBase, IFrameworkElementColumn, IFilterableColumn, IKeyedColumn, ISelectionHighlightListener { + internal class HyperlinkElementColumn : FrameworkElementColumnBase, IFrameworkElementColumn, IFilterableColumn, IKeyedColumn { static readonly Thickness _default_padding = new Thickness(6, 0, 6, 0); readonly BindingBase _binding, _command_binding; @@ -22,27 +22,17 @@ namespace mbts.ui.controls { public IDataGridColumnFilter filter { get; } public string filter_template { get; } public Thickness padding { get; set; } = _default_padding; - public Brush background { get; set; } - public Brush background_overlay { get; set; } = DefaultSelectionHighlight; - - public void on_selection_fill(Brush selection_fill) => - background_overlay = selection_fill; - + public override FrameworkElement view_factory() { - var hl = new HyperlinkCell { Foreground = font_brush, Background = background, Padding = padding }; + var hl = new HyperlinkCell { Padding = padding }; + hl.SetBinding(HyperlinkCell.ForegroundProperty, new Binding(nameof(font_brush)) { Source = this }); hl.SetBinding(HyperlinkCell.TextProperty, _binding); hl.SetBinding(HyperlinkCell.FontFamilyProperty, new Binding(nameof(font_family)) { Source = this }); hl.SetBinding(HyperlinkCell.FontSizeProperty, new Binding(nameof(font_size)) { Source = this }); hl.SetBinding(HyperlinkCell.HorizontalAlignmentProperty, new Binding(nameof(horizontal_alignment)) { Source = this }); hl.SetBinding(HyperlinkCell.CommandProperty, _command_binding); hl.SetBinding(HyperlinkCell.WidthProperty, new Binding(nameof(ActualWidth)) { Source = this }); - if (background_overlay != null) { - hl.SetBinding(BackgroundOverlayProperty, new Binding(nameof(ListBoxItem.IsSelected)) { - Converter = new AnonymousValueConverter(val => val ? background_overlay : null), - Mode = BindingMode.OneWay, - RelativeSource = new RelativeSource(RelativeSourceMode.FindAncestor, typeof(ListBoxItem), 1) - }); - } + hl.SetBinding(HyperlinkCell.BackgroundProperty, new Binding(nameof(background_brush)) { Source = this }); return hl; } } diff --git a/src/client/spark/view/Controls/DIYGrid/Columns/RenderColumn.cs b/src/client/spark/view/Controls/DIYGrid/Columns/RenderColumn.cs index 4c58bc40d..f5779e1e5 100644 --- a/src/client/spark/view/Controls/DIYGrid/Columns/RenderColumn.cs +++ b/src/client/spark/view/Controls/DIYGrid/Columns/RenderColumn.cs @@ -30,7 +30,7 @@ namespace mbts.ui.controls { Func get_brush = null) : base() { _get_text = get_text; - Func get_default_background_brush = (TRowVM _) => this.background; + Func get_default_background_brush = (TRowVM _) => this.background_brush; _get_background_brush = get_brush ?? get_default_background_brush; this.filter = filter; this.filter_template = filter_template; @@ -42,7 +42,6 @@ namespace mbts.ui.controls { public IDataGridColumnFilter filter { get; } public string filter_template { get; } - public Brush background { get; set; } public VerticalAlignment vertical_alignment { get; set; } = VerticalAlignment.Center; public Thickness padding { get; set; } = DefaultCellPadding; public GlyphContext glyph_context { get; private set; } diff --git a/src/client/spark/view/Controls/DIYGrid/DIYGrid.cs b/src/client/spark/view/Controls/DIYGrid/DIYGrid.cs index fda5d6cc6..ab0ae6d35 100644 --- a/src/client/spark/view/Controls/DIYGrid/DIYGrid.cs +++ b/src/client/spark/view/Controls/DIYGrid/DIYGrid.cs @@ -1,9 +1,9 @@ using bts; +using bts.utils; using mbts.spark.filters; using mbts.ui.controls.adorners; using mbts.ui.extensions; using mbts.ui.utility; -using bts.utils; using System; using System.Collections; using System.Collections.Generic; @@ -12,14 +12,13 @@ using System.Collections.Specialized; using System.ComponentModel; using System.Diagnostics; using System.Linq; +using System.Reactive.Linq; using System.Windows; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Data; using System.Windows.Input; using System.Windows.Media; -using mbts.utils; -using System.Reactive.Linq; namespace mbts.ui.controls { interface IHandleGridSorting { @@ -126,6 +125,7 @@ namespace mbts.ui.controls { double _row_height = DIYGrid.DefaultRowHeight; DIYGrid _grid; DragRectAdorner _drag_rect_adorner; + RowSelectionAdorner _rsa; ScrollViewer _scroll_viewer; Point? _drag_start; double _drag_start_vertical_drift; @@ -148,12 +148,18 @@ namespace mbts.ui.controls { _drag_rect_adorner.SetResourceReference(DragRectAdorner.StrokeProperty, DIYGrid.SelectionStrokeKey); _drag_rect_adorner.attach(); } + _rsa = new RowSelectionAdorner(this, _scroll_viewer); + _rsa.attach(); }; Unloaded += (s, e) => { if (_drag_rect_adorner != null) { _drag_rect_adorner.detach(); Disposable.dispose(ref _drag_rect_adorner); } + if (_rsa != null) { + _rsa.detach(); + Disposable.dispose(ref _rsa); + } }; void on_row_height_changed(double v) => _row_height = v; } @@ -261,6 +267,12 @@ namespace mbts.ui.controls { o.Resources[SelectionStrokeKey] = new Pen(o.SelectionHighlight.Color.to_solid_brush().frozen(), 1).frozen(); foreach (var col in o.Columns.empty_if_null().OfType()) col.on_selection_fill(v); + var ad_layer = System.Windows.Documents.AdornerLayer.GetAdornerLayer(o); + if (ad_layer != null) { + foreach (var ad in ad_layer.descendants_of_type()) { + ad.on_selection_fill(v); + } + } }, (o, v) => v as SolidColorBrush ?? DefaultSelectionHighlight, DefaultSelectionHighlight); @@ -562,6 +574,11 @@ namespace mbts.ui.controls { public static readonly DependencyProperty HeaderTotalSizeHackProperty = DependencyProperty.Register("HeaderTotalSizeHack", typeof(double), typeof(DIYGrid), new FrameworkPropertyMetadata(0.0, dp_invalidate_column_layout)); + public double HeaderTotalSizeHack { + get => (double)GetValue(HeaderTotalSizeHackProperty); + set => SetValue(HeaderTotalSizeHackProperty, value); + } + private static void dp_invalidate_column_layout(DependencyObject d, DependencyPropertyChangedEventArgs unused) { var grid = d as DIYGrid; if (grid != null) { @@ -594,6 +611,61 @@ namespace mbts.ui.controls { // Public Properties #region Public Properties + #region ColumnKey + public static readonly DependencyProperty ColumnKeyProperty = + DependencyProperty.RegisterAttached("ColumnKey", + typeof(object), + typeof(DIYGrid), + new PropertyMetadata((d, e) => { + if (!(d is UIElement child)) + return; + if (VisualTreeHelper.GetParent(child) is Grid panel) { + if (GetSyncWithColumnGeometrySource(d) is DIYGrid diy_grid || panel.try_find_ancestor_of_type(out diy_grid)) + ColumnGeometrySyncHelper.reset_panel_child(child, diy_grid, e.NewValue); + } + })); + + public static object GetColumnKey(DependencyObject d) => d.GetValue(ColumnKeyProperty); + public static void SetColumnKey(DependencyObject d, object value) => d.SetValue(ColumnKeyProperty, value); + #endregion + + #region SyncWithColumnGeometrySource + public static readonly DependencyProperty SyncWithColumnGeometrySourceProperty = + DependencyProperty.RegisterAttached( + "SyncWithColumnGeometrySource", + typeof(DIYGrid), + typeof(DIYGrid), + new PropertyMetadata(ColumnGeometrySyncHelper.reset_sync)); + + public static DIYGrid GetSyncWithColumnGeometrySource(DependencyObject d) => d.GetValue(SyncWithColumnGeometrySourceProperty) as DIYGrid; + public static void SetSyncWithColumnGeometrySource(DependencyObject d, DIYGrid value) => d.SetValue(SyncWithColumnGeometrySourceProperty, value); + #endregion + + #region SyncWithColumnGeometry + public static readonly DependencyProperty SyncWithColumnGeometryProperty = + DependencyProperty.RegisterAttached( + "SyncWithColumnGeometry", + typeof(bool), + typeof(DIYGrid), + new PropertyMetadata(false, ColumnGeometrySyncHelper.reset_sync)); + + public static bool GetSyncWithColumnGeometry(DependencyObject d) => (bool)d.GetValue(SyncWithColumnGeometryProperty); + public static void SetSyncWithColumnGeometry(DependencyObject d, bool value) => d.SetValue(SyncWithColumnGeometryProperty, value); + + static readonly DependencyPropertyKey SyncWithColumnGeometryHookPropertyKey = + DependencyProperty.RegisterAttachedReadOnly( + "SyncWithColumnGeometryHook", + typeof(IDisposable), + typeof(DIYGrid), + new PropertyMetadata(FrameworkElementLifeDependencyHelper.DisposeOld)); + + internal static IDisposable GetSyncWithColumnGeometryHook(DependencyObject d) => + d.GetValue(SyncWithColumnGeometryHookPropertyKey.DependencyProperty) as IDisposable; + + static void SetSyncWithColumnGeometryHook(DependencyObject d, IDisposable value) => + d.SetValue(SyncWithColumnGeometryHookPropertyKey, value); + #endregion + public static readonly DependencyProperty BackgroundOverlayProperty = DependencyProperty.RegisterAttached( "BackgroundOverlay", @@ -783,7 +855,7 @@ namespace mbts.ui.controls { /// Compute the geometry of all visible (or partially visible columns) columns /// This effectively replaces the entire Measure/Arrange pass of the grid rows (and enables column virtualization) /// Mouse events will be hit tested against this as well - internal IEnumerable GetColumnGeometry() { + internal IEnumerable GetColumnGeometry(bool include_obscured_cols = false) { if (_header_scroll_viewer != null && ActualWidth > 0) { double frozen_offset = 0; int vis_frozen_col_count = _get_visible_frozen_column_count(); @@ -805,7 +877,7 @@ namespace mbts.ui.controls { double left = Math.Max(offset, frozen_offset); double right = offset + col.ActualWidth; // If right < frozen_offset column is completely obscured - if (right > frozen_offset && left <= ActualWidth) { + if (include_obscured_cols || (right > frozen_offset && left <= ActualWidth)) { // fully visible yield return new ColumnGeometry() { column = col, @@ -883,6 +955,98 @@ namespace mbts.ui.controls { } #endregion + static class ColumnGeometrySyncHelper { + public static void reset_panel_child(UIElement child, DIYGrid diy_grid) => + reset_panel_child(child, diy_grid, GetColumnKey(child)); + + public static void reset_panel_child(UIElement child, DIYGrid diy_grid, object col_key) { + if (col_key == null) + return; + var key_str = col_key.ToString(); + if (diy_grid._visible_columns.TryGetFirst(c => string.Equals(c.id, key_str, StringComparison.CurrentCultureIgnoreCase), out var target_col, out int target_pos)) { + // set clip to null in case this child was hidden before (see 'else' block). + child.Clip = null; + Grid.SetColumn(child, target_pos); + } else { + // hide element by setting clip to 0x0 rect, rather than visibility to collapsed, + // to avoid incidentally breaking visibility bindings, triggers, animations, etc. + child.Clip = new RectangleGeometry(new Rect(0, 0, 0, 0)); + } + } + + public static void reset_sync(DependencyObject d, DependencyPropertyChangedEventArgs e) { + if (!GetSyncWithColumnGeometry(d)) + SetSyncWithColumnGeometryHook(d, null); + if (!(d is Grid g)) + return; + var hook = new DisposableContainer(); + if (g.IsLoaded) + hook.replace(impl()); + SetSyncWithColumnGeometryHook(d, Disposable.Create(g.SubscribeLoaded(on_loaded), hook)); + // + void on_loaded(object sender, RoutedEventArgs loaded_e) { + if (GetSyncWithColumnGeometry(d)) + hook.replace(impl()); + } + IDisposable impl() { + // Avoid resetting children on every collection change, as that could be very noisy and hurt perf. + // In the visible columns CollectionChanged handler, call reset_children inside a Dispatcher.InvokeAsync request + // to effectively wait for potential batch-changes to finish. + bool resetting_children = false; + if (!(GetSyncWithColumnGeometrySource(d) is DIYGrid diy_grid) && !g.try_find_ancestor_of_type(out diy_grid)) + return null; + g.SetBinding(Grid.WidthProperty, new Binding(nameof(HeaderTotalSizeHack)) { Source = diy_grid }); + reset_children(); + on_layout_changed(diy_grid.GetColumnGeometry(true).ToList()); + diy_grid.ColumnLayoutChanged += on_layout_changed; + diy_grid._visible_columns.CollectionChanged += on_vis_columns_changed; + return Disposable.Create(() => { + diy_grid.ColumnLayoutChanged -= on_layout_changed; + diy_grid._visible_columns.CollectionChanged -= on_vis_columns_changed; + }); + // + void on_vis_columns_changed(object sender, NotifyCollectionChangedEventArgs vce) { + if (!resetting_children) { + // avoid resetting children on every collection change, as that could be very noisy and hurt perf. + resetting_children = true; + diy_grid.Dispatcher.InvokeAsync(() => { + on_layout_changed(diy_grid.GetColumnGeometry().ToList()); + reset_children(); + resetting_children = false; + }); + } + } + void on_layout_changed(List layout) { + // TODO: figure out how to make the ColumnLayoutChanged event lazy, or somehow avoid making 2 lists of columns + // (the layout param does not include obscured cols, so we have to create a new list of ColumnGeoemtry to satisfy our needs). + layout = (from col in diy_grid._visible_columns + join pos in diy_grid.GetColumnGeometry(true) + on col.id equals pos.column.id + select pos).ToList(); + + int n_removed = g.ColumnDefinitions.Count - layout.Count; + if (n_removed > 0) + g.ColumnDefinitions.RemoveRange(g.ColumnDefinitions.Count - n_removed, n_removed); + int i = 0; + for (; i < g.ColumnDefinitions.Count; i++) { + var col_pos = layout[i]; + var col = g.ColumnDefinitions[i]; + if (col.Width.GridUnitType == GridUnitType.Pixel && col.Width.Value == col_pos.visible_width) + continue; + col.Width = new GridLength(col_pos.visible_width, GridUnitType.Pixel); + } + for (; i < layout.Count; i++) { + g.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(layout[i].visible_width, GridUnitType.Pixel) }); + } + } + void reset_children() { + foreach (UIElement child in g.Children) + reset_panel_child(child, diy_grid); + } + } + } + } + class DataContextHooks : IDisposable { List _hooks = new List(4); diff --git a/src/client/spark/view/Controls/DIYGrid/DIYGridResources.xaml b/src/client/spark/view/Controls/DIYGrid/DIYGridResources.xaml index d066fbb96..b4a77bb97 100644 --- a/src/client/spark/view/Controls/DIYGrid/DIYGridResources.xaml +++ b/src/client/spark/view/Controls/DIYGrid/DIYGridResources.xaml @@ -29,22 +29,6 @@ VerticalAlignment="{TemplateBinding VerticalContentAlignment}" /> - - - - - - - - - - - - - - - - @@ -61,6 +45,9 @@ diff --git a/src/client/spark/view/Resources/Converters.xaml b/src/client/spark/view/Resources/Converters.xaml index 12ef41b11..19601cc6c 100644 --- a/src/client/spark/view/Resources/Converters.xaml +++ b/src/client/spark/view/Resources/Converters.xaml @@ -21,6 +21,7 @@ + diff --git a/src/client/spark/view/Resources/WindowStyle.xaml b/src/client/spark/view/Resources/WindowStyle.xaml index e5cfbeda1..a5b05d21e 100644 --- a/src/client/spark/view/Resources/WindowStyle.xaml +++ b/src/client/spark/view/Resources/WindowStyle.xaml @@ -143,6 +143,7 @@ + #FFAAD1FF + + + + + + + + + + + (N/A) + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/client/spark/view/Shell/Workspaces/WorkspacesDialogViewModel.cs b/src/client/spark/view/Shell/Workspaces/WorkspacesDialogViewModel.cs index 80282e25e..72c80dc7d 100644 --- a/src/client/spark/view/Shell/Workspaces/WorkspacesDialogViewModel.cs +++ b/src/client/spark/view/Shell/Workspaces/WorkspacesDialogViewModel.cs @@ -8,12 +8,15 @@ using System.Threading.Tasks; using mbts; using mbts.ui; using mbts.ui.shell; +using bts.spark; +using System.Windows; namespace mbts.ui.shell { public class WorkspacesDialogViewModel : ViewModelBaseWithValidation { private WorkspacesModel _work_model; + IRaiseCanExecuteChangedCommand _load_command, _delete_command, _save_command; public WorkspacesDialogViewModel(WorkspacesModel wm) { @@ -25,36 +28,74 @@ namespace mbts.ui.shell public bool IsPublicWorkspace { get; set; } public bool ShowWorkspaces { get; set; } - public ICommand SaveWorkspace + WorkspaceViewModel _selected_workspace; + public WorkspaceViewModel selected_workspace { + get => _selected_workspace; + set { + if (Set(ref _selected_workspace, value)) { + LoadCommand.TryRaiseCanExecuteChanged(); + DeleteCommand.TryRaiseCanExecuteChanged(); + SaveCommand.TryRaiseCanExecuteChanged(); + } + } + } + + private bool _command_can_execute() => selected_workspace != null; + private void _clear_error_state() => clear_error(nameof(SaveName)); + + public ICommand LoadCommand => _load_command ?? + (_load_command = new DelegateCommand( + () => { + _work_model.load_workspace(selected_workspace.Definition, selected_workspace.Name).ignore(); + _clear_error_state(); + }, _command_can_execute)); + public ICommand DeleteCommand => _delete_command ?? + (_delete_command = new DelegateCommand( + () => { + if (BTSMessageBox.Show( + $"Delete the \"{selected_workspace.Name}\" workspace?", + "Delete Existing Workspace Confirmation", + BTSMessageBoxButtons.Yes | BTSMessageBoxButtons.No, + MessageBoxImage.Question) == BTSMessageBoxButtons.Yes) { + _work_model.delete_workspace(selected_workspace.Name, selected_workspace.Definition).ignore(); + _clear_error_state(); + } + }, _command_can_execute)); + public ICommand SaveCommand => _save_command ?? + (_save_command = new DelegateCommand( + () => { + if (BTSMessageBox.Show( + $"Overwrite \"{selected_workspace.Name}\" with current layout?", + "Save Existing Workspace Confirmation", + BTSMessageBoxButtons.Yes | BTSMessageBoxButtons.No, + MessageBoxImage.Question) == BTSMessageBoxButtons.Yes) { + _work_model.save_workspace(selected_workspace.Name, ispublic:selected_workspace.Definition.is_shared); + _clear_error_state(); + } + }, _command_can_execute)); + + public ICommand SaveNewWorkspace { get { return new DelegateCommand(arg => { + _clear_error_state(); // Check for errors in the input - if (string.IsNullOrEmpty(SaveName)) - { - set_error("SaveName", "Workspace must be named"); + if (string.IsNullOrEmpty(SaveName)) { + set_error(nameof(SaveName), "Workspace must be named"); return; } - if (SaveName.Contains(WorkspacesModel.ACTIVE_WORKSPACE_PREFIX)) - { - set_error("SaveName", "Workspace name cannot contains '{0}'".fmt(WorkspacesModel.ACTIVE_WORKSPACE_PREFIX)); + if (SaveName.Contains(WorkspacesModel.ACTIVE_WORKSPACE_PREFIX)) { + set_error(nameof(SaveName), "Workspace name cannot contains '{0}'".fmt(WorkspacesModel.ACTIVE_WORKSPACE_PREFIX)); return; } - else - { - clear_error("SaveName"); + if (Workspaces.Any(x => x.Name.Replace(WorkspacesModel.SHARED_MONIKER, string.Empty) == SaveName && x.IsShared == IsPublicWorkspace)) { + set_error(nameof(SaveName), $"Workspace already exists '{SaveName}'"); + return; } - var save_candidate_already_exists = Workspaces.Any(x => x.Name.Replace(WorkspacesModel.SHARED_MONIKER, string.Empty) == SaveName && x.IsShared == IsPublicWorkspace); - // Save _work_model.save_workspace(SaveName, ispublic: IsPublicWorkspace); - - // if we just overwrote something, have the vm reflect it - if (save_candidate_already_exists) - Workspaces.Where(x => x.Name.Replace(WorkspacesModel.SHARED_MONIKER, string.Empty) == SaveName && x.IsShared == IsPublicWorkspace).ForEach(x => x.VisualState = "Overridden"); }); } } - } } diff --git a/src/client/spark/view/Shell/Workspaces/WorkspacesModel.cs b/src/client/spark/view/Shell/Workspaces/WorkspacesModel.cs index 867c34b18..7f55387d7 100644 --- a/src/client/spark/view/Shell/Workspaces/WorkspacesModel.cs +++ b/src/client/spark/view/Shell/Workspaces/WorkspacesModel.cs @@ -179,6 +179,7 @@ namespace mbts.ui.shell public void save_workspace(string name, bool persist=true, bool ispublic=false) { WorkspaceDefinition workspace = get_workspace(); workspace.is_shared = ispublic; + workspace.last_save_lldatetime = LLDateTime.now().value; if (ispublic) { name += SHARED_MONIKER; } // Remove the old one if a workspace by this name exists already @@ -282,5 +283,8 @@ namespace mbts.ui.shell [ProtoMember(10, IsRequired = false)] public bool is_shared { get; set; } + [ProtoMember(11, IsRequired = false)] + public ulong last_save_lldatetime { get; set; } + } } diff --git a/src/client/spark/view/Utility/EnumHelper.cs b/src/client/spark/view/Utility/EnumHelper.cs index 3fc0c8926..ff87cca95 100644 --- a/src/client/spark/view/Utility/EnumHelper.cs +++ b/src/client/spark/view/Utility/EnumHelper.cs @@ -79,7 +79,8 @@ namespace mbts.ui.utility { long lflags = Convert.ToInt64(flags); foreach (TEnum e in get_values()) { long lval = Convert.ToInt64(e); - if ((lval & lflags)!= 0) + long common_bits = lval & lflags; + if (common_bits != 0 && common_bits == lval) yield return e; } } diff --git a/src/client/spark/view/Utility/ThreadedWindowLauncher.cs b/src/client/spark/view/Utility/ThreadedWindowLauncher.cs new file mode 100644 index 000000000..2af677603 --- /dev/null +++ b/src/client/spark/view/Utility/ThreadedWindowLauncher.cs @@ -0,0 +1,121 @@ +using bts; +using mbts.utils; +using System; +using System.Diagnostics; +using System.Threading; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Threading; + +namespace mbts.ui.utilities { + class ThreadedWindowLauncher { + const int _min_thread_count = 1; + static readonly int _max_thread_count = Environment.ProcessorCount; + readonly string _name; + readonly int _thread_count; + int _counter; + DispatcherContainer[] _cache; + readonly LoggerContext _log; + + public ThreadedWindowLauncher(string name) + : this(name, _max_thread_count) { } + + public ThreadedWindowLauncher(string name, int thread_count) { + ExceptionAssert.Argument.Between(thread_count, _min_thread_count, _max_thread_count, nameof(thread_count)); + _log = new LoggerContext(Log.Ui, $"{nameof(ThreadedWindowLauncher)} {name ?? "(anon)"} ", null); + _name = name; + _thread_count = thread_count; + _cache = new DispatcherContainer[thread_count]; + } + + public void show(Func factory) => + _show(factory, Interlocked.Increment(ref _counter) % _thread_count); + + void _show(Func factory, int thread_id) { + var dc = _cache[thread_id]; + if (dc != null) { + if (Interlocked.Increment(ref dc.window_count) == 1) { + // If window_count was 0 (before incrementing), the dispatcher must be shutting down. + // Since its initial count is 1, the only way it could have reached 0 is if all windows were closed, which triggers a shutdown. + _init_dispatcher(dc); + } + } else { + // the container may have been assigned since we last checked (if another thread is simultaneously executing this code block). + var late_dc = Interlocked.Exchange(ref _cache[thread_id], dc = new DispatcherContainer(thread_id)); + if (late_dc == null) + _init_dispatcher(dc); + } + _show_on_dispatcher(dc, factory); + } + + async void _show_on_dispatcher(DispatcherContainer dc, Func factory) { + const int max_loops = 50; + int count = 0; + var stopwatch = new Stopwatch(); + stopwatch.Start(); + // dc.dispatcher is only assigned once, so it is safe to access it after a null check (despite this being multithreaded code) + while (dc.dispatcher == null || dc.dispatcher.HasShutdownStarted) { + await Task.Delay(100); + if (++count == max_loops) { + stopwatch.Stop(); + // give up + _log.warn($"failed to open window: timed out waiting for dispatcher (looped {count} times over the course of {stopwatch.Elapsed:mm\\:ss\\.ff})."); + return; + } + } + await dc.dispatcher.InvokeAsync(() => { + var win = factory(); + win.Closed += closed; + win.Show(); + void closed(object sender, EventArgs e) { + if (Interlocked.Decrement(ref dc.window_count) == 0 && !dc.dispatcher.HasShutdownStarted) + dc.dispatcher.BeginInvokeShutdown(DispatcherPriority.Background); + } + }); + } + + void _init_dispatcher(DispatcherContainer dc) { + // kick off the new thread, and setup the dispatcher + var thread = new Thread(start) { + IsBackground = true + }; + thread.SetApartmentState(ApartmentState.STA); + thread.Start(); + // + void start() { + dc.dispatcher = Dispatcher.CurrentDispatcher; + try { + dc.dispatcher.UnhandledException += on_dispatcher_unhandled_exception; + Dispatcher.Run(); + } catch (Exception ex) { + _log.warn($"dispatcher caught an exception (shutting down dispatcher): {ex}"); + dispose_core(); + } + void on_dispatcher_unhandled_exception(object sender, DispatcherUnhandledExceptionEventArgs e) { + BTSApplicationBootstrapper.CurrentDispatcher_HandleClipboardError(sender, e); + if (!e.Handled) { + _log.error($"unhandled exception in dispatcher: {e.Exception}"); + if (!e.Dispatcher.HasShutdownStarted) + e.Dispatcher.BeginInvokeShutdown(DispatcherPriority.Send); + } + } + void dispose_core() { + if (!dc.dispatcher.HasShutdownStarted) + dc.dispatcher.BeginInvokeShutdown(DispatcherPriority.Background); + } + } + } + + // This simple wrapper allows dispatchers to be 'read' atomically via Interlocked. + // Since creation of a new Dispatcher is asynchronous, the wrapper acts as a placeholder until it is finally assigned. + class DispatcherContainer { + public readonly int id; + + public DispatcherContainer(int id) => + this.id = id; + + public Dispatcher dispatcher { get; set; } + public int window_count = 1; + } + } +} \ No newline at end of file diff --git a/src/client/spark_api/utils/Log.cs b/src/client/spark_api/utils/Log.cs index 6526cb32a..d3b86f5d0 100644 --- a/src/client/spark_api/utils/Log.cs +++ b/src/client/spark_api/utils/Log.cs @@ -64,6 +64,31 @@ namespace bts { static extern void Logger_log (Level level, Subsystem subsystem, string message, string file, int line); } + public readonly struct LoggerContext { + readonly string _prefix, _suffix; + readonly Logger _logger; + + public LoggerContext(Logger logger, string prefix, string suffix) { + _prefix = prefix; + _suffix = suffix; + _logger = logger; + } + + public void diag(string message) => _logger.diag(_fmt(message)); + public void info(string message) => _logger.info(_fmt(message)); + public void warn(string message) => _logger.warn(_fmt(message)); + public void error(string message) => _logger.error(_fmt(message)); + public void fatal(string message) => _logger.fatal(_fmt(message)); + + string _fmt(string message) { + if (_prefix != null) + message = _prefix + message; + if (_suffix != null) + message += _suffix; + return message; + } + } + public static class Log { internal static Logger Gen => new Logger(Subsystem.gen); internal static Logger Config => new Logger(Subsystem.Config); @@ -130,5 +155,5 @@ namespace bts { logger.warn(message, file, line); #endif } - } + } } diff --git a/src/client/spark_core/utils/Exceptions/ExceptionAssert.cs b/src/client/spark_core/utils/Exceptions/ExceptionAssert.cs index 05a86f42e..e61beb3fe 100644 --- a/src/client/spark_core/utils/Exceptions/ExceptionAssert.cs +++ b/src/client/spark_core/utils/Exceptions/ExceptionAssert.cs @@ -44,6 +44,11 @@ namespace mbts.utils { throw new ArgumentException($"Must equal {value}.", name); } + public static void Between(T argument, T minimum, T maximum, string name) where T : struct, IComparable { + if (argument.CompareTo(minimum) < 0 || argument.CompareTo(maximum) > 0) + throw new ArgumentException($"Must be between {minimum} and {maximum}, inclusive (actually {argument}).", name); + } + public static void GreaterThan(T argument, T value, string name) where T : IComparable { if (argument.CompareTo(value) <= 0) throw new ArgumentException($"Must be greater than {value}.", name); diff --git a/src/client/spark_core/utils/GlobalExtensions.cs b/src/client/spark_core/utils/GlobalExtensions.cs index 7433968b4..b8d93f6bc 100644 --- a/src/client/spark_core/utils/GlobalExtensions.cs +++ b/src/client/spark_core/utils/GlobalExtensions.cs @@ -67,6 +67,22 @@ namespace mbts { } } - + public static void sync_with_models(this IList target, IEnumerable models, Func add_factory, Func update_factory) { + var model_list = models as IList ?? models.ToList(); + if (model_list.Count == 0) { + target.Clear(); + } else { + int stop = Math.Min(target.Count, model_list.Count); + for (int i = 0; i < stop; i++) { + target[i] = update_factory(target[i], model_list[i]); + } + while (target.Count < model_list.Count) { + target.Add(add_factory(model_list[target.Count])); + } + while (model_list.Count < target.Count) { + target.RemoveAt(model_list.Count); + } + } + } } } \ No newline at end of file diff --git a/src/data_files/CMakeDeps.cmake b/src/data_files/CMakeDeps.cmake index c72de1cbb..de9a0184e 100644 --- a/src/data_files/CMakeDeps.cmake +++ b/src/data_files/CMakeDeps.cmake @@ -1 +1 @@ -set(sources files/Onixs.BTS.lic;files/cert_secure_logon.txt;files/futures.coconut.xz;files/onixs_ice/ConnectivityConfiguration.APITest.xml;files/onixs_ice/ConnectivityConfiguration.PerfTest.xml;files/onixs_ice/ConnectivityConfiguration.Production.xml;files/perf_trace/compiled.css;files/perf_trace/index.html;files/perf_trace/jquery-3.3.1.min.js;files/perf_trace/main.js;files/perf_trace/perf_log.sql;files/perf_trace/perf_trace_analysis.sql;files/perf_trace/plotly-latest.min.js) \ No newline at end of file +set(sources files/cert_secure_logon.txt;files/futures.coconut.xz;files/onixs_ice/ConnectivityConfiguration.APITest.xml;files/onixs_ice/ConnectivityConfiguration.PerfTest.xml;files/onixs_ice/ConnectivityConfiguration.Production.xml;files/perf_trace/compiled.css;files/perf_trace/index.html;files/perf_trace/jquery-3.3.1.min.js;files/perf_trace/main.js;files/perf_trace/perf_log.sql;files/perf_trace/perf_trace_analysis.sql;files/perf_trace/plotly-latest.min.js) \ No newline at end of file diff --git a/src/data_files/files/Onixs.BTS.lic b/src/data_files/files/Onixs.BTS.lic deleted file mode 100644 index 9ff33e7a2..000000000 --- a/src/data_files/files/Onixs.BTS.lic +++ /dev/null @@ -1,16 +0,0 @@ - - production - - Blue Trading Systems OF 9420-2 - - - 2019-05-02 - 2020-05-13 - - - - - - - 5E50A1DACD94D7C1BECD316EEAE5AB02 - \ No newline at end of file diff --git a/src/lib/CMakeDeps.cmake b/src/lib/CMakeDeps.cmake index d6f6bbed7..fd330f977 100644 --- a/src/lib/CMakeDeps.cmake +++ b/src/lib/CMakeDeps.cmake @@ -1 +1 @@ -set(sources api/apicore.proto;api/apigateway.proto;api/apioptions.proto;api/core/ApiClientInterop.cpp;api/core/ApiServerInterop.cpp;api/public/ApiServer.cpp;api/public/ClientChannel.cpp;api/public/QuickbusClientChannel.cpp;api/public/ServerChannel.cpp;api/public/ServiceContext.cpp;api/service_helpers/AdminServiceUtils.cpp;api/service_helpers/AlgoServiceUtils.cpp;api/services/AdminService.proto;api/services/AlgoDefinitionService.proto;api/services/AlgoService.proto;api/services/ApiUnitTestService.proto;api/services/AuthService.proto;api/services/ErrorReportService.proto;api/services/HelloService.proto;api/services/MBOService.proto;api/services/MarginService.proto;api/services/MarketDataAuxiliaryService.proto;api/services/MarketDataRelay.proto;api/services/OrderService.proto;api/services/OutOfProcessURLListener.proto;api/services/PersistenceService.proto;api/services/PositionService.proto;api/services/ShellDiagnosticService.proto;api/services/ShellLatencyService.proto;api/services/SyntheticSecurityService.proto;api/test/ApiTests.cpp;api/test/HelloServiceServer.cpp;config/ConfigCheck.cpp;config/ConfigDownloader.cpp;config/ConfigErrorCollector.cpp;config/ConfigLog.cpp;config/ConfigPropertyEvaluator.cpp;config/ConfigValueQueue.cpp;config/ConfigurationException.cpp;config/ConfigurationState.cpp;config/PreprocessInputStream.cpp;config/config.cpp;config/defaults/MarketData.conf;config/defaults/Ports.conf;config/defaults/Symbols.conf;config/defaults/cme_reference_data.conf;config/defaults/edge.conf;config/defaults/jetfix.conf;config/defaults/keycode.conf;config/defaults/logging.conf;config/defaults/orderman_cfg.conf;config/defaults/orders_fills_cleanup.conf;config/defaults/span.conf;config/defaults/spreader.conf;config/defaults/testkeys.conf;config/defaults/threads.conf;config/defaults/toggles.conf;config/extensions/extensions.proto;config/invalid/invalid.proto;config/protos/ExchangeSimCfg.proto;config/protos/MarketData.proto;config/protos/Ports.proto;config/protos/Symbols.proto;config/protos/UI.proto;config/protos/cme_reference_data.proto;config/protos/jetfix.proto;config/protos/keycode.proto;config/protos/logging.proto;config/protos/mercury_cfg.proto;config/protos/orderman_cfg.proto;config/protos/orders_fills_cleanup.proto;config/protos/perflog_cfg.proto;config/protos/quickbus_cfg.proto;config/protos/span.proto;config/protos/spreader.proto;config/protos/system.proto;config/protos/testkeys.proto;config/protos/threads.proto;config/protos/toggles.proto;config/tests/HTTPServer.cpp;config/tests/config_ref_tests.cpp;config/tests/config_tests.cpp;config/text_format/text_format.cpp;domain_model/Security.cpp;domain_model/Security.proto;domain_model/SecurityTests.cpp;domain_model/tests/domain_tests.cpp;expression/BooleanGrammar.cpp;expression/ExpressionEvaluator.cpp;expression/ParserExceptions.cpp;expression/Value.cpp;expression/tests/expression_parser_tests.cpp;jetfix/codec/FIXArray.cpp;jetfix/common/OutFIX.cpp;jetfix/connection/AsyncReader.cpp;jetfix/connection/IConnection.cpp;jetfix/connection/SocketConnection.cpp;jetfix/gateway/CoreGateway.cpp;jetfix/gateway/JetFIXGateway.cpp;jetfix/gateway/Session.cpp;jetfix/store/FIXFileStore.cpp;jetfix/store/session_name.cpp;jetfix/tests/async_reader_tests.cpp;jetfix/tests/decoding_tests.cpp;jetfix/tests/fix_encoding_stream_tests.cpp;jetfix/tests/fix_fragment_tests.cpp;jetfix/tests/jetfix_performance_tests.cpp;jetfix/tests/sample_fix.cpp;jetfix/tests/store_tests.cpp;logging/LoggerHub.cpp;logging/Sink.cpp;logging/logging.cpp;logging/tests/logging_tests.cpp;md/Diag/MDPeriodicDumper.cpp;md/Diag/ShmDumper.cpp;md/MBOProcessor.cpp;md/MBOServiceServer.cpp;md/MDClient.cpp;md/MDConsumer.cpp;md/MDConsumerHandle.cpp;md/MDConsumerInterop.cpp;md/MDProducer.cpp;md/MDProducerHandle.cpp;md/MemorySegmentUtils.cpp;md/PlatformLoader.cpp;md/PriceSize.cpp;md/SecurityCache.cpp;md/SecurityDB.cpp;md/SecurityIDRecorder.cpp;md/SecurityMapper.cpp;md/SecurityOracle.cpp;md/SettlementRecorder.cpp;md/Shm/FixedSecurity.cpp;md/SyntheticSecurityService.cpp;md/cme/MDP3Utils.cpp;md/common.cpp;md/ice/ICEUtils.cpp;md/protos/co2.proto;md/relay/QueryServer.cpp;md/relay/RelayClient.cpp;md/relay/RelayRecorder.cpp;md/test/Co2ManagedTestHelper.cpp;md/test/Co2TestInstrument.cpp;md/test/mbo_tests.cpp;md/test/md2_tests.cpp;md/test/md_test_utils.cpp;md/test/synthetic_book_merge_tests.cpp;mercury/actors/IPollableActor.cpp;mercury/broker/Broker.cpp;mercury/broker/BrokerProxy.cpp;mercury/broker/ILocalBroker.cpp;mercury/broker/IRemoteBroker.cpp;mercury/common/mercury_common.cpp;mercury/events/TimerEvent.cpp;mercury/executor/Executor.cpp;mercury/topics/Topic.cpp;metrics/metrics.cpp;metrics/system_metrics.cpp;orderman/actors/AsyncFactory.cpp;orderman/actors/ExecutionGateway.cpp;orderman/actors/FillStore.cpp;orderman/actors/MDSupplementarySource.cpp;orderman/actors/OrderStore.cpp;orderman/actors/SODPosition.cpp;orderman/actors/SecuritySrc.cpp;orderman/actors/ServiceBridge.cpp;orderman/actors/order_manager/OrderBuilder.cpp;orderman/actors/order_manager/OrderManager.cpp;orderman/actors/order_manager/OrderServices.cpp;orderman/actors/order_manager/OrderServicesData.cpp;orderman/core/IOrderServices.cpp;orderman/events/CancelRejectEvent.cpp;orderman/events/NewExecutionReportEvent.cpp;orderman/limiter/LimitStore.cpp;orderman/limiter/Limiter.cpp;orderman/limiter/ProductLimitNode.cpp;orderman/limiter/ProductLimitTree.cpp;orderman/limiter/SecurityLimitNode.cpp;orderman/limiter/SecurityLimitTree.cpp;orderman/limiter/tests/limit_tests.cpp;orderman/order_factory/DynamicOrderRegistry.cpp;orderman/order_factory/OrderFactory.cpp;orderman/order_router/OrderRouter.cpp;orderman/orderman_utils/fix_order_codec.cpp;orderman/orderman_utils/orderman_utils.cpp;orderman/orders/CompositeOrder.cpp;orderman/orders/DynamicOrder.cpp;orderman/orders/NativeOrder.cpp;orderman/orders/Order.cpp;orderman/orders/TimeBoxOrder.cpp;orderman/orders/TriggerOrder.cpp;orderman/orders/algo/AlgoWrapperOrder.cpp;orderman/orders/algo/DynamicHelpers.cpp;orderman/orders/algo/IAlgoOrder.cpp;orderman/orders/algo/IAlgoServices.cpp;orderman/orders/algo/IBeforeLaunchAlgoServices.cpp;orderman/orders/algo/algo_orders/CoverAlgo.cpp;orderman/orders/algo/algo_orders/DormanAlgo.cpp;orderman/orders/algo/algo_orders/IcebergAlgo.cpp;orderman/orders/algo/algo_orders/JoinAlgo.cpp;orderman/orders/algo/algo_orders/LeanAlgo.cpp;orderman/orders/algo/algo_orders/OffsetAlgo.cpp;orderman/orders/algo/algo_orders/ProRataAlgo.cpp;orderman/orders/algo/algo_orders/RegisterDorman.cpp;orderman/orders/algo/algo_orders/ScratchAlgo.cpp;orderman/orders/algo/algo_orders/SplitterAlgo.cpp;orderman/orders/algo/algo_orders/TopAlgo.cpp;orderman/orders/algo/algo_orders/tests/AlgoTestDriver.cpp;orderman/orders/algo/algo_orders/tests/dorman_tests.cpp;orderman/orders/algo/algo_orders/tests/splitter_tests.cpp;orderman/orders/book_algos/BookAlgo.cpp;orderman/orders/book_algos/BookOrderBase.cpp;orderman/orders/book_algos/OCOOrder.cpp;orderman/orders/book_algos/PricerOrder.cpp;orderman/orders/queue_holder/QueueHolderOrder.cpp;orderman/orders/queue_holder/state_workers/QHOEndStateWorker.cpp;orderman/orders/queue_holder/state_workers/QHOStartStateWorker.cpp;orderman/orders/queue_holder/state_workers/QHOWaitingForAckStateWorker.cpp;orderman/orders/queue_holder/state_workers/QHOWaitingForCancelAllStateWorker.cpp;orderman/orders/queue_holder/state_workers/QHOWorkingStateWorker.cpp;orderman/orders/spreader_orders/SpreaderOrder.cpp;orderman/orders/spreader_orders/spreader/LegFillState.cpp;orderman/orders/spreader_orders/spreader/LegPropertyData.cpp;orderman/orders/spreader_orders/spreader/NLegsHedgeRecompData.cpp;orderman/orders/spreader_orders/spreader/QuoteLegPriceQuantityState.cpp;orderman/orders/spreader_orders/spreader/SingleFillHedger.cpp;orderman/orders/spreader_orders/spreader/SingleLegQuoter.cpp;orderman/orders/spreader_orders/spreader/SpreaderBookkeepingData.cpp;orderman/orders/spreader_orders/spreader/SpreaderChildOrderState.cpp;orderman/orders/spreader_orders/spreader/SpreaderLegData.cpp;orderman/orders/spreader_orders/spreader/SpreaderUtils.cpp;orderman/orders/spreader_orders/spreader/external_interfacing/SpreaderOrderBuilder.cpp;orderman/orders/spreader_orders/spreader/external_interfacing/SpreaderOrderServices.cpp;orderman/orders/spreader_orders/spreader/external_interfacing/SpreaderPreActivationOrderServices.cpp;orderman/orders/spreader_orders/spreader/hedger/HedgerManager.cpp;orderman/orders/spreader_orders/spreader/hedger/UnhedgedDelta.cpp;orderman/orders/spreader_orders/spreader/hedger/hedger_states/HedgerEndStateWorker.cpp;orderman/orders/spreader_orders/spreader/hedger/hedger_states/HedgerStartStateWorker.cpp;orderman/orders/spreader_orders/spreader/hedger/hedger_states/HedgerWaitingForCancelAckStateWorker.cpp;orderman/orders/spreader_orders/spreader/hedger/hedger_states/HedgerWaitingForFirstAckCancelledStateWorker.cpp;orderman/orders/spreader_orders/spreader/hedger/hedger_states/HedgerWaitingForFirstAckStateWorker.cpp;orderman/orders/spreader_orders/spreader/hedger/hedger_states/HedgerWorkingStateWorker.cpp;orderman/orders/spreader_orders/spreader/quoter/QuoteDriverSet.cpp;orderman/orders/spreader_orders/spreader/quoter/QuoteDriverSetHistory.cpp;orderman/orders/spreader_orders/spreader/quoter/QuoteLegDriver.cpp;orderman/orders/spreader_orders/spreader/quoter/quoter_states/QuoterEndStateWorker.cpp;orderman/orders/spreader_orders/spreader/quoter/quoter_states/QuoterStartStateWorker.cpp;orderman/orders/spreader_orders/spreader/quoter/quoter_states/QuoterWaitingForCancelAckStateWorker.cpp;orderman/orders/spreader_orders/spreader/quoter/quoter_states/QuoterWaitingForFirstAckCancelledWorker.cpp;orderman/orders/spreader_orders/spreader/quoter/quoter_states/QuoterWaitingForFirstAckWorker.cpp;orderman/orders/spreader_orders/spreader/quoter/quoter_states/QuoterWaitingForIOCWorker.cpp;orderman/orders/spreader_orders/spreader/quoter/quoter_states/QuoterWaitingForSizeStateWorker.cpp;orderman/orders/spreader_orders/spreader/quoter/quoter_states/QuoterWorkingStateWorker.cpp;orderman/orders/spreader_orders/spreader_states/SpreaderEndStateWorker.cpp;orderman/orders/spreader_orders/spreader_states/SpreaderStartStateWorker.cpp;orderman/orders/spreader_orders/spreader_states/SpreaderWaitingForCancelAllStateWorker.cpp;orderman/orders/spreader_orders/spreader_states/SpreaderWaitingForInitialDataStateWorker.cpp;orderman/orders/spreader_orders/spreader_states/SpreaderWorkingStateWorker.cpp;orderman/orders/spreader_orders/tests/spreader_tests.cpp;orderman/server/OrderServiceServer.cpp;orderman/tests/fat_wrapper_tests.cpp;os/os.cpp;os/tests/os_tests.cpp;persistence/IStore.cpp;persistence/PersistenceServiceServer.cpp;persistence/SqliteStore.cpp;persistence/persistence_utils.cpp;persistence/tests/PersistenceServiceTests.cpp;plugin/SparkServices.cpp;plugin/plugin.cpp;quickbus/core/LocalNode.cpp;quickbus/core/Quickbus.cpp;quickbus/core/SubscriptionID.cpp;quickbus/core/TableID.cpp;quickbus/message_model/Update.cpp;quickbus/message_model/merge_updates.cpp;quickbus/network/QBConnection.cpp;quickbus/network/QBConnectionManager.cpp;quickbus/network/endpoint_description.cpp;quickbus/network/quickbus_msgs.proto;quickbus/pubsub/TablePublisher.cpp;quickbus/pubsub/TableSubscriber.cpp;quickbus/pubsub/tests/qb_pubsub_tests.cpp;quickbus/routing/INode.cpp;quickbus/routing/NodeID.cpp;quickbus/routing/Router.cpp;quickbus/rpc/RPCClient.cpp;quickbus/rpc/RPCServer.cpp;quickbus/rpc/RPCSessionID.cpp;quickbus/rpc/rpc_utils.cpp;quickbus/rpc/tests/qb_rpc_tests.cpp;quickbus/tests/quickbus_tests.cpp;sparkproto/SparkProtos.proto;testing/catch_test_runner.cpp;tracing/PerfLog.cpp;tracing/bts_trace.cpp;utils/AuthSessionManager.cpp;utils/AuthToken.cpp;utils/Dispatcher.cpp;utils/GrowableSPSCQueue.cpp;utils/HTTPStream.cpp;utils/PBUtils.cpp;utils/Puid.cpp;utils/SecureLogon.cpp;utils/SharedMemory.cpp;utils/Sqlite_utils.cpp;utils/Uuid.cpp;utils/crypto/CipherType.cpp;utils/crypto/CryptoInit.cpp;utils/crypto/Digest.cpp;utils/crypto/KeyCodeHelper.cpp;utils/crypto/PasswordCallback.cpp;utils/crypto/PrivateKey.cpp;utils/crypto/PublicKey.cpp;utils/crypto/iostreambio.cpp;utils/datetime.cpp;utils/download.cpp;utils/file_utils.cpp;utils/init_spark_lib.cpp;utils/is_unittest_environment.cpp;utils/stats.cpp;utils/tests/AuthTokenTests.cpp;utils/tests/SingleWriterConcurrentVectorTests.cpp;utils/thread_manager.cpp) \ No newline at end of file +set(sources api/apicore.proto;api/apigateway.proto;api/apioptions.proto;api/core/ApiClientInterop.cpp;api/core/ApiServerInterop.cpp;api/public/ApiServer.cpp;api/public/ClientChannel.cpp;api/public/QuickbusClientChannel.cpp;api/public/ServerChannel.cpp;api/public/ServiceContext.cpp;api/service_helpers/AdminServiceUtils.cpp;api/service_helpers/AlgoServiceUtils.cpp;api/services/AdminService.proto;api/services/AlgoDefinitionService.proto;api/services/AlgoService.proto;api/services/ApiUnitTestService.proto;api/services/AuthService.proto;api/services/ErrorReportService.proto;api/services/HelloService.proto;api/services/MBOService.proto;api/services/MarginService.proto;api/services/MarketDataAuxiliaryService.proto;api/services/MarketDataRelay.proto;api/services/OrderService.proto;api/services/OutOfProcessURLListener.proto;api/services/PersistenceService.proto;api/services/PositionService.proto;api/services/ShellDiagnosticService.proto;api/services/ShellLatencyService.proto;api/services/SyntheticSecurityService.proto;api/test/ApiTests.cpp;api/test/HelloServiceServer.cpp;config/ConfigCheck.cpp;config/ConfigDownloader.cpp;config/ConfigErrorCollector.cpp;config/ConfigLog.cpp;config/ConfigPropertyEvaluator.cpp;config/ConfigValueQueue.cpp;config/ConfigurationException.cpp;config/ConfigurationState.cpp;config/PreprocessInputStream.cpp;config/config.cpp;config/defaults/MarketData.conf;config/defaults/Ports.conf;config/defaults/Symbols.conf;config/defaults/cme_reference_data.conf;config/defaults/edge.conf;config/defaults/jetfix.conf;config/defaults/keycode.conf;config/defaults/logging.conf;config/defaults/orderman_cfg.conf;config/defaults/orders_fills_cleanup.conf;config/defaults/span.conf;config/defaults/spreader.conf;config/defaults/testkeys.conf;config/defaults/threads.conf;config/defaults/toggles.conf;config/extensions/extensions.proto;config/invalid/invalid.proto;config/protos/ExchangeSimCfg.proto;config/protos/MarketData.proto;config/protos/Ports.proto;config/protos/Symbols.proto;config/protos/UI.proto;config/protos/cme_reference_data.proto;config/protos/jetfix.proto;config/protos/keycode.proto;config/protos/logging.proto;config/protos/mercury_cfg.proto;config/protos/orderman_cfg.proto;config/protos/orders_fills_cleanup.proto;config/protos/perflog_cfg.proto;config/protos/quickbus_cfg.proto;config/protos/span.proto;config/protos/spreader.proto;config/protos/system.proto;config/protos/testkeys.proto;config/protos/threads.proto;config/protos/toggles.proto;config/tests/HTTPServer.cpp;config/tests/config_ref_tests.cpp;config/tests/config_tests.cpp;config/text_format/text_format.cpp;domain_model/Security.cpp;domain_model/Security.proto;domain_model/SecurityTests.cpp;domain_model/tests/domain_tests.cpp;expression/BooleanGrammar.cpp;expression/ExpressionEvaluator.cpp;expression/ParserExceptions.cpp;expression/Value.cpp;expression/tests/expression_parser_tests.cpp;jetfix/codec/FIXArray.cpp;jetfix/common/OutFIX.cpp;jetfix/connection/AsyncReader.cpp;jetfix/connection/IConnection.cpp;jetfix/connection/SocketConnection.cpp;jetfix/gateway/CoreGateway.cpp;jetfix/gateway/JetFIXGateway.cpp;jetfix/gateway/Session.cpp;jetfix/store/FIXFileStore.cpp;jetfix/store/session_name.cpp;jetfix/tests/async_reader_tests.cpp;jetfix/tests/decoding_tests.cpp;jetfix/tests/fix_encoding_stream_tests.cpp;jetfix/tests/fix_fragment_tests.cpp;jetfix/tests/jetfix_performance_tests.cpp;jetfix/tests/sample_fix.cpp;jetfix/tests/store_tests.cpp;logging/LoggerHub.cpp;logging/Sink.cpp;logging/logging.cpp;logging/tests/logging_tests.cpp;md/Diag/MDPeriodicDumper.cpp;md/Diag/ShmDumper.cpp;md/MBOProcessor.cpp;md/MBOServiceServer.cpp;md/MDClient.cpp;md/MDConsumer.cpp;md/MDConsumerHandle.cpp;md/MDConsumerInterop.cpp;md/MDProducer.cpp;md/MDProducerHandle.cpp;md/MemorySegmentUtils.cpp;md/PlatformLoader.cpp;md/PriceSize.cpp;md/SecurityCache.cpp;md/SecurityDB.cpp;md/SecurityIDRecorder.cpp;md/SecurityMapper.cpp;md/SecurityOracle.cpp;md/SettlementRecorder.cpp;md/Shm/FixedSecurity.cpp;md/SyntheticSecurityService.cpp;md/cme/MDP3Utils.cpp;md/common.cpp;md/ice/ICEUtils.cpp;md/protos/co2.proto;md/relay/QueryServer.cpp;md/relay/RelayClient.cpp;md/relay/RelayRecorder.cpp;md/test/Co2ManagedTestHelper.cpp;md/test/Co2TestInstrument.cpp;md/test/mbo_tests.cpp;md/test/md2_tests.cpp;md/test/md_test_utils.cpp;md/test/synthetic_book_merge_tests.cpp;md/vendor/OnixsUtils.cpp;mercury/actors/IPollableActor.cpp;mercury/broker/Broker.cpp;mercury/broker/BrokerProxy.cpp;mercury/broker/ILocalBroker.cpp;mercury/broker/IRemoteBroker.cpp;mercury/common/mercury_common.cpp;mercury/events/TimerEvent.cpp;mercury/executor/Executor.cpp;mercury/topics/Topic.cpp;metrics/metrics.cpp;metrics/system_metrics.cpp;orderman/actors/AsyncFactory.cpp;orderman/actors/ExecutionGateway.cpp;orderman/actors/FillStore.cpp;orderman/actors/MDSupplementarySource.cpp;orderman/actors/OrderStore.cpp;orderman/actors/SODPosition.cpp;orderman/actors/SecuritySrc.cpp;orderman/actors/ServiceBridge.cpp;orderman/actors/order_manager/OrderBuilder.cpp;orderman/actors/order_manager/OrderManager.cpp;orderman/actors/order_manager/OrderServices.cpp;orderman/actors/order_manager/OrderServicesData.cpp;orderman/core/IOrderServices.cpp;orderman/events/CancelRejectEvent.cpp;orderman/events/NewExecutionReportEvent.cpp;orderman/limiter/LimitStore.cpp;orderman/limiter/Limiter.cpp;orderman/limiter/ProductLimitNode.cpp;orderman/limiter/ProductLimitTree.cpp;orderman/limiter/SecurityLimitNode.cpp;orderman/limiter/SecurityLimitTree.cpp;orderman/limiter/tests/limit_tests.cpp;orderman/order_factory/DynamicOrderRegistry.cpp;orderman/order_factory/OrderFactory.cpp;orderman/order_router/OrderRouter.cpp;orderman/orderman_utils/fix_order_codec.cpp;orderman/orderman_utils/orderman_utils.cpp;orderman/orders/CompositeOrder.cpp;orderman/orders/DynamicOrder.cpp;orderman/orders/NativeOrder.cpp;orderman/orders/Order.cpp;orderman/orders/TimeBoxOrder.cpp;orderman/orders/TriggerOrder.cpp;orderman/orders/algo/AlgoWrapperOrder.cpp;orderman/orders/algo/DynamicHelpers.cpp;orderman/orders/algo/IAlgoOrder.cpp;orderman/orders/algo/IAlgoServices.cpp;orderman/orders/algo/IBeforeLaunchAlgoServices.cpp;orderman/orders/algo/algo_orders/CoverAlgo.cpp;orderman/orders/algo/algo_orders/DormanAlgo.cpp;orderman/orders/algo/algo_orders/IcebergAlgo.cpp;orderman/orders/algo/algo_orders/JoinAlgo.cpp;orderman/orders/algo/algo_orders/LeanAlgo.cpp;orderman/orders/algo/algo_orders/OffsetAlgo.cpp;orderman/orders/algo/algo_orders/ProRataAlgo.cpp;orderman/orders/algo/algo_orders/RegisterDorman.cpp;orderman/orders/algo/algo_orders/ScratchAlgo.cpp;orderman/orders/algo/algo_orders/SplitterAlgo.cpp;orderman/orders/algo/algo_orders/TopAlgo.cpp;orderman/orders/algo/algo_orders/tests/AlgoTestDriver.cpp;orderman/orders/algo/algo_orders/tests/dorman_tests.cpp;orderman/orders/algo/algo_orders/tests/splitter_tests.cpp;orderman/orders/book_algos/BookAlgo.cpp;orderman/orders/book_algos/BookOrderBase.cpp;orderman/orders/book_algos/OCOOrder.cpp;orderman/orders/book_algos/PricerOrder.cpp;orderman/orders/queue_holder/QueueHolderOrder.cpp;orderman/orders/queue_holder/state_workers/QHOEndStateWorker.cpp;orderman/orders/queue_holder/state_workers/QHOStartStateWorker.cpp;orderman/orders/queue_holder/state_workers/QHOWaitingForAckStateWorker.cpp;orderman/orders/queue_holder/state_workers/QHOWaitingForCancelAllStateWorker.cpp;orderman/orders/queue_holder/state_workers/QHOWorkingStateWorker.cpp;orderman/orders/spreader_orders/SpreaderOrder.cpp;orderman/orders/spreader_orders/spreader/LegFillState.cpp;orderman/orders/spreader_orders/spreader/LegPropertyData.cpp;orderman/orders/spreader_orders/spreader/NLegsHedgeRecompData.cpp;orderman/orders/spreader_orders/spreader/QuoteLegPriceQuantityState.cpp;orderman/orders/spreader_orders/spreader/SingleFillHedger.cpp;orderman/orders/spreader_orders/spreader/SingleLegQuoter.cpp;orderman/orders/spreader_orders/spreader/SpreaderBookkeepingData.cpp;orderman/orders/spreader_orders/spreader/SpreaderChildOrderState.cpp;orderman/orders/spreader_orders/spreader/SpreaderLegData.cpp;orderman/orders/spreader_orders/spreader/SpreaderUtils.cpp;orderman/orders/spreader_orders/spreader/external_interfacing/SpreaderOrderBuilder.cpp;orderman/orders/spreader_orders/spreader/external_interfacing/SpreaderOrderServices.cpp;orderman/orders/spreader_orders/spreader/external_interfacing/SpreaderPreActivationOrderServices.cpp;orderman/orders/spreader_orders/spreader/hedger/HedgerManager.cpp;orderman/orders/spreader_orders/spreader/hedger/UnhedgedDelta.cpp;orderman/orders/spreader_orders/spreader/hedger/hedger_states/HedgerEndStateWorker.cpp;orderman/orders/spreader_orders/spreader/hedger/hedger_states/HedgerStartStateWorker.cpp;orderman/orders/spreader_orders/spreader/hedger/hedger_states/HedgerWaitingForCancelAckStateWorker.cpp;orderman/orders/spreader_orders/spreader/hedger/hedger_states/HedgerWaitingForFirstAckCancelledStateWorker.cpp;orderman/orders/spreader_orders/spreader/hedger/hedger_states/HedgerWaitingForFirstAckStateWorker.cpp;orderman/orders/spreader_orders/spreader/hedger/hedger_states/HedgerWorkingStateWorker.cpp;orderman/orders/spreader_orders/spreader/quoter/QuoteDriverSet.cpp;orderman/orders/spreader_orders/spreader/quoter/QuoteDriverSetHistory.cpp;orderman/orders/spreader_orders/spreader/quoter/QuoteLegDriver.cpp;orderman/orders/spreader_orders/spreader/quoter/quoter_states/QuoterEndStateWorker.cpp;orderman/orders/spreader_orders/spreader/quoter/quoter_states/QuoterStartStateWorker.cpp;orderman/orders/spreader_orders/spreader/quoter/quoter_states/QuoterWaitingForCancelAckStateWorker.cpp;orderman/orders/spreader_orders/spreader/quoter/quoter_states/QuoterWaitingForFirstAckCancelledWorker.cpp;orderman/orders/spreader_orders/spreader/quoter/quoter_states/QuoterWaitingForFirstAckWorker.cpp;orderman/orders/spreader_orders/spreader/quoter/quoter_states/QuoterWaitingForIOCWorker.cpp;orderman/orders/spreader_orders/spreader/quoter/quoter_states/QuoterWaitingForSizeStateWorker.cpp;orderman/orders/spreader_orders/spreader/quoter/quoter_states/QuoterWorkingStateWorker.cpp;orderman/orders/spreader_orders/spreader_states/SpreaderEndStateWorker.cpp;orderman/orders/spreader_orders/spreader_states/SpreaderStartStateWorker.cpp;orderman/orders/spreader_orders/spreader_states/SpreaderWaitingForCancelAllStateWorker.cpp;orderman/orders/spreader_orders/spreader_states/SpreaderWaitingForInitialDataStateWorker.cpp;orderman/orders/spreader_orders/spreader_states/SpreaderWorkingStateWorker.cpp;orderman/orders/spreader_orders/tests/spreader_tests.cpp;orderman/server/OrderServiceServer.cpp;orderman/tests/fat_wrapper_tests.cpp;os/os.cpp;os/tests/os_tests.cpp;persistence/IStore.cpp;persistence/PersistenceServiceServer.cpp;persistence/SqliteStore.cpp;persistence/persistence_utils.cpp;persistence/tests/PersistenceServiceTests.cpp;plugin/SparkServices.cpp;plugin/plugin.cpp;quickbus/core/LocalNode.cpp;quickbus/core/Quickbus.cpp;quickbus/core/SubscriptionID.cpp;quickbus/core/TableID.cpp;quickbus/message_model/Update.cpp;quickbus/message_model/merge_updates.cpp;quickbus/network/QBConnection.cpp;quickbus/network/QBConnectionManager.cpp;quickbus/network/endpoint_description.cpp;quickbus/network/quickbus_msgs.proto;quickbus/pubsub/TablePublisher.cpp;quickbus/pubsub/TableSubscriber.cpp;quickbus/pubsub/tests/qb_pubsub_tests.cpp;quickbus/routing/INode.cpp;quickbus/routing/NodeID.cpp;quickbus/routing/Router.cpp;quickbus/rpc/RPCClient.cpp;quickbus/rpc/RPCServer.cpp;quickbus/rpc/RPCSessionID.cpp;quickbus/rpc/rpc_utils.cpp;quickbus/rpc/tests/qb_rpc_tests.cpp;quickbus/tests/quickbus_tests.cpp;sparkproto/SparkProtos.proto;testing/catch_test_runner.cpp;tracing/PerfLog.cpp;tracing/bts_trace.cpp;utils/AuthSessionManager.cpp;utils/AuthToken.cpp;utils/Dispatcher.cpp;utils/GrowableSPSCQueue.cpp;utils/HTTPStream.cpp;utils/PBUtils.cpp;utils/Puid.cpp;utils/SecureLogon.cpp;utils/SharedMemory.cpp;utils/Sqlite_utils.cpp;utils/Uuid.cpp;utils/crypto/CipherType.cpp;utils/crypto/CryptoInit.cpp;utils/crypto/Digest.cpp;utils/crypto/KeyCodeHelper.cpp;utils/crypto/PasswordCallback.cpp;utils/crypto/PrivateKey.cpp;utils/crypto/PublicKey.cpp;utils/crypto/iostreambio.cpp;utils/datetime.cpp;utils/download.cpp;utils/file_utils.cpp;utils/init_spark_lib.cpp;utils/is_unittest_environment.cpp;utils/stats.cpp;utils/tests/AuthTokenTests.cpp;utils/tests/SingleWriterConcurrentVectorTests.cpp;utils/thread_manager.cpp) \ No newline at end of file diff --git a/src/lib/CMakeDeps_win.cmake b/src/lib/CMakeDeps_win.cmake index afeace7fe..ecd7b1cc6 100644 --- a/src/lib/CMakeDeps_win.cmake +++ b/src/lib/CMakeDeps_win.cmake @@ -1 +1 @@ -set(sources api/apicore.proto;api/apigateway.proto;api/apioptions.proto;api/core/ApiClientInterop.cpp;api/core/ApiServerInterop.cpp;api/public/ApiServer.cpp;api/public/ClientChannel.cpp;api/public/QuickbusClientChannel.cpp;api/public/ServerChannel.cpp;api/public/ServiceContext.cpp;api/service_helpers/AdminServiceUtils.cpp;api/service_helpers/AlgoServiceUtils.cpp;api/services/AdminService.proto;api/services/AlgoDefinitionService.proto;api/services/AlgoService.proto;api/services/ApiUnitTestService.proto;api/services/AuthService.proto;api/services/ErrorReportService.proto;api/services/HelloService.proto;api/services/MBOService.proto;api/services/MarginService.proto;api/services/MarketDataAuxiliaryService.proto;api/services/MarketDataRelay.proto;api/services/OrderService.proto;api/services/OutOfProcessURLListener.proto;api/services/PersistenceService.proto;api/services/PositionService.proto;api/services/ShellDiagnosticService.proto;api/services/ShellLatencyService.proto;api/services/SyntheticSecurityService.proto;api/test/ApiTests.cpp;api/test/HelloServiceServer.cpp;config/ConfigCheck.cpp;config/ConfigDownloader.cpp;config/ConfigErrorCollector.cpp;config/ConfigLog.cpp;config/ConfigPropertyEvaluator.cpp;config/ConfigValueQueue.cpp;config/ConfigurationException.cpp;config/ConfigurationState.cpp;config/PreprocessInputStream.cpp;config/config.cpp;config/defaults/MarketData.conf;config/defaults/Ports.conf;config/defaults/Symbols.conf;config/defaults/cme_reference_data.conf;config/defaults/edge.conf;config/defaults/jetfix.conf;config/defaults/keycode.conf;config/defaults/logging.conf;config/defaults/orderman_cfg.conf;config/defaults/orders_fills_cleanup.conf;config/defaults/span.conf;config/defaults/spreader.conf;config/defaults/testkeys.conf;config/defaults/threads.conf;config/defaults/toggles.conf;config/extensions/extensions.proto;config/invalid/invalid.proto;config/protos/ExchangeSimCfg.proto;config/protos/MarketData.proto;config/protos/Ports.proto;config/protos/Symbols.proto;config/protos/UI.proto;config/protos/cme_reference_data.proto;config/protos/jetfix.proto;config/protos/keycode.proto;config/protos/logging.proto;config/protos/mercury_cfg.proto;config/protos/orderman_cfg.proto;config/protos/orders_fills_cleanup.proto;config/protos/perflog_cfg.proto;config/protos/quickbus_cfg.proto;config/protos/span.proto;config/protos/spreader.proto;config/protos/system.proto;config/protos/testkeys.proto;config/protos/threads.proto;config/protos/toggles.proto;config/tests/HTTPServer.cpp;config/tests/config_ref_tests.cpp;config/tests/config_tests.cpp;config/text_format/text_format.cpp;domain_model/Security.cpp;domain_model/Security.proto;domain_model/SecurityTests.cpp;domain_model/tests/domain_tests.cpp;expression/BooleanGrammar.cpp;expression/ExpressionEvaluator.cpp;expression/ParserExceptions.cpp;expression/Value.cpp;expression/tests/expression_parser_tests.cpp;logging/LoggerHub.cpp;logging/Sink.cpp;logging/logging.cpp;logging/tests/logging_tests.cpp;md/Diag/MDPeriodicDumper.cpp;md/Diag/ShmDumper.cpp;md/MBOProcessor.cpp;md/MBOServiceServer.cpp;md/MDClient.cpp;md/MDConsumer.cpp;md/MDConsumerHandle.cpp;md/MDConsumerInterop.cpp;md/MDProducer.cpp;md/MDProducerHandle.cpp;md/MemorySegmentUtils.cpp;md/PlatformLoader.cpp;md/PriceSize.cpp;md/SecurityCache.cpp;md/SecurityDB.cpp;md/SecurityIDRecorder.cpp;md/SecurityMapper.cpp;md/SecurityOracle.cpp;md/SettlementRecorder.cpp;md/Shm/FixedSecurity.cpp;md/SyntheticSecurityService.cpp;md/cme/MDP3Utils.cpp;md/common.cpp;md/ice/ICEUtils.cpp;md/protos/co2.proto;md/relay/QueryServer.cpp;md/relay/RelayClient.cpp;md/relay/RelayRecorder.cpp;md/test/Co2ManagedTestHelper.cpp;md/test/Co2TestInstrument.cpp;md/test/mbo_tests.cpp;md/test/md2_tests.cpp;md/test/md_test_utils.cpp;md/test/synthetic_book_merge_tests.cpp;os/os.cpp;os/tests/os_tests.cpp;quickbus/core/LocalNode.cpp;quickbus/core/Quickbus.cpp;quickbus/core/SubscriptionID.cpp;quickbus/core/TableID.cpp;quickbus/message_model/Update.cpp;quickbus/message_model/merge_updates.cpp;quickbus/network/QBConnection.cpp;quickbus/network/QBConnectionManager.cpp;quickbus/network/endpoint_description.cpp;quickbus/network/quickbus_msgs.proto;quickbus/pubsub/TablePublisher.cpp;quickbus/pubsub/TableSubscriber.cpp;quickbus/pubsub/tests/qb_pubsub_tests.cpp;quickbus/routing/INode.cpp;quickbus/routing/NodeID.cpp;quickbus/routing/Router.cpp;quickbus/rpc/RPCClient.cpp;quickbus/rpc/RPCServer.cpp;quickbus/rpc/RPCSessionID.cpp;quickbus/rpc/rpc_utils.cpp;quickbus/rpc/tests/qb_rpc_tests.cpp;quickbus/tests/quickbus_tests.cpp;sparkproto/SparkProtos.proto;testing/catch_test_runner.cpp;utils/AuthSessionManager.cpp;utils/AuthToken.cpp;utils/Dispatcher.cpp;utils/GrowableSPSCQueue.cpp;utils/HTTPStream.cpp;utils/PBUtils.cpp;utils/Puid.cpp;utils/SecureLogon.cpp;utils/SharedMemory.cpp;utils/Sqlite_utils.cpp;utils/Uuid.cpp;utils/crypto/CipherType.cpp;utils/crypto/CryptoInit.cpp;utils/crypto/Digest.cpp;utils/crypto/KeyCodeHelper.cpp;utils/crypto/PasswordCallback.cpp;utils/crypto/PrivateKey.cpp;utils/crypto/PublicKey.cpp;utils/crypto/iostreambio.cpp;utils/datetime.cpp;utils/download.cpp;utils/file_utils.cpp;utils/init_spark_lib.cpp;utils/is_unittest_environment.cpp;utils/stats.cpp;utils/tests/AuthTokenTests.cpp;utils/tests/SingleWriterConcurrentVectorTests.cpp;utils/thread_manager.cpp) \ No newline at end of file +set(sources api/apicore.proto;api/apigateway.proto;api/apioptions.proto;api/core/ApiClientInterop.cpp;api/core/ApiServerInterop.cpp;api/public/ApiServer.cpp;api/public/ClientChannel.cpp;api/public/QuickbusClientChannel.cpp;api/public/ServerChannel.cpp;api/public/ServiceContext.cpp;api/service_helpers/AdminServiceUtils.cpp;api/service_helpers/AlgoServiceUtils.cpp;api/services/AdminService.proto;api/services/AlgoDefinitionService.proto;api/services/AlgoService.proto;api/services/ApiUnitTestService.proto;api/services/AuthService.proto;api/services/ErrorReportService.proto;api/services/HelloService.proto;api/services/MBOService.proto;api/services/MarginService.proto;api/services/MarketDataAuxiliaryService.proto;api/services/MarketDataRelay.proto;api/services/OrderService.proto;api/services/OutOfProcessURLListener.proto;api/services/PersistenceService.proto;api/services/PositionService.proto;api/services/ShellDiagnosticService.proto;api/services/ShellLatencyService.proto;api/services/SyntheticSecurityService.proto;api/test/ApiTests.cpp;api/test/HelloServiceServer.cpp;config/ConfigCheck.cpp;config/ConfigDownloader.cpp;config/ConfigErrorCollector.cpp;config/ConfigLog.cpp;config/ConfigPropertyEvaluator.cpp;config/ConfigValueQueue.cpp;config/ConfigurationException.cpp;config/ConfigurationState.cpp;config/PreprocessInputStream.cpp;config/config.cpp;config/defaults/MarketData.conf;config/defaults/Ports.conf;config/defaults/Symbols.conf;config/defaults/cme_reference_data.conf;config/defaults/edge.conf;config/defaults/jetfix.conf;config/defaults/keycode.conf;config/defaults/logging.conf;config/defaults/orderman_cfg.conf;config/defaults/orders_fills_cleanup.conf;config/defaults/span.conf;config/defaults/spreader.conf;config/defaults/testkeys.conf;config/defaults/threads.conf;config/defaults/toggles.conf;config/extensions/extensions.proto;config/invalid/invalid.proto;config/protos/ExchangeSimCfg.proto;config/protos/MarketData.proto;config/protos/Ports.proto;config/protos/Symbols.proto;config/protos/UI.proto;config/protos/cme_reference_data.proto;config/protos/jetfix.proto;config/protos/keycode.proto;config/protos/logging.proto;config/protos/mercury_cfg.proto;config/protos/orderman_cfg.proto;config/protos/orders_fills_cleanup.proto;config/protos/perflog_cfg.proto;config/protos/quickbus_cfg.proto;config/protos/span.proto;config/protos/spreader.proto;config/protos/system.proto;config/protos/testkeys.proto;config/protos/threads.proto;config/protos/toggles.proto;config/tests/HTTPServer.cpp;config/tests/config_ref_tests.cpp;config/tests/config_tests.cpp;config/text_format/text_format.cpp;domain_model/Security.cpp;domain_model/Security.proto;domain_model/SecurityTests.cpp;domain_model/tests/domain_tests.cpp;expression/BooleanGrammar.cpp;expression/ExpressionEvaluator.cpp;expression/ParserExceptions.cpp;expression/Value.cpp;expression/tests/expression_parser_tests.cpp;logging/LoggerHub.cpp;logging/Sink.cpp;logging/logging.cpp;logging/tests/logging_tests.cpp;md/Diag/MDPeriodicDumper.cpp;md/Diag/ShmDumper.cpp;md/MBOProcessor.cpp;md/MBOServiceServer.cpp;md/MDClient.cpp;md/MDConsumer.cpp;md/MDConsumerHandle.cpp;md/MDConsumerInterop.cpp;md/MDProducer.cpp;md/MDProducerHandle.cpp;md/MemorySegmentUtils.cpp;md/PlatformLoader.cpp;md/PriceSize.cpp;md/SecurityCache.cpp;md/SecurityDB.cpp;md/SecurityIDRecorder.cpp;md/SecurityMapper.cpp;md/SecurityOracle.cpp;md/SettlementRecorder.cpp;md/Shm/FixedSecurity.cpp;md/SyntheticSecurityService.cpp;md/cme/MDP3Utils.cpp;md/common.cpp;md/ice/ICEUtils.cpp;md/protos/co2.proto;md/relay/QueryServer.cpp;md/relay/RelayClient.cpp;md/relay/RelayRecorder.cpp;md/test/Co2ManagedTestHelper.cpp;md/test/Co2TestInstrument.cpp;md/test/mbo_tests.cpp;md/test/md2_tests.cpp;md/test/md_test_utils.cpp;md/test/synthetic_book_merge_tests.cpp;md/vendor/OnixsUtils.cpp;os/os.cpp;os/tests/os_tests.cpp;quickbus/core/LocalNode.cpp;quickbus/core/Quickbus.cpp;quickbus/core/SubscriptionID.cpp;quickbus/core/TableID.cpp;quickbus/message_model/Update.cpp;quickbus/message_model/merge_updates.cpp;quickbus/network/QBConnection.cpp;quickbus/network/QBConnectionManager.cpp;quickbus/network/endpoint_description.cpp;quickbus/network/quickbus_msgs.proto;quickbus/pubsub/TablePublisher.cpp;quickbus/pubsub/TableSubscriber.cpp;quickbus/pubsub/tests/qb_pubsub_tests.cpp;quickbus/routing/INode.cpp;quickbus/routing/NodeID.cpp;quickbus/routing/Router.cpp;quickbus/rpc/RPCClient.cpp;quickbus/rpc/RPCServer.cpp;quickbus/rpc/RPCSessionID.cpp;quickbus/rpc/rpc_utils.cpp;quickbus/rpc/tests/qb_rpc_tests.cpp;quickbus/tests/quickbus_tests.cpp;sparkproto/SparkProtos.proto;testing/catch_test_runner.cpp;utils/AuthSessionManager.cpp;utils/AuthToken.cpp;utils/Dispatcher.cpp;utils/GrowableSPSCQueue.cpp;utils/HTTPStream.cpp;utils/PBUtils.cpp;utils/Puid.cpp;utils/SecureLogon.cpp;utils/SharedMemory.cpp;utils/Sqlite_utils.cpp;utils/Uuid.cpp;utils/crypto/CipherType.cpp;utils/crypto/CryptoInit.cpp;utils/crypto/Digest.cpp;utils/crypto/KeyCodeHelper.cpp;utils/crypto/PasswordCallback.cpp;utils/crypto/PrivateKey.cpp;utils/crypto/PublicKey.cpp;utils/crypto/iostreambio.cpp;utils/datetime.cpp;utils/download.cpp;utils/file_utils.cpp;utils/init_spark_lib.cpp;utils/is_unittest_environment.cpp;utils/stats.cpp;utils/tests/AuthTokenTests.cpp;utils/tests/SingleWriterConcurrentVectorTests.cpp;utils/thread_manager.cpp) \ No newline at end of file diff --git a/src/lib/config/protos/MarketData.proto b/src/lib/config/protos/MarketData.proto index 3992aaf7f..18c08950a 100755 --- a/src/lib/config/protos/MarketData.proto +++ b/src/lib/config/protos/MarketData.proto @@ -127,7 +127,8 @@ message CMEOptions optional bool validate_mbo = 35 [default = false]; } - optional string onixs_license = 1 [default = "{default}"]; + // optional string onixs_license = 1 [default = "{default}"]; + reserved 1; repeated CMEChannel channel = 3; repeated FeedEngineSettings feed_engine = 5; @@ -174,11 +175,16 @@ message ICEOptions optional bool load_security_db = 41 [default = true]; } - optional string onixs_license = 1 [default = "{default}"]; + // optional string onixs_license = 1 [default = "{default}"]; + reserved 1; optional string ice_config_file = 2 [default = "ConnectivityConfiguration.Production.xml"]; repeated ICEChannel channel = 3; } +message OnixsOptions { + optional string onixs_license = 1 [default = "{default}"]; +} + message RecordOptions { // optional string output_path = 2 [default = "/home/bts/md/today"]; optional bool enable_depth = 3 [default = false]; diff --git a/src/lib/md/cme/MDP3Utils.cpp b/src/lib/md/cme/MDP3Utils.cpp index 1f09eb931..f1a8d7b41 100644 --- a/src/lib/md/cme/MDP3Utils.cpp +++ b/src/lib/md/cme/MDP3Utils.cpp @@ -167,5 +167,6 @@ const vector parse_channels(const vector& symbols) { return result; } + }} //namespace #endif \ No newline at end of file diff --git a/src/lib/md/cme/MDP3Utils.h b/src/lib/md/cme/MDP3Utils.h index dab13ff8d..08caddeab 100644 --- a/src/lib/md/cme/MDP3Utils.h +++ b/src/lib/md/cme/MDP3Utils.h @@ -1,10 +1,12 @@ #pragma once #include "lib/md/coconut2.h" +#include "lib/utils/optional.h" #include #include #include + namespace bts { namespace md { @@ -99,5 +101,6 @@ inline int floorlog10(int64_t m) { } + }}//namespace diff --git a/src/lib/md/relay/RelayClient.cpp b/src/lib/md/relay/RelayClient.cpp index 341ff53fd..b7d4da066 100644 --- a/src/lib/md/relay/RelayClient.cpp +++ b/src/lib/md/relay/RelayClient.cpp @@ -240,6 +240,9 @@ public: log << Venue_Name(ch.exchange()).substr(sizeof("venue")); log << " " << (uint32_t)ch.time(); log << " " << (uint16_t)ch.segment_id(); + if (!ch.entitled()) { + log << " " << "Ent=0"; + } } log << "\n}"; auto encoded = websocketpp::base64_encode(log.str()); diff --git a/src/lib/md/vendor/OnixsUtils.cpp b/src/lib/md/vendor/OnixsUtils.cpp new file mode 100644 index 000000000..c76422f0e --- /dev/null +++ b/src/lib/md/vendor/OnixsUtils.cpp @@ -0,0 +1,68 @@ +#ifndef WIN32 +#include "OnixsUtils.h" +#include "lib/logging/logging.h" +#include "lib/config/config.h" +#include "lib/config/protos/MarketData.pb.h" + +namespace bts { +namespace md { + +// The onixs checksum includes the line endings as \r\n +// to avoid the possibility of git mangling the line endings we store +// an array of lines instead of a single string and restore the lines +// when we write it out in MDP3main.cpp +const char * onixs_license[] = { +"", +" production", +" ", +" Blue Trading Systems OF 9420-2", +" ", +" ", +" 2019-05-02", +" 2020-05-13", +" ", +" ", +" ", +" ", +" ", +" ", +" 5E50A1DACD94D7C1BECD316EEAE5AB02", +"", +}; + +OnixsTemplLicense onixs_create_temporary_license() { + const auto& options = config::get(); + OnixsTemplLicense linfo; + linfo.path = options.onixs_license(); + if (linfo.path == "{default}") { + linfo.path = boost::filesystem::path {os::bts_data_path()} / "licenses"; + auto ident = boost::filesystem::unique_path("%%%%-%%%%-%%%%-%%%%.lic"); + linfo.license = { linfo.path / ident }; + } + + if (linfo.license) { + boost::system::error_code ignore; + boost::filesystem::create_directories(linfo.path, ignore); + auto temp = linfo.license.value(); + std::ofstream out(temp.c_str(), std::ios::out | std::ios::binary); + if (out.good()) { + for (const char* line : onixs_license) { + if (line != onixs_license[0]) out << "\r\n"; + out << line; + } + } + else { + LOG(md,Warn, "Licensing error. Failed to write to '{}'. Please ensure it is writeable.", linfo.path); + } + } + return linfo; +} +void onixs_destroy_temporary_license(const OnixsTemplLicense& lic) { + if (lic.license) { + boost::system::error_code ignore; + boost::filesystem::remove(lic.license.value(), ignore); + } +} + +}} //namespace +#endif diff --git a/src/lib/md/vendor/OnixsUtils.h b/src/lib/md/vendor/OnixsUtils.h new file mode 100644 index 000000000..0d46fc357 --- /dev/null +++ b/src/lib/md/vendor/OnixsUtils.h @@ -0,0 +1,16 @@ +#pragma once +#include "boost/filesystem.hpp" +#include "lib/utils/optional.h" + +namespace bts { +namespace md { + +struct OnixsTemplLicense { + boost::filesystem::path path; + std::optional license; +}; + +OnixsTemplLicense onixs_create_temporary_license(); +void onixs_destroy_temporary_license(const OnixsTemplLicense&); + +}} //namespace diff --git a/src/lib/utils/AuthSessionManager.cpp b/src/lib/utils/AuthSessionManager.cpp index dddb415fd..8b1b74438 100644 --- a/src/lib/utils/AuthSessionManager.cpp +++ b/src/lib/utils/AuthSessionManager.cpp @@ -80,7 +80,7 @@ bool AuthSessionManager::validate_ip_port(const bts::config::KeyCode& kc) return portgood && ipgood; } -bool AuthSessionManager::add_or_replace_session(const api::user::TokenPayload& tok, std::string* msg) +bool AuthSessionManager::add_or_replace_session(const api::user::TokenPayload& tok, const admin::BTSUser& user, std::string* msg) { if(tok.wheel()) return true; @@ -105,18 +105,18 @@ bool AuthSessionManager::add_or_replace_session(const api::user::TokenPayload& t if(it != _map.end()) { _map[tok.id()] = Session{tok}; - LOG(User, Warn, "KEYCODE: Replacing session {} ", tok.id()); + LOG(User, Warn, "KEYCODE: Replacing session {} user:{}:{} ", tok.id(), user.id(), user.name()); return true; } else if(_map.size() < _nusers) { _map[tok.id()] = Session{tok}; - LOG(User, Warn, "KEYCODE: Creating session {} ", tok.id()); + LOG(User, Warn, "KEYCODE: Creating session {} user:{}:{}", tok.id(), user.id(), user.name()); return true; } if(msg) *msg = "KEYCODES: Not Enough Logins available for session"; - LOG(User, Error, "KEYCODES: Not Enough Logins available for session {}", tok.id()); + LOG(User, Error, "KEYCODES: Not Enough Logins available for session {} user:{}:{}", tok.id(), user.id(), user.name()); return false; } diff --git a/src/lib/utils/AuthSessionManager.h b/src/lib/utils/AuthSessionManager.h index 08e9d03cd..fa68d097e 100644 --- a/src/lib/utils/AuthSessionManager.h +++ b/src/lib/utils/AuthSessionManager.h @@ -8,7 +8,7 @@ namespace bts { namespace config { class KeyCode; } namespace api { namespace auth { - + struct Session { api::user::TokenPayload token; @@ -18,8 +18,8 @@ class AuthSessionManager { public: AuthSessionManager(); - - bool add_or_replace_session(const api::user::TokenPayload& tok, std::string* msg = nullptr); + + bool add_or_replace_session(const api::user::TokenPayload& tok, const admin::BTSUser& user, std::string* msg = nullptr); bool check_session(const api::user::TokenPayload& tok); private: @@ -33,6 +33,6 @@ private: bool _concurrent; }; - - + + }}} \ No newline at end of file diff --git a/src/lib/utils/AuthToken.cpp b/src/lib/utils/AuthToken.cpp index 2423638a8..9c062c592 100644 --- a/src/lib/utils/AuthToken.cpp +++ b/src/lib/utils/AuthToken.cpp @@ -89,7 +89,7 @@ AuthToken generate_token(const admin::BTSUser& user, std::string* msg) payload.set_wheel(true); if(requires_auth_session(user)) - session_manager().add_or_replace_session(payload, msg); + session_manager().add_or_replace_session(payload, user, msg); auto token = encrypt(payload.SerializeAsString()); bts_assert_d(token.size() < 255-8); AuthToken result; diff --git a/src/server/sparkd/md/platforms/ice_onixs/ICEMain.cpp b/src/server/sparkd/md/platforms/ice_onixs/ICEMain.cpp index f36be139d..ea2b3ef9b 100644 --- a/src/server/sparkd/md/platforms/ice_onixs/ICEMain.cpp +++ b/src/server/sparkd/md/platforms/ice_onixs/ICEMain.cpp @@ -1,6 +1,7 @@ #include "ICEMain.h" #include "lib/md/ice/ICEUtils.h" +#include "lib/md/vendor/OnixsUtils.h" #include "lib/config/config.h" #include "lib/md/coconut2.h" #include "lib/md/SecurityDB.h" @@ -24,16 +25,16 @@ void recursive_copy(const boost::filesystem::path &src, const boost::filesystem: { if (boost::filesystem::exists(dst)) throw std::runtime_error(dst.generic_string() + " exists"); - if (boost::filesystem::is_directory(src)) + if (boost::filesystem::is_directory(src)) { boost::filesystem::create_directories(dst); - for (boost::filesystem::directory_entry& item : boost::filesystem::directory_iterator(src)) - recursive_copy(item.path(), dst/item.path().filename()); - } - else if (boost::filesystem::is_regular_file(src)) - boost::filesystem::copy(src, dst); - else - throw std::runtime_error(dst.generic_string() + " not dir or file"); + for (boost::filesystem::directory_entry& item : boost::filesystem::directory_iterator(src)) + recursive_copy(item.path(), dst/item.path().filename()); + } + else if (boost::filesystem::is_regular_file(src)) + boost::filesystem::copy(src, dst); + else + throw std::runtime_error(dst.generic_string() + " not dir or file"); } using namespace std; @@ -55,10 +56,10 @@ ICEMain::ICEMain() : ICEMain::~ICEMain() {} -const ICEOptions::ICEChannel channel_settings_for(const ICEChannel& channel) +const ICEOptions::ICEChannel channel_settings_for(const ICEChannel& channel) { const auto& config = config::get(); - for (const auto& ch : config.channel()) + for (const auto& ch : config.channel()) { if(ch.name() == channel.name) return ch; @@ -67,7 +68,7 @@ const ICEOptions::ICEChannel channel_settings_for(const ICEChannel& channel) } -onixs_ice::MarketSubscriptions market_subcription_for_channel(const ICEChannel& chan) +onixs_ice::MarketSubscriptions market_subcription_for_channel(const ICEChannel& chan) { onixs_ice::MarketSubscriptions subs; for(const auto& x : chan.market_types) @@ -82,106 +83,96 @@ onixs_ice::MarketSubscriptions market_subcription_for_channel(const ICEChannel& } -void ICEMain::start(std::vector& symbols) +void ICEMain::start(std::vector& symbols) { - // License path and config file - auto license_location = os::bts_data_path() + "/licenses/"; - if (!boost::filesystem::is_directory(license_location)) - { - auto license_path =os::sparkd_wd() + "/data_files/Onixs.BTS.lic" ; - boost::filesystem::create_directories(license_location); - boost::filesystem::copy_file(license_path,license_location+"/Onixs.BTS.lic"); - } auto ice_conf_location = os::bts_data_path() + "/onixs_ice/"; - if (!boost::filesystem::is_directory(ice_conf_location)) + if (!boost::filesystem::is_directory(ice_conf_location)) { auto conf_path = os::sparkd_wd() + "/data_files/onixs_ice/" ; recursive_copy(boost::filesystem::path(conf_path), boost::filesystem::path(ice_conf_location)); } - + await_ice_config(); + auto license = onixs_create_temporary_license(); + const auto& channels = parse_ice_channels(symbols); - for (const auto& channel : channels) + for (const auto& channel : channels) { - unique_ptr phandler = prepare_handler(channel); + unique_ptr phandler = prepare_handler(channel, license.path.string()); _listeners.push_back(prepare_listener(*phandler, channel)); - _handlers.push_back(std::make_pair(channel, move(phandler))); - - std::stringstream symstr; - for (const auto& sym : channel.symbols) - symstr << sym.symbol() << "-" << SecurityType_Name(sym.type()) << " "; + _handlers.push_back(std::make_pair(channel, move(phandler))); + + std::stringstream symstr; + for (const auto& sym : channel.symbols) + symstr << sym.symbol() << "-" << SecurityType_Name(sym.type()) << " "; LOG(md,Info, "ICE: Initialized channel {} ({})", channel.to_string(), symstr.str()); } - for (auto& pair : _handlers) - { + for (auto& pair : _handlers) + { LOG(md,Info, "ICE: Init Handler {}", pair.first.to_string()); - sleep_for(16s); - onixs_ice::MarketSubscriptions subs = market_subcription_for_channel(pair.first); + sleep_for(16s); + onixs_ice::MarketSubscriptions subs = market_subcription_for_channel(pair.first); pair.second->start(subs); } + onixs_destroy_temporary_license(license); LOG(md,Info, "** ICE Publisher started **"); } void ICEMain::send_heartbeats() { - for (const auto& listener: _listeners) + for (const auto& listener: _listeners) listener->heartbeat(); } // // // Initialize HandlerSettings and allocate the channel Handler -unique_ptr ICEMain::prepare_handler(const ICEChannel& channel) +unique_ptr ICEMain::prepare_handler(const ICEChannel& channel, const std::string& license) { - const auto& ice_options = config::get(); - auto license = ice_options.onixs_license(); - if (license == "{default}") - license = os::bts_data_path() + "/licenses/"; - const auto& options = channel_settings_for(channel); LOG(md,Info,"Loaded channel options for channel {}:\n{}", channel.to_string(), options.DebugString()); - onixs_ice::HandlerSettings settings; - settings.licenseDirectory = license; + onixs_ice::HandlerSettings settings; + settings.licenseDirectory = license; // // Logging settings.logLevel = (onixs_ice::LogLevels::Enum) options.onixs_log_mode(); settings.logDirectory = ice_log_path(); - + // - // Config file + // Config file settings.connectivityConfiguration = ice_config_path(); - // + // // Network settings const auto& pub_options = config::get(); - if (pub_options.has_network_interface()) + if (pub_options.has_network_interface()) settings.networkInterface = pub_options.network_interface(); - else + else { std::string inter; - if (pub_options.has_network_interface_a() && !pub_options.has_network_interface_b()) + if (pub_options.has_network_interface_a() && !pub_options.has_network_interface_b()) inter = pub_options.network_interface_a(); - if (!pub_options.has_network_interface_a() && pub_options.has_network_interface_b()) + if (!pub_options.has_network_interface_a() && pub_options.has_network_interface_b()) inter = pub_options.network_interface_b(); - if (pub_options.has_network_interface_a() && pub_options.has_network_interface_b()) + if (pub_options.has_network_interface_a() && pub_options.has_network_interface_b()) inter = pub_options.network_interface_b() + ":" + pub_options.network_interface_b(); settings.networkInterface = inter; - } + } settings.udpBufferSize = options.udp_buffer_size(); settings.heartbeatInterval = options.heartbeat_interval(); settings.sequenceGapMargin = options.sequence_gap_margin(); settings.gapTimeoutInMilliseconds = options.gap_timeout_in_ms(); - + // // Snapshot recovery options settings.snapshotRecoveryOptions.snapshotRecoveryTimeoutInMilliseconds = options.snapshot_recovery_timeout_in_ms(); settings.snapshotRecoveryOptions.maximumNumberOfSnaphotRecoveryAttempts = options.maximum_number_of_snapshot_recovery_attempts(); settings.snapshotRecoveryOptions.maximumSizeOfSnapshotMessageQueue = options.maximum_size_of_snapshot_message_queue(); - settings.snapshotRecoveryOptions.maximumSizeOfLiveMessageQueue = options.maximum_size_of_live_message_queue(); + settings.snapshotRecoveryOptions.maximumSizeOfLiveMessageQueue = options.maximum_size_of_live_message_queue(); // - // Misc settings + // Misc settings if(options.processing_thread_affinity() != "" ) settings.processingThreadAffinity = onixs_ice::ThreadAffinity::deserialize(options.processing_thread_affinity()); // if(options.has_track_top_of_the_book_only() @@ -192,10 +183,10 @@ unique_ptr ICEMain::prepare_handler(const ICEChannel& channe settings.maxMulticastMessageBlockSize = options.max_multicast_message_block_size(); if(options.product_definition_cache_directory() != "" ) settings.productDefinitionCacheDirectory = options.product_definition_cache_directory(); - + // // return feed handler - try + try { auto handler = unique_ptr(new onixs_ice::Handler(settings)); return handler; @@ -208,18 +199,18 @@ unique_ptr ICEMain::prepare_handler(const ICEChannel& channe // // Create a listener for this channel and register callbacks -unique_ptr ICEMain::prepare_listener(onixs_ice::Handler& handler, const ICEChannel& channel) +unique_ptr ICEMain::prepare_listener(onixs_ice::Handler& handler, const ICEChannel& channel) { // We need to get a handler to the producer channels so we can produce heartbeats vector producer_channels; - for (auto& symbol : channel.symbols) + for (auto& symbol : channel.symbols) { producer_channels.push_back(_producer.get_channel(symbol.symbol().c_str(), symbol.type(), symbol.exchange())); } unique_ptr listener(new ICEListener(_index, _producer, /*_settlement_recorder,*/ producer_channels)); - for (auto& symbol : channel.symbols) - listener->add_filter_symbol(symbol.symbol()); + for (auto& symbol : channel.symbols) + listener->add_filter_symbol(symbol.symbol()); handler.registerExchangeListener(listener.get()); handler.registerFeedListener(listener.get()); diff --git a/src/server/sparkd/md/platforms/ice_onixs/ICEMain.h b/src/server/sparkd/md/platforms/ice_onixs/ICEMain.h index ec6f1dfb8..5c43220c5 100644 --- a/src/server/sparkd/md/platforms/ice_onixs/ICEMain.h +++ b/src/server/sparkd/md/platforms/ice_onixs/ICEMain.h @@ -34,7 +34,7 @@ public: void start(std::vector&); void send_heartbeats() override; - std::unique_ptr prepare_handler(const ICEChannel& channel); + std::unique_ptr prepare_handler(const ICEChannel& channel, const std::string& license); std::unique_ptr prepare_listener(onixs_ice::Handler& handler, const ICEChannel& channel); private: diff --git a/src/server/sparkd/md/platforms/mdp3_onixs/MDP3Main.cpp b/src/server/sparkd/md/platforms/mdp3_onixs/MDP3Main.cpp index af427f286..78547f12a 100644 --- a/src/server/sparkd/md/platforms/mdp3_onixs/MDP3Main.cpp +++ b/src/server/sparkd/md/platforms/mdp3_onixs/MDP3Main.cpp @@ -1,6 +1,7 @@ #include "MDP3Main.h" #include "lib/md/cme/MDP3Utils.h" +#include "lib/md/vendor/OnixsUtils.h" #include "lib/md/MBOProcessor.h" #include "lib/config/config.h" #include "lib/md/coconut2.h" @@ -17,6 +18,7 @@ #include #include #include +#include using namespace std; using namespace bts::co2; @@ -144,7 +146,8 @@ onixs::SessionSettings session_settings_for_channel(const string& channel_id, MB void MDP3Main::start(std::vector& symbols, MBOWriter* mbo) { await_cme_config(); - initialize(); + auto license = onixs_create_temporary_license(); + initialize(license.path.string()); const auto& channels = parse_channels(symbols); _engines = create_feed_engines(channels); for (const auto& channel : channels) { @@ -160,37 +163,19 @@ void MDP3Main::start(std::vector& symbols, MBOWriter* mbo) { onixs::SessionSettings settings = session_settings_for_channel(pair.first, mbo); pair.second->start(settings); } + onixs_destroy_temporary_license(license); LOG(md,Info, "** CME MDP3 Publisher started **"); } void MDP3Main::send_heartbeats() { - for (const auto& listener: _listeners) - listener->heartbeat(); - - // utils::DispatcherTimer settlement_timer(disp, 100, [&]() { - // _settlement_recorder.do_work(); - // }); - // settlement_timer.start(); + for (const auto& listener: _listeners) { + listener->heartbeat(); + } } -void MDP3Main::initialize() { - const auto& options = config::get(); - auto license_location = os::bts_data_path() + "/licenses/"; - - if (!boost::filesystem::is_directory(license_location)) { - auto license_path =os::sparkd_wd() + "/data_files/Onixs.BTS.lic" ; - boost::filesystem::create_directories(license_location); - boost::filesystem::copy_file(license_path,license_location+"/Onixs.BTS.lic"); - } - - // - // License path +void MDP3Main::initialize(const std::string& license_store) { onixs::InitializationSettings init_settings; - auto license = options.onixs_license(); - init_settings.licenseStore(license); - if (license == "{default}") { - init_settings.licenseStore(license_location); - } + init_settings.licenseStore(license_store); LOG(md,Info,"Loading onixs license from {}", init_settings.licenseStore()); onixs::initialize(init_settings); } diff --git a/src/server/sparkd/md/platforms/mdp3_onixs/MDP3Main.h b/src/server/sparkd/md/platforms/mdp3_onixs/MDP3Main.h index bda70e4c6..baacdab35 100644 --- a/src/server/sparkd/md/platforms/mdp3_onixs/MDP3Main.h +++ b/src/server/sparkd/md/platforms/mdp3_onixs/MDP3Main.h @@ -35,7 +35,7 @@ public: void start(std::vector&, MBOWriter*); void send_heartbeats() override; - void initialize(); + void initialize(const std::string& license_store); std::unique_ptr prepare_handler(const std::string& channel, MBOWriter*); std::unique_ptr prepare_listener(onixs::Handler& handler, const CMEChannel& channel, MBOWriter*); diff --git a/src/web/CMakeDeps.cmake b/src/web/CMakeDeps.cmake index bc74cb4cf..454edca8b 100644 --- a/src/web/CMakeDeps.cmake +++ b/src/web/CMakeDeps.cmake @@ -1 +1 @@ -set(sources ../../externals/linux/include/google/protobuf/descriptor.proto;../../externals/linux/include/google/protobuf/timestamp.proto;../lib/api/apicore.proto;../lib/api/apigateway.proto;../lib/api/apioptions.proto;../lib/api/services/AdminService.proto;../lib/api/services/AlgoDefinitionService.proto;../lib/api/services/AlgoService.proto;../lib/api/services/ApiUnitTestService.proto;../lib/api/services/AuthService.proto;../lib/api/services/ErrorReportService.proto;../lib/api/services/HelloService.proto;../lib/api/services/MBOService.proto;../lib/api/services/MarginService.proto;../lib/api/services/MarketDataAuxiliaryService.proto;../lib/api/services/MarketDataRelay.proto;../lib/api/services/OrderService.proto;../lib/api/services/OutOfProcessURLListener.proto;../lib/api/services/PersistenceService.proto;../lib/api/services/PositionService.proto;../lib/api/services/ShellDiagnosticService.proto;../lib/api/services/ShellLatencyService.proto;../lib/api/services/SyntheticSecurityService.proto;../lib/domain_model/Security.proto;../lib/md/protos/co2.proto;../lib/sparkproto/SparkProtos.proto;api/build.sh;api/node_modules/exit/test/fixtures/create-files.sh;api/node_modules/protobufjs/cli/node_modules/acorn-jsx/node_modules/acorn/bin/update_authors.sh;api/node_modules/psl/scripts/ci-build.sh;api/node_modules/watch/release.sh;api/quiet_build.sh;api/src/DynamicService.ts;api/src/ServiceContext.ts;api/src/bts_assert.ts;ui/src/Access.fs;ui/src/Accounts/ClipLimits.fs;ui/src/Accounts/ProductLimits.fs;ui/src/Accounts/SecurityLimits.fs;ui/src/Accounts/State.fs;ui/src/Accounts/Types.fs;ui/src/Accounts/View.fs;ui/src/App.fs;ui/src/Cmd.fs;ui/src/Controls/Button.fs;ui/src/Controls/DataGrid.fs;ui/src/Controls/Fields.fs;ui/src/Controls/Modal.fs;ui/src/Controls/ReactGrid.fs;ui/src/Controls/Table.fs;ui/src/Controls/nbsp.fs;ui/src/Global.fs;ui/src/Imports.fs;ui/src/Lens.fs;ui/src/Login/Login.fs;ui/src/Nav.fs;ui/src/State.fs;ui/src/Types.fs;ui/src/Users/State.fs;ui/src/Users/Types.fs;ui/src/Users/View.fs;ui/src/Util/EnumUtils.fs;ui/src/Util/JSMap.fs;ui/src/obj/Debug/netstandard2.0/ui.AssemblyInfo.fs) \ No newline at end of file +set(sources ../../externals/linux/include/google/protobuf/descriptor.proto;../../externals/linux/include/google/protobuf/timestamp.proto;../lib/api/apicore.proto;../lib/api/apigateway.proto;../lib/api/apioptions.proto;../lib/api/services/AdminService.proto;../lib/api/services/AlgoDefinitionService.proto;../lib/api/services/AlgoService.proto;../lib/api/services/ApiUnitTestService.proto;../lib/api/services/AuthService.proto;../lib/api/services/ErrorReportService.proto;../lib/api/services/HelloService.proto;../lib/api/services/MBOService.proto;../lib/api/services/MarginService.proto;../lib/api/services/MarketDataAuxiliaryService.proto;../lib/api/services/MarketDataRelay.proto;../lib/api/services/OrderService.proto;../lib/api/services/OutOfProcessURLListener.proto;../lib/api/services/PersistenceService.proto;../lib/api/services/PositionService.proto;../lib/api/services/ShellDiagnosticService.proto;../lib/api/services/ShellLatencyService.proto;../lib/api/services/SyntheticSecurityService.proto;../lib/domain_model/Security.proto;../lib/md/protos/co2.proto;../lib/sparkproto/SparkProtos.proto;api/build.sh;api/node_modules/exit/test/fixtures/create-files.sh;api/node_modules/protobufjs/cli/node_modules/acorn-jsx/node_modules/acorn/bin/update_authors.sh;api/node_modules/watch/release.sh;api/quiet_build.sh;api/src/DynamicService.ts;api/src/ServiceContext.ts;api/src/bts_assert.ts;ui/src/Access.fs;ui/src/Accounts/ClipLimits.fs;ui/src/Accounts/ProductLimits.fs;ui/src/Accounts/SecurityLimits.fs;ui/src/Accounts/State.fs;ui/src/Accounts/Types.fs;ui/src/Accounts/View.fs;ui/src/App.fs;ui/src/Cmd.fs;ui/src/Controls/Button.fs;ui/src/Controls/DataGrid.fs;ui/src/Controls/Fields.fs;ui/src/Controls/Modal.fs;ui/src/Controls/ReactGrid.fs;ui/src/Controls/Table.fs;ui/src/Controls/nbsp.fs;ui/src/Global.fs;ui/src/Imports.fs;ui/src/Lens.fs;ui/src/Login/Login.fs;ui/src/Nav.fs;ui/src/State.fs;ui/src/Types.fs;ui/src/Users/State.fs;ui/src/Users/Types.fs;ui/src/Users/View.fs;ui/src/Util/EnumUtils.fs;ui/src/Util/JSMap.fs;ui/src/obj/Debug/netstandard2.0/ui.AssemblyInfo.fs) \ No newline at end of file