diff --git a/.vscode/launch.json b/.vscode/launch.json index f3c362de0..17ef37c0b 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -281,5 +281,42 @@ "RedirectOutput" ] }, + { + "name": ".NET Core Remote Attach", + "type": "coreclr", + "request": "attach", + "processId": "${command:pickRemoteProcess}", + "pipeTransport": { + "pipeProgram": "c:\\program files\\git\\usr\\bin\\ssh.exe", + "pipeArgs": ["bts@sparkvm"], + "debuggerPath": "/home/bts/vsdbg/vsdbg", + "pipeCwd": "${workspaceRoot}", + "quoteArgs": true + }, + "sourceFileMap": { + "/home/bts/spark/": "${workspaceRoot}" + }, + "justMyCode": true + }, + { + "name": ".NET Core Remote Launch", + "type": "coreclr", + "request": "launch", + "program": "/usr/bin/dotnet", + "args": ["sparkcmd.dll", "test", "test_join_create_and_takeout_market"], + "stopAtEntry": false, + "cwd": "/home/bts/spark/build/ninja_debug/server", + "pipeTransport": { + "pipeProgram": "c:\\program files\\git\\usr\\bin\\ssh.exe", + "pipeArgs": ["bts@sparkvm"], + "debuggerPath": "/home/bts/vsdbg/vsdbg", + "pipeCwd": "${workspaceRoot}", + "quoteArgs": true + }, + "sourceFileMap": { + "/home/bts/spark/": "${workspaceRoot}" + }, + "justMyCode": false + }, ] } \ No newline at end of file diff --git a/doc/user/CMakeDeps.cmake b/doc/user/CMakeDeps.cmake index 5f3811807..1b1ac7fc0 100644 --- a/doc/user/CMakeDeps.cmake +++ b/doc/user/CMakeDeps.cmake @@ -1 +1 @@ -set(sources /home/ppinto/Dropbox/bts/spark/doc/user/build.sh;content/_index.md;content/bts_spark/Glossary/index.md;content/bts_spark/Help/about_spark.png;content/bts_spark/Help/image39.png;content/bts_spark/Help/image58.png;content/bts_spark/Help/index.md;content/bts_spark/Launcher/image38.png;content/bts_spark/Launcher/image68.png;content/bts_spark/Launcher/index.md;content/bts_spark/Logging-In-to-the-System/image3.png;content/bts_spark/Logging-In-to-the-System/image64.png;content/bts_spark/Logging-In-to-the-System/index.md;content/bts_spark/Market/change_securities.png;content/bts_spark/Market/image11.png;content/bts_spark/Market/image14.png;content/bts_spark/Market/image20.png;content/bts_spark/Market/image21.png;content/bts_spark/Market/image23.png;content/bts_spark/Market/image24.png;content/bts_spark/Market/image34.png;content/bts_spark/Market/image49.png;content/bts_spark/Market/image53.png;content/bts_spark/Market/image66.png;content/bts_spark/Market/image69.png;content/bts_spark/Market/index.md;content/bts_spark/Market/market_view.png;content/bts_spark/Market/settings_icon.png;content/bts_spark/Market/time_and_sales.png;content/bts_spark/My-Windows/image15.png;content/bts_spark/My-Windows/image16.png;content/bts_spark/My-Windows/image37.png;content/bts_spark/My-Windows/index.md;content/bts_spark/Settings/image51.png;content/bts_spark/Settings/image9.png;content/bts_spark/Settings/index.md;content/bts_spark/Spreader/image10.png;content/bts_spark/Spreader/image13.png;content/bts_spark/Spreader/image18.png;content/bts_spark/Spreader/image19.png;content/bts_spark/Spreader/image28.png;content/bts_spark/Spreader/image29.png;content/bts_spark/Spreader/image31.png;content/bts_spark/Spreader/image35.png;content/bts_spark/Spreader/image40.png;content/bts_spark/Spreader/image43.png;content/bts_spark/Spreader/image54.png;content/bts_spark/Spreader/image55.png;content/bts_spark/Spreader/image56.png;content/bts_spark/Spreader/image6.png;content/bts_spark/Spreader/image7.png;content/bts_spark/Spreader/image70.png;content/bts_spark/Spreader/image72.png;content/bts_spark/Spreader/image8.png;content/bts_spark/Spreader/index.md;content/bts_spark/Trading/algo_studio.png;content/bts_spark/Trading/collapse_all_icon.png;content/bts_spark/Trading/cover_algo_control.png;content/bts_spark/Trading/expand_all_icon.png;content/bts_spark/Trading/image1.png;content/bts_spark/Trading/image17.png;content/bts_spark/Trading/image2.png;content/bts_spark/Trading/image25.png;content/bts_spark/Trading/image27.png;content/bts_spark/Trading/image33.png;content/bts_spark/Trading/image42.png;content/bts_spark/Trading/image44.png;content/bts_spark/Trading/image47.png;content/bts_spark/Trading/image48.png;content/bts_spark/Trading/image5.png;content/bts_spark/Trading/image50.png;content/bts_spark/Trading/image52.png;content/bts_spark/Trading/image57.png;content/bts_spark/Trading/image59.png;content/bts_spark/Trading/image60.png;content/bts_spark/Trading/image61.png;content/bts_spark/Trading/image62.png;content/bts_spark/Trading/image73.png;content/bts_spark/Trading/image74.png;content/bts_spark/Trading/index.md;content/bts_spark/Trading/join_algo_control.png;content/bts_spark/Trading/ladder.png;content/bts_spark/Trading/ladder_badges.png;content/bts_spark/Trading/ladder_main_part.png;content/bts_spark/Trading/lean_algo_control.png;content/bts_spark/Trading/mini_orderbook.png;content/bts_spark/Trading/oco_algo_control.png;content/bts_spark/Trading/offset_algo_control.png;content/bts_spark/Trading/pnl_calculation.png;content/bts_spark/Trading/pnl_window.png;content/bts_spark/Trading/recreate_icon.png;content/bts_spark/Trading/settings_icon.png;content/bts_spark/Trading/spark_menu_order_book.png;content/bts_spark/Trading/top_algo_control.png;content/bts_spark/Trading/trigger_algo_control.png;content/bts_spark/_index.md;content/bts_spark_sdk/Client/Overview.md;content/bts_spark_sdk/Client/Threading.md;content/bts_spark_sdk/Client/_index.md;content/bts_spark_sdk/Server/_index.md;content/bts_spark_sdk/_index.md;content/release_notes/_index.md;static/book.js;static/favicon.ico;static/image.js;templates/index.html;templates/page.html;templates/section.html;templates/shortcodes/back_button.html) \ No newline at end of file +set(sources /home/ppinto/Dropbox/bts/spark/doc/user/build.sh;content/_index.md;content/bts_spark/Algos/_index.md;content/bts_spark/Glossary/index.md;content/bts_spark/Help/about_spark.png;content/bts_spark/Help/image39.png;content/bts_spark/Help/image58.png;content/bts_spark/Help/index.md;content/bts_spark/Launcher/image38.png;content/bts_spark/Launcher/image68.png;content/bts_spark/Launcher/index.md;content/bts_spark/Logging-In-to-the-System/image3.png;content/bts_spark/Logging-In-to-the-System/image64.png;content/bts_spark/Logging-In-to-the-System/index.md;content/bts_spark/Market/change_securities.png;content/bts_spark/Market/image11.png;content/bts_spark/Market/image14.png;content/bts_spark/Market/image20.png;content/bts_spark/Market/image21.png;content/bts_spark/Market/image23.png;content/bts_spark/Market/image24.png;content/bts_spark/Market/image34.png;content/bts_spark/Market/image49.png;content/bts_spark/Market/image53.png;content/bts_spark/Market/image66.png;content/bts_spark/Market/image69.png;content/bts_spark/Market/index.md;content/bts_spark/Market/market_view.png;content/bts_spark/Market/settings_icon.png;content/bts_spark/Market/time_and_sales.png;content/bts_spark/My-Windows/image15.png;content/bts_spark/My-Windows/image16.png;content/bts_spark/My-Windows/image37.png;content/bts_spark/My-Windows/index.md;content/bts_spark/Settings/image51.png;content/bts_spark/Settings/image9.png;content/bts_spark/Settings/index.md;content/bts_spark/Spreader/image10.png;content/bts_spark/Spreader/image13.png;content/bts_spark/Spreader/image18.png;content/bts_spark/Spreader/image19.png;content/bts_spark/Spreader/image28.png;content/bts_spark/Spreader/image29.png;content/bts_spark/Spreader/image31.png;content/bts_spark/Spreader/image35.png;content/bts_spark/Spreader/image40.png;content/bts_spark/Spreader/image43.png;content/bts_spark/Spreader/image54.png;content/bts_spark/Spreader/image55.png;content/bts_spark/Spreader/image56.png;content/bts_spark/Spreader/image6.png;content/bts_spark/Spreader/image7.png;content/bts_spark/Spreader/image70.png;content/bts_spark/Spreader/image72.png;content/bts_spark/Spreader/image8.png;content/bts_spark/Spreader/index.md;content/bts_spark/Trading/algo_studio.png;content/bts_spark/Trading/collapse_all_icon.png;content/bts_spark/Trading/cover_algo_control.png;content/bts_spark/Trading/expand_all_icon.png;content/bts_spark/Trading/image1.png;content/bts_spark/Trading/image17.png;content/bts_spark/Trading/image2.png;content/bts_spark/Trading/image25.png;content/bts_spark/Trading/image27.png;content/bts_spark/Trading/image33.png;content/bts_spark/Trading/image42.png;content/bts_spark/Trading/image44.png;content/bts_spark/Trading/image47.png;content/bts_spark/Trading/image48.png;content/bts_spark/Trading/image5.png;content/bts_spark/Trading/image50.png;content/bts_spark/Trading/image52.png;content/bts_spark/Trading/image57.png;content/bts_spark/Trading/image59.png;content/bts_spark/Trading/image60.png;content/bts_spark/Trading/image61.png;content/bts_spark/Trading/image62.png;content/bts_spark/Trading/image73.png;content/bts_spark/Trading/image74.png;content/bts_spark/Trading/index.md;content/bts_spark/Trading/join_algo_control.png;content/bts_spark/Trading/ladder.png;content/bts_spark/Trading/ladder_badges.png;content/bts_spark/Trading/ladder_main_part.png;content/bts_spark/Trading/lean_algo_control.png;content/bts_spark/Trading/mini_orderbook.png;content/bts_spark/Trading/oco_algo_control.png;content/bts_spark/Trading/offset_algo_control.png;content/bts_spark/Trading/pnl_calculation.png;content/bts_spark/Trading/pnl_window.png;content/bts_spark/Trading/recreate_icon.png;content/bts_spark/Trading/settings_icon.png;content/bts_spark/Trading/spark_menu_order_book.png;content/bts_spark/Trading/top_algo_control.png;content/bts_spark/Trading/trigger_algo_control.png;content/bts_spark/_index.md;content/release_notes/_index.md;static/book.js;static/favicon.ico;static/image.js;templates/index.html;templates/page.html;templates/section.html;templates/shortcodes/back_button.html) \ No newline at end of file diff --git a/doc/user/build.sh b/doc/user/build.sh index 663e6aa53..80e6dd052 100644 --- a/doc/user/build.sh +++ b/doc/user/build.sh @@ -8,7 +8,6 @@ zola_path=$(readlink -f "../../externals/linux/bin/zola/zola") mkdir -p $temp_path cp -r ./* $temp_path - cd $temp_path $zola_path build -u '/docs/' -o $1 >$tmpfile 2>&1 diff --git a/doc/user/content/release_notes/_index.md b/doc/user/content/release_notes/_index.md index f37e8d038..f7fb3889d 100644 --- a/doc/user/content/release_notes/_index.md +++ b/doc/user/content/release_notes/_index.md @@ -4,6 +4,29 @@ weight = 3 sort_by = "weight" insert_anchor_links = "right" +++ +## 2.0.0 +### User Visible Changes + - Support for attaching and detaching algos to existing orders + - Support for display and update of all parameters in running algos + - Streamlining of order badge decorations in ladder + - New order search/filtering algorithm for order book + - Simpler representation of complex algo chains in order book and mini order book + - Visual and usability improvements to mini order book + - Streamlining of algo parameter dialog in ladder + - New spreader queue holder behavior + - Visual improvements to the order book + - New server side API + - Improved admin UI performance + - Optimized PIQ rendering +### Internal changes + - Exchange simulator no longer requires daily sequence number reset + - Improved MD resilience to corrupted shared memory + - Native orders can now buffer updates/cancels when disconnected or pending first acknowledgment + - Improved settings manager tool output + - Added diagnostics in the event MD memory corruption is detected + - Added systems tests for join,lean, iceberg and spreader orders + - Made exchange order recovery more resilient in the presence of database loss + ## 1.6.2 ### User Visible Changes ### Exchange simulator diff --git a/src/client/spark/Images/Icons.cs b/src/client/spark/Images/Icons.cs index 5ac03d359..1d730b6ee 100644 --- a/src/client/spark/Images/Icons.cs +++ b/src/client/spark/Images/Icons.cs @@ -22,7 +22,9 @@ namespace mbts.ui { AddBoxesGeometryKey = nameof(AddBoxesGeometryKey), AddFileGeometryKey = nameof(AddFileGeometryKey), AddFileThinGeometryKey = nameof(AddFileThinGeometryKey), + AttachAlgosKey = nameof(AttachAlgosKey), CheckMarkGeometryKey = nameof(CheckMarkGeometryKey), + DetachAlgosKey = nameof(DetachAlgosKey), DiskGeometryKey = nameof(DiskGeometryKey), DiskFileGeometryKey = nameof(DiskFileGeometryKey), DocumentGeometryKey = nameof(DocumentGeometryKey), @@ -35,10 +37,14 @@ namespace mbts.ui { EditDocumentAltGeometryKey = nameof(EditDocumentAltGeometryKey), EditDocumentGeometryKey = nameof(EditDocumentGeometryKey), GearGeometryKey = nameof(GearGeometryKey), + LetterAKey = nameof(LetterAKey), + LetterDKey = nameof(LetterDKey), OrdersGeometryKey = nameof(OrdersGeometryKey), PaymentGeometryKey = nameof(PaymentGeometryKey), PencilGeometryKey = nameof(PencilGeometryKey), PlayGeometryKey = nameof(PlayGeometryKey), + ProhibitedGeometryKey = nameof(ProhibitedGeometryKey), + RubberStampGeometryKey = nameof(RubberStampGeometryKey), StarGeometryKey = nameof(StarGeometryKey), ToolsGeometryKey = nameof(ToolsGeometryKey), TrashGeometryKey = nameof(TrashGeometryKey), @@ -115,6 +121,7 @@ namespace mbts.ui { public static ImageSource AddBoxes => create_icon(AddBoxesGeometryKey); public static ImageSource AddEncircled { get { return load_resource_and_freeze("AddEncircled"); } } public static ImageSource AddFile => create_icon(Smashicons.AddFileGeometryKey); + public static ImageSource AttachAlgos => create_icon(AttachAlgosKey); public static ImageSource Beaker { get { return load_resource_and_freeze("Beaker"); } } public static ImageSource Book { get { return load_resource_and_freeze("Book"); } } @@ -139,6 +146,7 @@ namespace mbts.ui { public static ImageSource CheckMark => create_icon(CheckMarkGeometryKey); public static ImageSource Clock { get { return load_resource_and_freeze("Clock"); } } public static ImageSource Defrag { get { return load_resource_and_freeze("Defrag"); } } + public static ImageSource DetachAlgos => create_icon_and_rotate(DetachAlgosKey, Brushes.Red); public static ImageSource Disk => create_icon(DiskGeometryKey); public static ImageSource DiskFile => create_icon(DiskFileGeometryKey); public static ImageSource Display { get { return load_resource_and_freeze("Display"); } } @@ -158,6 +166,8 @@ namespace mbts.ui { public static ImageSource Knight { get { return load_resource_and_freeze("Knight"); } } public static ImageSource Payment => create_icon(PaymentGeometryKey); public static ImageSource Pencil => create_icon(PencilGeometryKey); + public static ImageSource Prohibited => create_icon(ProhibitedGeometryKey); + 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 Star => create_icon(StarGeometryKey); @@ -186,6 +196,19 @@ namespace mbts.ui { return rv; } + public static ImageSource create_icon_and_rotate(string geometric_path_key, Brush brush = null, Pen pen = null, Transform transform = null, double degrees = 90) { + if (brush == null) { + brush = Brushes.Black; + } + var drawing = create_drawing(geometric_path_key, brush, pen, transform); + var dg = new DrawingGroup(); + dg.Children.Add(drawing); + dg.Transform = new RotateTransform(degrees); + var rv = new DrawingImage(dg); + rv.Freeze(); + return rv; + } + public static Drawing create_drawing(string geometric_path_key) => create_drawing(geometric_path_key, Brushes.Black); diff --git a/src/client/spark/Images/Vector/Icons.xaml b/src/client/spark/Images/Vector/Icons.xaml index 9cba2864c..115c988c4 100644 --- a/src/client/spark/Images/Vector/Icons.xaml +++ b/src/client/spark/Images/Vector/Icons.xaml @@ -5,6 +5,14 @@ xmlns:mbts="clr-namespace:mbts.ui" xmlns:sys="clr-namespace:System;assembly=mscorlib" > + + + M10.519881,14.945064C11.300896,14.955074,12.079896,15.102078,12.819896,15.386075L10.878893,17.326085C9.6458764,17.201085,8.3688531,17.591071,7.4258485,18.533091L3.5977991,22.360102C1.9327704,24.026093 1.9317786,26.736124 3.5977991,28.402117 5.2638197,30.068108 7.9748359,30.068108 9.6398644,28.402117L13.467914,24.575106C14.410919,23.632109,14.800938,22.355097,14.675937,21.121083L16.615963,19.180096C17.523962,21.546103,17.034943,24.325104,15.126931,26.234108L11.298882,30.061119C8.7138591,32.64612 4.5238051,32.64612 1.9387672,30.062127 -0.64625573,27.477126 -0.64625573,23.287106 1.9387672,20.701098L5.7668166,16.875065C7.077837,15.564055,8.8018727,14.923061,10.519881,14.945064z M19.825993,10.418039L21.580012,12.17305 12.089907,21.665091 10.333873,19.911087z M25.383069,0C27.077088,3.0538786E-08 28.771109,0.64599859 30.063117,1.9390028 32.647133,4.5230274 32.647133,8.7120385 30.062109,11.298047L26.235068,15.125058C24.327055,17.033085,21.547022,17.52207,19.181973,16.614077L21.121998,14.674067C22.356022,14.799068,23.633046,14.409051,24.57605,13.466054L28.403094,9.6400513C30.068121,7.9740295 30.069129,5.2630205 28.403094,3.5980362 26.738064,1.9320143 24.027033,1.9320143 22.362034,3.5980362L18.533986,7.4240398C17.591958,8.3670363,17.201968,9.643042,17.32697,10.877056L15.385937,12.817066C14.478913,10.452035,14.968939,7.6730337,16.875945,5.7660436L20.703019,1.9390028C21.995026,0.64599859,23.689047,3.0538786E-08,25.383069,0z + + + M19.522852,25.255011L20.920847,25.256994 20.920847,29.729012 19.522852,29.729012z M22.826874,21.952002L25.989905,25.113989 25.001887,26.101996 21.838856,22.941015z M25.269894,19.506992L29.742937,19.509007 29.742937,20.906012 25.269894,20.907995z M10.519729,14.945011C11.300744,14.954991,12.079745,15.103001,12.818766,15.386997L10.878742,17.327C9.6457264,17.200016,8.368704,17.592014,7.4257004,18.532993L3.597655,22.359015C1.9326275,24.025 1.9316508,26.734991 3.597655,28.40299 5.2636887,30.068001 7.9747178,30.066017 9.6397144,28.40299L13.468767,24.575018C14.410794,23.633001,14.800783,22.355993,14.674774,21.122015L16.615807,19.181004C17.523806,21.547003,17.034817,24.325995,15.126776,26.233008L11.298761,30.061012C8.713709,32.644997 4.5236599,32.644997 1.9396465,30.061012 -0.64638097,27.475012 -0.64638097,23.286017 1.9386395,20.702002L5.7666852,16.875004C7.0777046,15.562992,8.8017227,14.922001,10.519729,14.945011z M2.1536381,10.959994L6.6257035,10.959994 6.6266801,12.359988 2.1536381,12.359988z M6.7686803,5.894014L9.9307338,9.0549947 8.9427158,10.044008 5.7806932,6.8819901z M10.976735,2.1390082L12.374761,2.1390082 12.375768,6.6130081 10.975728,6.6130081z M25.382902,0C27.076922,-1.8170738E-08 28.770941,0.6470033 30.063955,1.9389956 32.646992,4.5220043 32.646992,8.7130147 30.061941,11.297L26.234902,15.126011C24.326891,17.032993,21.546862,17.521,19.181845,16.614994L21.121868,14.674015C22.35586,14.798008,23.63389,14.407992,24.575886,13.467013L28.403933,9.6390096C30.067953,7.972994 30.069967,5.2619945 28.403933,3.5960094 26.738905,1.9310002 24.0269,1.9320073 22.361872,3.5960094L18.533827,7.4249893C17.591829,8.3659993,17.201811,9.6440145,17.32782,10.87601L15.385781,12.817996C14.477781,10.453005,14.968784,7.6730062,16.875818,5.7659928L20.702858,1.9379885C21.994864,0.64599622,23.688883,-1.8170738E-08,25.382902,0z + + + + M32.759,0C14.696,0,0,14.695,0,32.759s14.695,32.759,32.759,32.759s32.759-14.695,32.759-32.759S50.822,0,32.759,0z + M6,32.759C6,18.004,18.004,6,32.759,6c6.648,0,12.734,2.443,17.419,6.472L12.472,50.178C8.443,45.493,6,39.407,6,32.759z + M32.759,59.518c-5.948,0-11.447-1.953-15.895-5.248l37.405-37.405c3.295,4.448,5.248,9.947,5.248,15.895 + C59.518,47.514,47.514,59.518,32.759,59.518z + + 4 @@ -559,85 +557,27 @@ - - - - - - - - - - - - - - - - - - - + + + + + + + + + Show Strategy Params + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Best Bid Price (click to assign) + + + Hold a number key to cross the market by 'n' ticks. + + + + + + + + + + + + + + + + + + Best Ask Price (click to assign) + + + Hold a number key to cross the market by 'n' ticks. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Algo + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/client/spark/Modules/Trading/AlgoStudio/View/AlgoEditorGridView/AlgoEditorGridView.xaml.cs b/src/client/spark/Modules/Trading/AlgoStudio/View/AlgoEditorGridView/AlgoEditorGridView.xaml.cs new file mode 100644 index 000000000..c8dbb61a0 --- /dev/null +++ b/src/client/spark/Modules/Trading/AlgoStudio/View/AlgoEditorGridView/AlgoEditorGridView.xaml.cs @@ -0,0 +1,207 @@ +using bts.collections; +using bts.utils; +using mbts.spark; +using mbts.ui.controls; +using mbts.ui.converters; +using mbts.ui.utility; +using System; +using System.Collections; +using System.Collections.Generic; +using System.Linq; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Data; +using System.Windows.Documents; +using System.Windows.Input; + +namespace mbts.ui.spark { + partial class AlgoEditorGridView : UserControl { + public static readonly IValueConverter + GeneralVisualStateConverter = ValueConverter.create(is_read_only => is_read_only ? VisualStateNames.General.ReadOnly : VisualStateNames.General.Normal), + AlgoRootVisualStateConverter = ValueConverter.create(show_bbo => show_bbo ? VisualStateNames.AlgoRoot.Active : VisualStateNames.AlgoRoot.Inactive), + AlgoRootComboBoxMarginConverter = ValueConverter.create(name_col_width => new Thickness(name_col_width + 8, 0, 0, 0)), + NullableEnumParamRowItemsSourceConverter = ValueConverter.create(param_row => { + if (param_row?.param != null) { + var tenum = param_row.param.GetType().GetInterfaceGenericArgument(AlgoParamTemplateSelector.generic_algo_param_itype); + if (tenum.IsNullable()) { + // .First() should be safe, since we know this is a Nullable. + tenum = tenum.GetGenericArguments().First(); + } + if (tenum.IsEnum) + return Enum.GetValues(tenum); + } + return null; + }); + + public static readonly MouseButtonEventHandler PayupTicksMouseButtonHandler = (s, e) => { + if ((s as Hyperlink)?.Command is ICommand cmd) { + cmd.ExecuteIfCan(KeyboardExtensions.GetPressedNumber() ?? 0); + e.Handled = true; + } + }; + + readonly ObservableAggregateCollection _param_rows = new ObservableAggregateCollection(); + + public AlgoEditorGridView() { + InitializeComponent(); + _set_value_column_width(); + // AlgoRoots + AlgoRootsViewSource = new CollectionViewSource<_AlgoRootsCollectionView>(); + BindingOperations.SetBinding(AlgoRootsViewSource, CollectionViewSource.SourceProperty, new Binding(nameof(AlgoRoots)) { Source = this }); + AlgoRootsViewSource.GroupDescriptions.Add(new PropertyGroupDescription(nameof(IAlgoVM.group))); + // AlgoParamRows + AlgoParamRowsViewSource = new CollectionViewSource>(); + BindingOperations.SetBinding(AlgoParamRowsViewSource, CollectionViewSource.SourceProperty, new Binding(nameof(AlgoParamRows)) { Source = this }); + AlgoParamRowsViewSource.IsLiveFilteringRequested = true; + AlgoParamRowsViewSource.LiveFilteringProperties.Add(nameof(AlgoParamRowVM.permissions)); + AlgoParamRowsViewSource.Filter += param_rows_filter; + DataGridEditHelper.set_hooks(this); + void param_rows_filter(object sender, FilterEventArgs e) => + e.Accepted = e.Item is AlgoParamRowVM row && row.param.permissions != AlgoParamPermissions.None; + } + + public enum Columns { ParamName, Value } + + event Action CommitEditRequested, CancelEditRequested; + + public CollectionViewSource AlgoRootsViewSource { get; } + public CollectionViewSource> AlgoParamRowsViewSource { get; } + + bool _stretch_value_column = true; + public bool StretchValueColumn { + get => _stretch_value_column; + set { + if (_stretch_value_column != value) { + _stretch_value_column = value; + _set_value_column_width(); + } + } + } + + #region AnimateDirtyParams + public static readonly DependencyProperty AnimateDirtyProperty = + WPFHelper.create_dp(nameof(AnimateDirty), true); + + public bool AnimateDirty { + get => (bool)GetValue(AnimateDirtyProperty); + set => SetValue(AnimateDirtyProperty, value); + } + #endregion + + #region IsReadOnly + public static readonly DependencyProperty IsReadOnlyProperty = + WPFHelper.create_dp(nameof(IsReadOnly)); + + public bool IsReadOnly { + get => (bool)GetValue(IsReadOnlyProperty); + set => SetValue(IsReadOnlyProperty, value); + } + #endregion + + #region CanUserChangeAlgoRoot + public static readonly DependencyProperty CanUserChangeAlgoRootProperty = + WPFHelper.create_dp(nameof(CanUserChangeAlgoRoot)); + + public bool CanUserChangeAlgoRoot { + get => (bool)GetValue(CanUserChangeAlgoRootProperty); + set => SetValue(CanUserChangeAlgoRootProperty, value); + } + #endregion + + #region AlgoRoots + public static readonly DependencyProperty AlgoRootsProperty = + WPFHelper.create_dp, AlgoEditorGridView>(nameof(AlgoRoots)); + + public IReadOnlyObservableCollection AlgoRoots { + get => GetValue(AlgoRootsProperty) as IReadOnlyObservableCollection; + set => SetValue(AlgoRootsProperty, value); + } + #endregion + + #region SelectedAlgoRoot + public static readonly DependencyProperty SelectedAlgoRootProperty = + WPFHelper.create_dp(nameof(SelectedAlgoRoot), FrameworkPropertyMetadataOptions.BindsTwoWayByDefault); + + public IAlgoVM SelectedAlgoRoot { + get => GetValue(SelectedAlgoRootProperty) as IAlgoVM; + set => SetValue(SelectedAlgoRootProperty, value); + } + #endregion + + #region AlgoParamRows + public static readonly DependencyProperty AlgoParamRowsProperty = + WPFHelper.create_dp, AlgoEditorGridView>(nameof(AlgoParamRows)); + + public IReadOnlyObservableCollection AlgoParamRows { + get => GetValue(AlgoParamRowsProperty) as IReadOnlyObservableCollection; + set => SetValue(AlgoParamRowsProperty, value); + } + #endregion + + public static AlgoEditorGridView create_attach_view() => + new AlgoEditorGridView { + Margin = new Thickness(6), + CanUserChangeAlgoRoot = true, + }; + + public void commit_edit() => CommitEditRequested?.Invoke(); + public void cancel_edit() => CancelEditRequested?.Invoke(); + + void _set_value_column_width() { + foreach (var c in _param_grid?.Columns.empty_if_null()) + c.Width = _stretch_value_column ? new DataGridLength(1, DataGridLengthUnitType.Star) : DataGridLength.Auto; + } + + void _on_execution_strategy_toggle_click(object sender, RoutedEventArgs e) { + if (sender is Hyperlink hl && hl.try_find_ancestor_of_type(out DataGridRow row_view)) { + Visibility vis; string text; + if (row_view.DetailsVisibility == Visibility.Visible) { + vis = Visibility.Collapsed; + text = "Show Strategy Params"; + } else { + vis = Visibility.Visible; + text = "Hide Strategy Params"; + } + hl.Inlines.Clear(); + hl.Inlines.Add(text); + row_view.SetCurrentValue(DataGridRow.DetailsVisibilityProperty, vis); + } + } + + public static class VisualStateNames { + public static class General { + public const string GroupName = nameof(General); + + public static readonly string + Normal = $"{GroupName}{nameof(Normal)}", + ReadOnly = $"{GroupName}{nameof(ReadOnly)}"; + } + + public static class AlgoRoot { + public const string GroupName = nameof(AlgoRoot); + + public static readonly string + Active = $"{GroupName}{VisualStates.Active}", + Inactive = $"{GroupName}{VisualStates.Inactive}"; + } + } + + class _AlgoRootsCollectionView : ListCollectionView { + public _AlgoRootsCollectionView(IList list) : base(list) => + CustomSort = AlgoCollectionHelper.algo_vm_comparer.to_non_generic(); + } + } + + class AlgoEditorGridRowStyleSelector : StyleSelector { + public Style DefaultStyle { get; set; } + public Style SpreaderStyle { get; set; } + + public override Style SelectStyle(object item, DependencyObject container) { + if (item is AlgoParamRowVM row) { + if (row.param.id == nameof(bts.api.orderman.SpreaderOrderDefinition.ExecutionStrategy)) + return SpreaderStyle; + } + return DefaultStyle; + } + } +} diff --git a/src/client/spark/Modules/Trading/AlgoStudio/View/AlgoEditorGridView/AlgoParamRowsHelper.cs b/src/client/spark/Modules/Trading/AlgoStudio/View/AlgoEditorGridView/AlgoParamRowsHelper.cs new file mode 100644 index 000000000..5f4d64a32 --- /dev/null +++ b/src/client/spark/Modules/Trading/AlgoStudio/View/AlgoEditorGridView/AlgoParamRowsHelper.cs @@ -0,0 +1,88 @@ +using bts.collections; +using mbts.ui.controls; +using mbts.ui.utility; +using mbts.utils; +using System; +using System.Collections.ObjectModel; +using System.Reactive.Linq; +using System.Reactive.Disposables; + +namespace mbts.spark { + static class AlgoParamRowsHelper { + public static IDisposable connect(AlgoDefinitionVM algo, ObservableAggregateCollection rows, bool include_algo_type_rows) => + algo == null ? null : new CompositeDisposable(algo.observe_algo_root().SubscribeEach(a => { + rows.clear_collections(); + if (a == null) + return Disposable.empty; + var child_rows = new ObservableAggregateCollection(); + /// Note: the order of operations here matters + /// has the potential to trigger a lot of CollectionChanged events (depending on how deep the algo-tree is). + /// There is no need to burden the aggregate 'rows' with echoing all of these events, if the child-row collection is finished changing when it is added to the aggregate. + var hook = _wrap_rows(a, null, child_rows, include_algo_type_rows); + rows.add_collection(child_rows.AsReadOnly()); + return hook; + })) { + rows.clear_collections + }; + + public static IDisposable negate_is_dirty(IReadOnlyObservableCollection rows) { + return ObservableAutoWrapper.connect_item_hooks(rows, hook); + IDisposable hook(AlgoParamRowVM r) { + r.param.is_dirty_changed += negate; + return Disposable.Create(unhook); + void negate(bool is_dirty) { + if (is_dirty) + r.param.mark_committed(); + } + void unhook() => + r.param.is_dirty_changed -= negate; + } + } + + static IDisposable _wrap_rows(AlgoDefinitionVM algo_def, ObservableAggregateCollection rows, bool include_algo_type_rows) { + AlgoParamRowVM root = null; + ObservableAggregateCollection algo_params; + if (include_algo_type_rows) { + // while normal params live and die with the selected algo-type (when the algo-type changes, they are removed, and replaced with params for the new algo type), + // the algo-type row is constant (it is the row with the algo-type dropdown, which the user may use to select different algos). + algo_params = new ObservableAggregateCollection(); + rows.add_collection(new ObservableAppendCollection(algo_params, root = new AlgoSelectorParamRowVM(new AlgoVMWrapper(algo_def), algo_def, null)).AsReadOnly()); + } else { + algo_params = rows; + } + return algo_def.observe_algo_root().SubscribeEach(a => { + algo_params.clear_collections(); + if (a == null) + return Disposable.empty; + var child_rows = new ObservableAggregateCollection(); + /// Note: the order of operations here matters + /// has the potential to trigger a lot of CollectionChanged events (depending on how deep the algo-tree is). + /// There is no need to burden the aggregate 'rows' with echoing all of these events, if the child-row collection is finished changing when it is added to the aggregate. + var hook = _wrap_rows(a, root, child_rows, include_algo_type_rows); + algo_params.add_collection(child_rows.AsReadOnly()); + return hook; + }); + } + + static IDisposable _wrap_rows(IAlgoVM algo_root, AlgoParamRowVM parent, ObservableAggregateCollection all_rows, bool include_algo_type_rows) { + var wrapped_params = new ObservableAutoWrapper(algo_root.algo_params, pvm => new AlgoParamRowVM(algo_root, pvm, parent)); + var selector_params = new ObservableCollection(); + all_rows.add_collection(wrapped_params); + all_rows.add_collection(selector_params); + return ObservableAggregateCollection.connect(selector_params, algo_root.child_algo_selectors, new Func, IDisposable)>(hook_children)); + (ObservableCollection, IDisposable) hook_children(IAlgoSelector s) { + var child_rows = new ObservableAggregateCollection(); + var selector_wrapper = new AlgoSelectorParamRowVM(algo_root, s, parent); + return ( + include_algo_type_rows ? + (ObservableCollection)new ObservableAppendCollection(child_rows, selector_wrapper) : + child_rows, + s.subscribe_selected_algo().SubscribeEach(a => { + s.value = a; + child_rows.clear_collections(); + return _wrap_rows(a, selector_wrapper, child_rows, include_algo_type_rows); + })); + } + } + } +} diff --git a/src/client/spark/Modules/Trading/AlgoStudio/View/AlgoEditorGridView/AlgoParamTemplateSelector.cs b/src/client/spark/Modules/Trading/AlgoStudio/View/AlgoEditorGridView/AlgoParamTemplateSelector.cs new file mode 100644 index 000000000..11459e1bc --- /dev/null +++ b/src/client/spark/Modules/Trading/AlgoStudio/View/AlgoEditorGridView/AlgoParamTemplateSelector.cs @@ -0,0 +1,78 @@ +using bts.collections; +using bts.spark; +using mbts.spark; +using System; +using System.Collections; +using System.Collections.Generic; +using System.Linq; +using System.Reactive.Linq; +using System.Reflection; +using System.Windows; +using System.Windows.Controls; + +namespace mbts.ui.spark { + static class AlgoParamTemplateKeys { + public const string + Price = nameof(Price), + Size = nameof(Size); + } + + /// TODO: remove this class and just use a . + class AlgoParamTemplateSelector : DataTemplateSelector { + public static readonly Type generic_algo_param_itype = typeof(IAlgoParamVM<>); + + KeyedCollection _keyed_templates = new KeyedCollection(tsk => tsk.Key); + + public DataTemplate BoolTemplate { get; set; } + public DataTemplate NullableBoolTemplate { get; set; } + public DataTemplate IntTemplate { get; set; } + public DataTemplate NullableIntTemplate { get; set; } + public DataTemplate UIntTemplate { get; set; } + public DataTemplate NullableUIntTemplate { get; set; } + public DataTemplate DoubleTemplate { get; set; } + public DataTemplate EnumTemplate { get; set; } + public DataTemplate NullableEnumTemplate { get; set; } + public DataTemplate StringTemplate { get; set; } + public DataTemplate QuantityMeasureTemplate { get; set; } + public DataTemplate OrderDefTemplate { get; set; } + public DataTemplate ExecutionStrategyTemplate { get; set; } + public DataTemplate TimestampTemplate { get; set; } + + /// is needed for the 'price' param. Price was formerly edited in a separate control, however now it is just another param row. + /// Before this, the generic type argument in the implementation was enough to determine the template. + /// Since 'price' is just a double, further specification was needed to associate it with a 'PriceEntryControl' template. + public IList KeyedTemplates => _keyed_templates; + + public override DataTemplate SelectTemplate(object item, DependencyObject container) { + if (item is ITemplateSelectorKey tsk && tsk.key is string template_key && _keyed_templates.TryGetValue(template_key, out var tkv)) + return tkv.Value; + IAlgoParamVM pvm = item as IAlgoParamVM ?? (item as AlgoParamRowVM)?.param; + if (pvm != null) { + if (pvm is IAlgoParamVM) return DoubleTemplate; + if (pvm is IAlgoParamVM) return IntTemplate; + if (pvm is IAlgoParamVM) return NullableIntTemplate; + if (pvm is IAlgoParamVM) return UIntTemplate; + if (pvm is IAlgoParamVM) return NullableUIntTemplate; + if (pvm is IAlgoParamVM) return NullableBoolTemplate; + if (pvm is IAlgoParamVM) return BoolTemplate; + if (pvm is IAlgoParamVM) return StringTemplate; + if (pvm is IAlgoParamVM) return OrderDefTemplate; + if (pvm is IAlgoParamVM) return QuantityMeasureTemplate; + if (pvm is IAlgoParamVM) return ExecutionStrategyTemplate; + if (pvm is IAlgoParamVM) return TimestampTemplate; + var targ = ReflectionHelper.GetGenericTypeArgs(pvm.GetType(), generic_algo_param_itype).FirstOrDefault(); + if (targ != null) { + if (targ.IsEnum) + return EnumTemplate; + else if (targ.IsNullable()) { + targ = targ.GetGenericArguments()[0]; + if (targ.IsEnum) + return NullableEnumTemplate; + } + + } + } + return null; + } + } +} diff --git a/src/client/spark/Modules/Trading/AlgoStudio/View/AlgoEditorGridView/DataGridEditHelper.cs b/src/client/spark/Modules/Trading/AlgoStudio/View/AlgoEditorGridView/DataGridEditHelper.cs new file mode 100644 index 000000000..d232ab8c7 --- /dev/null +++ b/src/client/spark/Modules/Trading/AlgoStudio/View/AlgoEditorGridView/DataGridEditHelper.cs @@ -0,0 +1,181 @@ +#define ENTER_BEHAVES_LIKE_TAB +using bts; +using mbts.ui.controls; +using mbts.ui.extensions; +using mbts.ui.spark.algo; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reactive.Linq; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Controls.Primitives; +using System.Windows.Input; + +namespace mbts.ui.spark { + partial class AlgoEditorGridView { + static class DataGridEditHelper { + public static IDisposable set_hooks(AlgoEditorGridView algo_editor) { + var grid = algo_editor._param_grid; + grid.PreviewKeyDown += on_preview_key_down; + grid.KeyDown += on_key_down; + grid.SelectionChanged += on_selection_changed; + grid.PreparingCellForEdit += on_preparing_cell_for_edit; + grid.CellEditEnding += on_cell_edit_ending; + grid.GotFocus += on_got_focus; + algo_editor.CommitEditRequested += on_commit_edit_requested; + algo_editor.CancelEditRequested += on_cancel_edit_requested; + return Disposable.Create(() => { + grid.PreviewKeyDown += on_preview_key_down; + grid.KeyDown -= on_key_down; + grid.SelectionChanged -= on_selection_changed; + grid.PreparingCellForEdit -= on_preparing_cell_for_edit; + grid.CellEditEnding -= on_cell_edit_ending; + grid.GotFocus -= on_got_focus; + algo_editor.CommitEditRequested -= on_commit_edit_requested; + algo_editor.CancelEditRequested -= on_cancel_edit_requested; + }); + /// Handlers + // hooked up to PreviewKeyDown, instead of KeyDown, so the cells can't override this behavior + void on_preview_key_down(object sender, KeyEventArgs e) { + switch (e.Key) { + case Key.Escape: e.Handled = cancel_edit(); break; + case Key.Enter: + if (grid.TryGetCurrentRowView(out var row_view)) { + if (row_view.IsEditing) { + commit_edit(); +#if ENTER_BEHAVES_LIKE_TAB + NavigationHelper.keyboard_move_focus(FocusNavigationDirection.Down); +#endif + } else grid.BeginEdit(); + } + e.Handled = true; + break; + } + } + + // hooked up to KeyDown, instead of PreviewKeyDown, so cells can implement custom Key/CommandBindings, or other key-based behavior without the DataGrid handling it in the PreviewKeyDown event. + // for ex: TickUpDown cells can do things like TickUp/Down when Ctrl+Up/Down arrow-key is pressed. + void on_key_down(object sender, KeyEventArgs e) { + switch (e.Key) { + case Key.Up: NavigationHelper.keyboard_move_focus(FocusNavigationDirection.Up); break; + case Key.Down: NavigationHelper.keyboard_move_focus(FocusNavigationDirection.Down); break; + default: return; + } + e.Handled = true; + } + + void on_selection_changed(object sender, SelectionChangedEventArgs e) { + _commit(e.RemovedItems?.Cast()?.SafeSingleOrDefault()); + _commit(e.AddedItems?.Cast()?.SafeSingleOrDefault()); + void _commit(object row_item) { + if (grid.TryGetRowView(row_item, out var row_view) && row_view.IsEditing) + grid.CommitEdit(); + } + } + + void on_preparing_cell_for_edit(object sender, DataGridPreparingCellForEditEventArgs e) { + if (e.EditingElement is ContentPresenter presenter) { + OneOf.Match(get, get, get, get, text_box, combo_box, quantity_measure_control, toggle_button); + T get() => presenter.descendants_of_type().FirstOrDefault(); + // TextBox + void text_box(TextBox tb) => Keyboard.Focus(tb); + // ComboBox + void combo_box(ComboBox cb) { } + // QuantityMeasureControl + async void quantity_measure_control(QuantityMeasureControl qmc) { + if (!focus_text()) { + await qmc.LoadedAsync(); + focus_text(); + } + bool focus_text() => + qmc.try_find_descendent_of_type(out TextBox tb) && Keyboard.Focus(tb) == tb; + } + // ToggleButton + void toggle_button(ToggleButton tb) { + if (Mouse.LeftButton == MouseButtonState.Pressed && !tb.IsLoaded) { + // this is a hack to toggle IsChecked when the user clicks a checkbox cell that is not already in edit mode. + IDisposable dispose = null; + dispose = Disposable.Create( + tb.SubscribePreviewMouseUp(on_mouse_up), + tb.SubscribeMouseLeave(on_mouse_leave)); + void on_mouse_up(object s, MouseButtonEventArgs mbe) { + if (tb.IsMouseOver) + tb.SetCurrentValue(ToggleButton.IsCheckedProperty, !tb.IsChecked); + Disposable.dispose(ref dispose); + } + void on_mouse_leave(object s, MouseEventArgs me) => + Disposable.dispose(ref dispose); + } + } + } + e.EditingElement.Focus(); + } + + void on_cell_edit_ending(object sender, DataGridCellEditEndingEventArgs e) { + if (e.EditingElement is ContentPresenter presenter) { + switch (e.EditAction) { + case DataGridEditAction.Cancel: OneOf.Match(get, get, get, cancel_text_box, cancel_combo_box, cancel_toggle_button); break; + case DataGridEditAction.Commit: OneOf.Match(get, get, get, commit_text_box, commit_combo_box, commit_toggle_button); break; + } + T get() => presenter.descendants_of_type().FirstOrDefault(); + // TextBox + void commit_text_box(TextBox tb) => tb.GetBindingExpression(TextBox.TextProperty)?.UpdateSource(); + void cancel_text_box(TextBox tb) => tb.GetBindingExpression(TextBox.TextProperty)?.UpdateTarget(); + // ComboBox + void commit_combo_box(ComboBox cb) { } + void cancel_combo_box(ComboBox cb) { } + // ToggleButton + void commit_toggle_button(ToggleButton tb) { } + void cancel_toggle_button(ToggleButton tb) { } + } + } + + void on_got_focus(object sender, RoutedEventArgs e) { + if (e.OriginalSource is DataGridCell cell && cell.try_find_ancestor_of_type(out DataGridRow row)) { + if (row.IsEditing) { + if (!cell.IsEditing) { + grid.CancelEdit(DataGridEditingUnit.Row); + if (try_set_current()) + grid.BeginEdit(e); + } + } else { + try_set_current(); + if (!row.IsEditing) + grid.BeginEdit(e); + } + bool try_set_current() { + grid.SetCurrentValue(DataGrid.CurrentItemProperty, row.Item); + if (grid.TryGetCurrentRowView(out var row_view)) { + row_view.SetCurrentValue(DataGridRow.IsSelectedProperty, true); + grid.SetCurrentValue(DataGrid.CurrentCellProperty, new DataGridCellInfo(row.Item, grid.Columns[1])); + return true; + } else return false; + } + } + } + + void on_commit_edit_requested() { + if (grid.TryGetCurrentRowView(out var row_view) && row_view.IsEditing) + commit_edit(); + } + + void commit_edit() { + using (grid.SuspendGotFocus(on_got_focus)) + grid.CommitEdit(DataGridEditingUnit.Row, true); + } + + void on_cancel_edit_requested() => + cancel_edit(); + + bool cancel_edit() { + if (grid.CurrentCell != null && grid.TryGetCurrentRowView(out var row_view) && row_view.IsEditing) { + using (grid.SuspendGotFocus(on_got_focus)) + grid.CancelEdit(DataGridEditingUnit.Row); + return true; + } else return false; + } + } + } + } +} \ No newline at end of file diff --git a/src/client/spark/Modules/Trading/AlgoStudio/View/AlgoEditorView.xaml b/src/client/spark/Modules/Trading/AlgoStudio/View/AlgoEditorView.xaml new file mode 100644 index 000000000..179c48a45 --- /dev/null +++ b/src/client/spark/Modules/Trading/AlgoStudio/View/AlgoEditorView.xaml @@ -0,0 +1,120 @@ + + + + + + + + + 4 + 8 + 12 + 4 + 8 + 12 + + + + + + + + + + + + + + + + + + + + + + + + + + + + AllowEditStructure + + + + + + + + + + + + + + - - + + @@ -172,7 +172,7 @@ - + diff --git a/src/client/spark/view/Spark/Ladder/LadderSettingsView.xaml.cs b/src/client/spark/Modules/Trading/Ladder/View/LadderSettingsView.xaml.cs similarity index 100% rename from src/client/spark/view/Spark/Ladder/LadderSettingsView.xaml.cs rename to src/client/spark/Modules/Trading/Ladder/View/LadderSettingsView.xaml.cs diff --git a/src/client/spark/view/Spark/Ladder/LadderTactileAdorner.cs b/src/client/spark/Modules/Trading/Ladder/View/LadderTactileAdorner.cs similarity index 90% rename from src/client/spark/view/Spark/Ladder/LadderTactileAdorner.cs rename to src/client/spark/Modules/Trading/Ladder/View/LadderTactileAdorner.cs index d2687010d..ef8d80395 100644 --- a/src/client/spark/view/Spark/Ladder/LadderTactileAdorner.cs +++ b/src/client/spark/Modules/Trading/Ladder/View/LadderTactileAdorner.cs @@ -1,9 +1,9 @@ using mbts.ui; using mbts.ui.controls; using mbts.ui.extensions; -using mbts.ui.utility.text; using System; using System.Collections.Generic; +using System.Reactive.Linq; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; @@ -30,7 +30,7 @@ namespace mbts.spark { readonly LadderGridHost _host; readonly IList _hooks; - bool _is_mouse_over, _is_mouse_down, _is_mouse_dragging; + bool _is_mouse_over, _is_mouse_down, _is_mouse_dragging, _can_send_orders; int _curr_row; Column _curr_column = Column.Empty; @@ -41,6 +41,10 @@ namespace mbts.spark { _bid_mouse_down_pen = new Pen(new SolidColorBrush(Color.FromRgb(102, 178, 255)), 1).frozen(); _ask_mouse_down_pen = new Pen(new SolidColorBrush(Color.FromRgb(255, 178, 102)), 1).frozen(); _hooks = new List { + _host._subscribe_can_send_orders().Subscribe(v => { + _can_send_orders = v; + _host.Cursor = _evaluate_position(); + }), _host.SubscribeMouseEnter(_host_MouseEnter), _host.SubscribeMouseMove(_host_MouseMove), _host.SubscribeMouseLeave(_host_MouseLeave), @@ -88,7 +92,7 @@ namespace mbts.spark { _draw_cell(drawingContext, _navy_pen, x, y, _curr_column.settings.width); } } - else if (_is_mouse_over && (_curr_column.column_type == ColumnType.Bid || _curr_column.column_type == ColumnType.Ask)) { + else if (_is_mouse_over && _can_send_orders && (_curr_column.column_type == ColumnType.Bid || _curr_column.column_type == ColumnType.Ask)) { double y = _curr_row * _host._settings.row_height; double x = _curr_column.x_left; Pen style = default; @@ -112,12 +116,17 @@ namespace mbts.spark { } } + Cursor _evaluate_position() { + var pos = Mouse.GetPosition(_host); + return _evaluate_position(_host._column_for_point(pos), pos, _host.columns); + } + Cursor _evaluate_position(Column column, Point point, Column[] columns) { if (columns.Length == 0) return Cursors.Arrow; switch (column.column_type) { case ColumnType.Bid: - case ColumnType.Ask: return Cursors.Hand; + case ColumnType.Ask: return _can_send_orders ? Cursors.Hand : Cursors.No; default: return Cursors.Arrow; } } diff --git a/src/client/spark/view/Spark/Ladder/LadderView.xaml b/src/client/spark/Modules/Trading/Ladder/View/LadderView.xaml similarity index 97% rename from src/client/spark/view/Spark/Ladder/LadderView.xaml rename to src/client/spark/Modules/Trading/Ladder/View/LadderView.xaml index dc8b3afc2..7b4a662c2 100644 --- a/src/client/spark/view/Spark/Ladder/LadderView.xaml +++ b/src/client/spark/Modules/Trading/Ladder/View/LadderView.xaml @@ -466,7 +466,7 @@ + + + + + Auto Clear + + - - - - - Auto Clear - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/client/spark/Modules/Trading/OrderBook/View/OrderBookView.xaml.cs b/src/client/spark/Modules/Trading/OrderBook/View/OrderBookView.xaml.cs new file mode 100644 index 000000000..db144e084 --- /dev/null +++ b/src/client/spark/Modules/Trading/OrderBook/View/OrderBookView.xaml.cs @@ -0,0 +1,290 @@ +using bts.api.orderman; +using bts.utils; +using mbts.ui; +using mbts.ui.controls; +using mbts.ui.controls.adorners; +using mbts.ui.converters; +using mbts.ui.extensions; +using mbts.ui.spark; +using mbts.ui.utilities; +using mbts.ui.utility; +using mbts.utils; +using System; +using System.Collections; +using System.Reactive.Disposables; +using System.Reactive.Linq; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Data; +using System.Windows.Input; +using System.Windows.Media; +using OrderParamsVM = mbts.spark.OrderBookVM.OrderParamsVM; + +namespace mbts.spark { + internal partial class OrderBookView : UserControl { + public const double + GridSplitterWidth = 5, + GridSplitterHeight = 5; + + public static readonly IValueConverter + RightPanelVisualStateConverter = ValueConverter.create(show_panel => show_panel ? VisualStateNames.RightPanel.Active : VisualStateNames.RightPanel.Inactive), + OrderParamsVisualStateConverter = ValueConverter.create(row => row != null ? VisualStateNames.OrderDescription.Active : VisualStateNames.OrderDescription.Inactive), + ToolBarMenuItemHeightConverter = ValueConverter.create(padding => padding.Top + 22 + padding.Bottom), + LadderVisualStateConverter = ValueConverter.create(security_plurality => { + switch (security_plurality) { + case Plurality.None: return VisualStateNames.Ladder.NoSecuritySelected; + case Plurality.One: return VisualStateNames.Ladder.OneSecuritySelected; + case Plurality.Many: return VisualStateNames.Ladder.ManySecuritiesSelected; + default: return null; + } + }); + + public static readonly IMultiValueConverter + RightPanelDialogSkirtLeftAnchorConverter = ValueConverter.create((canvas_width, skirt_width) => canvas_width - skirt_width + GridSplitterWidth), + SlaveDataVisualStateConverter = ValueConverter.create( + (show_order_params, show_fills, show_ladder) => { + VisualStateNames.SlaveData.Data d = (VisualStateNames.SlaveData.Data)0; + if (show_order_params) + d |= VisualStateNames.SlaveData.Data.OrderParams; + if (show_fills) + d |= VisualStateNames.SlaveData.Data.Fills; + if (show_ladder) + d |= VisualStateNames.SlaveData.Data.Ladder; + return VisualStateNames.SlaveData.fmt_name(d); + }); + static readonly IMultiValueConverter + _right_panel_expander_margin_converter = ValueConverter.create( + (is_expanded, scrollbar_vis) => + !is_expanded && scrollbar_vis == Visibility.Visible ? + new Thickness(0, DIYGrid.DefaultColumnHeaderHeight, SystemParameters.VerticalScrollBarWidth, 0) : + new Thickness(0)); + + IDisposable _attach_op; + + public OrderBookView(OrderBookVM vm) { + InitializeComponent(); + DataContext = vm; + bind_right_panel_expander_margin(); + var algo_editor_cm = new ContextMenu(); + algo_editor_cm.Items.AddRange(order_mod_menu()); + algo_editor.ContextMenu = algo_editor_cm; + vm.SubscribeDisposed( + Disposable.Create( + algo_editor._param_grid.SubscribeIsEditing().SubscribeEach(is_editing => is_editing ? orders_grid.SubscribeGotFocus(on_orders_grid_got_focus) : null), + WPFHelper.connect_vertical_splitter_components(vm, right_panel_content_root.RowDefinitions, 2, + /*order params*/(order_params_root, nameof(OrderBookVM.order_params_height), vm.subscribe_show_order_params()), + /*mini ladder */(ladder, nameof(OrderBookVM.ladder_height), vm.subscribe_show_ladder()), + /*fills grid */(fills_grid, nameof(OrderBookVM.fills_height), vm.subscribe_show_fills()))) + ); + // 'send attach orders' behavior + vm.begin_attaching += begin_attach_orders; + vm.end_attaching += () => Disposable.dispose(ref _attach_op); + // 'scroll to current order' behavior (mini ladder) + vm.SubscribeDisposed(vm.subscribe_show_ladder().SubscribeEach(show => show ? connect_mini_ladder_auto_scroll() : null)); + IDisposable connect_mini_ladder_auto_scroll() { + bool is_busy = false; + vm.selected_order_changed += on_selected_order_changed; + return Disposable.Create(() => vm.selected_order_changed -= on_selected_order_changed); + async void on_selected_order_changed(OrderRecordImmutable? order) { + if (order.HasValue && !is_busy) { + is_busy = true; + await Task.Delay(200); + if (vm.current_order.HasValue && vm.current_order.Value.security_key() == ladder.ladder_grid_host.security.Id && vm.current_order.Value.is_active()) + ladder.ladder_grid_host.scroll_to_price(vm.current_order.Value.price()); + is_busy = false; + } + } + } + + void on_orders_grid_got_focus(object sender, RoutedEventArgs e) { + if (e.OriginalSource is ListBoxItem && algo_editor._param_grid.TryGetCurrentRowView(out var row_view) && row_view.IsEditing) + algo_editor._param_grid.CancelEdit(); + } + + IEnumerable order_mod_menu() { + var revert_cell_mi = new MenuItem(); + var revert_cell_cmd = new DelegateCommand(revert_impl, () => get_current_row()?.param?.is_dirty ?? false); + revert_cell_mi.Command = revert_cell_cmd; + IDisposable param_is_dirty_sub = null; + algo_editor._param_grid.CurrentCellChanged += on_current_cell_changed; + // menu items + yield return revert_cell_mi; + yield return new MenuItem { + Header = CommandHelper.fmt("Revert All", KeyboardShortcuts.RevertOrders), + Command = vm.revert_selected_orders_cmd + }; + yield return new Separator(); + yield return new MenuItem { + Header = CommandHelper.fmt("Modify Orders", KeyboardShortcuts.ModifyOrders), + Command = CommandWithActionWrapper.wrap(vm.modify_selected_orders_cmd, algo_editor.commit_edit) + }; + // local methods + AlgoParamRowVM get_current_row() => algo_editor._param_grid.SelectedItem as AlgoParamRowVM; + void on_current_cell_changed(object sender, EventArgs e) { + Disposable.dispose(ref param_is_dirty_sub); + var r = get_current_row(); + var header = new StringBuilderEx("Revert "); + revert_cell_cmd.RaiseCanExecuteChanged(); + if (r != null) { + header.Add("'", r.param.display_name, "'"); + r.param.is_dirty_changed += on_is_dirty_changed; + param_is_dirty_sub = Disposable.Create(dispose); + // local methods + void on_is_dirty_changed(bool _) => revert_cell_cmd.RaiseCanExecuteChanged(); + void dispose() => r.param.is_dirty_changed -= on_is_dirty_changed; + } else { + header.Add("(Param)"); + } + revert_cell_mi.Header = header.ToString(); + } + void revert_impl() { + if (get_current_row() is AlgoParamRowVM r) { + algo_editor.cancel_edit(); + r.param.revert(); + } + } + } + + async void bind_right_panel_expander_margin() { + if (!orders_grid.IsLoaded) + await orders_grid.LoadedAsync(); + if (orders_grid.try_find_descendent_of_type(out DIYGridRowsPresenter rows_presenter)) { + if (rows_presenter.try_find_descendent_of_type(out ScrollViewer scroll_viewer)) { + var mb = new MultiBinding { Converter = _right_panel_expander_margin_converter }; + mb.Bindings.Add(new Binding(nameof(OrderBookVM.show_right_panel)) { Source = vm }); + mb.Bindings.Add(new Binding(nameof(ScrollViewer.ComputedVerticalScrollBarVisibility)) { Source = scroll_viewer }); + right_panel_expander_toggle.SetBinding(MarginProperty, mb); + } + } + } + } + + public new OrderBookVM DataContext { + get => base.DataContext as OrderBookVM; + set => base.DataContext = value; + } + + public void begin_attach_orders() { + Disposable.dispose(ref _attach_op); + var vm = DataContext.attach_vm; + // attach orders view + var attach_orders_view = AlgoEditorGridView.create_attach_view(); + attach_orders_view.DataContext = vm; + attach_orders_view.StretchValueColumn = false; + attach_orders_view.SetBinding(AlgoEditorGridView.AlgoRootsProperty, new Binding(string.Join(".", nameof(OrderParamsVM.algo_vm), nameof(AlgoDefinitionVM.algo_roots))) { Source = vm }); + attach_orders_view.SetBinding(AlgoEditorGridView.SelectedAlgoRootProperty, new Binding(string.Join(".", nameof(OrderParamsVM.algo_vm), nameof(AlgoDefinitionVM.algo_root))) { Source = vm }); + attach_orders_view.SetBinding(AlgoEditorGridView.AlgoParamRowsProperty, new Binding(nameof(OrderParamsVM.param_rows)) { Source = vm }); + // dialog skirt + var dialog_skirt = new DialogSkirt { + RightItems = new[] { + new DialogSkirtItem("Attach To Orders", DataContext.send_attached_orders_cmd) { is_default = true }, + new DialogSkirtItem("Cancel", new DelegateCommand(() => Disposable.dispose(ref _attach_op))) { is_cancel = true } + } + }; + Grid.SetRow(dialog_skirt, 1); + // grid + var grid = new Grid(); + grid.RowDefinitions.Add(new RowDefinition { Height = new GridLength(1, GridUnitType.Star) }); + grid.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto }); + grid.Children.Add(attach_orders_view); + grid.Children.Add(dialog_skirt); + // popup adorner + var popup_adorner = new PopupAdorner( + orders_grid, orders_grid, + new Border { + Child = grid, + Background = BTSColors.common_background_brush, + BorderBrush = Brushes.Black, + BorderThickness = new Thickness(1) + }, + HorizontalPosition.Middle, + VerticalPosition.Middle, + 0, + orders_grid.RowHeight) { + OpenRelativeToMouse = true, + ClipToBounds = true + }; + popup_adorner.attach(); + popup_adorner.IsOpen = true; + // attach op (dispose) + _attach_op = new CompositeDisposable(orders_grid.SubscribePreviewMouseDown((s, e) => { + if (!KeyboardExtensions.IsShiftDown() && !KeyboardExtensions.IsCtrlDown() && !popup_adorner.PopupElement.IsMouseOver) + Disposable.dispose(ref _attach_op); + })) { + () => { + popup_adorner.IsOpen = false; + popup_adorner.detach(); + DataContext.is_attaching_orders = false; + } + }; + } + + public static class CommandDescriptions { + public static readonly string + ShowRightPanel = "Show Details Panel", + HideRightPanel = "Hide Details Panel", + ModifyOrders = "Modify selected orders", + RevertOrders = "Revert modifications to selected orders"; + } + + public static class KeyboardShortcuts { + public static readonly KeyGesture + ToggleShowRightPanel = new KeyGesture(Key.M, ModifierKeys.Control | ModifierKeys.Shift), + ModifyOrders = new KeyGesture(Key.S, ModifierKeys.Control | ModifierKeys.Shift), + RevertOrders = new KeyGesture(Key.R, ModifierKeys.Control); + } + + public static class VisualStateNames { + public static class RightPanel { + public const string GroupName = nameof(RightPanel); + + public static readonly string + Active = $"{GroupName}{VisualStates.Active}", + Inactive = $"{GroupName}{VisualStates.Inactive}"; + } + + public static class OrderDescription { + public const string GroupName = nameof(OrderDescription); + + public static readonly string + Active = $"{GroupName}{VisualStates.Active}", + Inactive = $"{GroupName}{VisualStates.Inactive}"; + } + + public static class Ladder { + public const string GroupName = nameof(Ladder); + + public static readonly string + NoSecuritySelected = $"{GroupName}{nameof(NoSecuritySelected)}", + OneSecuritySelected = $"{GroupName}{nameof(OneSecuritySelected)}", + ManySecuritiesSelected = $"{GroupName}{nameof(ManySecuritiesSelected)}"; + } + + public static class SlaveData { + public const string GroupName = nameof(SlaveData); + + public static readonly string + None = $"{GroupName}{nameof(None)}", + OrderParams = $"{GroupName}{nameof(OrderParams)}", + OrderParamsLadder = $"{GroupName}{nameof(OrderParamsLadder)}", + OrderParamsFills = $"{GroupName}{nameof(OrderParamsFills)}", + OrderParamsLadderFills = $"{GroupName}{nameof(OrderParamsLadderFills)}", + LadderFills = $"{GroupName}{nameof(LadderFills)}", + Ladder = $"{GroupName}{nameof(Ladder)}", + Fills = $"{GroupName}{nameof(Fills)}"; + + public enum Data { + OrderParams = 1, + Ladder = 1 << 1, + Fills = 1 << 2 + } + + public static string fmt_name(Data d) { + var vis_data = string.Join("", EnumHelper.split_flags(d)); + return vis_data == string.Empty ? None : GroupName + vis_data; + } + } + } + } +} diff --git a/src/client/spark/Modules/Trading/OrderBook/View/OrderParamsPanel.xaml b/src/client/spark/Modules/Trading/OrderBook/View/OrderParamsPanel.xaml new file mode 100644 index 000000000..b7e3bb85a --- /dev/null +++ b/src/client/spark/Modules/Trading/OrderBook/View/OrderParamsPanel.xaml @@ -0,0 +1,285 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -43,10 +33,14 @@ - + - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/client/spark/view/Spark/SparkWindowView.xaml.cs b/src/client/spark/view/Spark/SparkWindowView.xaml.cs index 164fc5897..f4c9f2ad7 100644 --- a/src/client/spark/view/Spark/SparkWindowView.xaml.cs +++ b/src/client/spark/view/Spark/SparkWindowView.xaml.cs @@ -7,10 +7,12 @@ using System.Linq; using System.Windows; using System.Windows.Controls; using System.Windows.Data; +using System.Windows.Input; namespace bts.view { public partial class SparkWindowView : UserControl { - SparkMenu _menu; + readonly SparkMenu _menu; + public SparkWindowView(IBus bus, IEnumerable commands, UIElement content) { InitializeComponent(); @@ -26,11 +28,17 @@ namespace bts.view { _menu.BorderThickness = new Thickness(0, 0, 0, 0); _menu.ShowText = false; _grid.Children.Add(_menu); + foreach (var cmd in commands) { + if (cmd.key_gesture != null) + InputBindings.Add(new KeyBinding(cmd.ICommand(bus), cmd.key_gesture)); + } if (ContextMenu != null) { // ObservableCollection to avoid WPF Binding Leak - var context_menu_items_view = new ListCollectionView(new ObservableCollection(commands.Select(c => new SparkCommandVM(c, bus)))) { + ContextMenuItems = new ObservableCollection(commands.Select(c => new SparkCommandVM(c, bus))); + var context_menu_items_view = new ListCollectionView(ContextMenuItems) { Filter = item => (item as SparkCommandVM)?.show_in_context_menu ?? false }; + context_menu_items_view.GroupDescriptions.Add(new PropertyGroupDescription(nameof(SparkCommandVM.group))); context_menu_items_view.LiveFilteringProperties.Add(nameof(SparkCommandVM.show_in_context_menu)); ContextMenu.ItemsSource = context_menu_items_view; } @@ -40,6 +48,8 @@ namespace bts.view { } } + public ObservableCollection ContextMenuItems { get; } + public void collapse_click(object sender, RoutedEventArgs e) { _menu.ShowText = !_menu.ShowText; } diff --git a/src/client/spark/view/Spark/Utilities/BBOVM.cs b/src/client/spark/view/Spark/Utilities/BBOVM.cs index ddf44404f..f4ce1111d 100644 --- a/src/client/spark/view/Spark/Utilities/BBOVM.cs +++ b/src/client/spark/view/Spark/Utilities/BBOVM.cs @@ -1,30 +1,45 @@ using bts.api; -using mbts.spark.utilities; using mbts.ui.shell; using System; -using System.Reactive.Linq; namespace mbts.spark { class BBOVM : DisposableViewModelBase { - readonly Property _security; - readonly Property _bid, _ask; - readonly Property _bid_size, _ask_size; + IDisposable _md_poll; + SecurityMD? _security_md; + double _bid, _ask; + uint _bid_size, _ask_size; + ulong _time; - public BBOVM(IObservable security_md) - : this(security_md.Select(smd => smd.security).OnDispatcher(), new SecurityMDPump(security_md.Select(smd => smd.md))) { } - - public BBOVM(IObservable security, ISecurityMDPump md_pump) { - _security = backing(nameof(security), security, SecurityDataHelper.Defaults.SecurityImmutable); - _bid = backing(nameof(bid), md_pump.bid_price, double.NaN); - _ask = backing(nameof(ask), md_pump.ask_price, double.NaN); - _bid_size = backing(nameof(bid_size), md_pump.bid_size, (uint)0); - _ask_size = backing(nameof(ask_size), md_pump.ask_size, (uint)0); + public SecurityImmutable? security => _security_md?.security; + public SecurityMD? security_md { + get => _security_md; + set { + if (_security_md != value) { + _security_md = value; + RaisePropertyChanged(nameof(security)); + _begin_polling(); + } + } } + public double bid => _bid; + public double ask => _ask; + public uint bid_size => _bid_size; + public uint ask_size => _ask_size; - public SecurityImmutable security => _security.Value; - public double bid => _bid.Value; - public double ask => _ask.Value; - public uint bid_size => _bid_size.Value; - public uint ask_size => _ask_size.Value; + void _begin_polling() { + Disposable.dispose(ref _md_poll); + if (security_md.HasValue) { + var md = security_md.Value.md; + _md_poll = WorkLoop.Start($"{nameof(BBOVM)} md poll.", poll); + void poll() { + if (md.get_bbo(ref _time, out co2.NativePriceSize bid, out co2.NativePriceSize ask)) { + Set(ref _bid, bid.price, nameof(bid)); + Set(ref _bid_size, bid.size, nameof(bid_size)); + Set(ref _ask, ask.price, nameof(ask)); + Set(ref _ask_size, ask.size, nameof(ask_size)); + } + } + } + } } } \ No newline at end of file diff --git a/src/client/spark/view/Spark/Utilities/Grid/GridAnimation/DIYGridAnimationAdorner.cs b/src/client/spark/view/Spark/Utilities/Grid/GridAnimation/DIYGridAnimationAdorner.cs index 791f051d7..a13d68bf0 100644 --- a/src/client/spark/view/Spark/Utilities/Grid/GridAnimation/DIYGridAnimationAdorner.cs +++ b/src/client/spark/view/Spark/Utilities/Grid/GridAnimation/DIYGridAnimationAdorner.cs @@ -1,4 +1,5 @@ -using mbts.ui.controls; +using bts.collections; +using mbts.ui.controls; using System; using System.Collections.Generic; using System.Linq; @@ -74,8 +75,8 @@ namespace mbts.ui.spark { } void _grid_RowAnimationChanged(object sender, RowAnimationChangedEventArgs e) { - if (ListExtensions.IsNullOrEmpty(e.NewValue)) { - if (ListExtensions.IsNullOrEmpty(e.OldValue)) { + if (e.NewValue.IsNullOrEmpty()) { + if (e.OldValue.IsNullOrEmpty()) { return; } else _row_animation_map.Remove(e.Row); } else { diff --git a/src/client/spark/view/Spark/Utilities/Grid/GridAnimation/GridAnimationAdorner.cs b/src/client/spark/view/Spark/Utilities/Grid/GridAnimation/GridAnimationAdorner.cs index 242c239c2..25a2170ea 100644 --- a/src/client/spark/view/Spark/Utilities/Grid/GridAnimation/GridAnimationAdorner.cs +++ b/src/client/spark/view/Spark/Utilities/Grid/GridAnimation/GridAnimationAdorner.cs @@ -1,4 +1,5 @@ -using mbts.ui.controls; +using bts.collections; +using mbts.ui.controls; using System; using System.Collections.Generic; using System.Linq; diff --git a/src/client/spark/view/Spark/Utilities/Grid/GridRowViewModelBase.cs b/src/client/spark/view/Spark/Utilities/Grid/GridRowViewModelBase.cs index a42e16776..357a26fa9 100644 --- a/src/client/spark/view/Spark/Utilities/Grid/GridRowViewModelBase.cs +++ b/src/client/spark/view/Spark/Utilities/Grid/GridRowViewModelBase.cs @@ -1,4 +1,5 @@ -using mbts.collections; +using bts.collections; +using mbts.collections; using mbts.ui.controls; using mbts.ui.shell; using System; diff --git a/src/client/spark/view/Spark/Utilities/ISecurityMDPump.cs b/src/client/spark/view/Spark/Utilities/ISecurityMDPump.cs index 8648d226f..16c411790 100644 --- a/src/client/spark/view/Spark/Utilities/ISecurityMDPump.cs +++ b/src/client/spark/view/Spark/Utilities/ISecurityMDPump.cs @@ -1,6 +1,5 @@ using bts.api; using mbts.co2; -using mbts.collections.extensions; using System; using System.Collections.Generic; using System.Linq; diff --git a/src/client/spark/view/Spark/Utilities/SecurityDataHelper.cs b/src/client/spark/view/Spark/Utilities/SecurityDataHelper.cs index 6b7e465c7..0936380a0 100644 --- a/src/client/spark/view/Spark/Utilities/SecurityDataHelper.cs +++ b/src/client/spark/view/Spark/Utilities/SecurityDataHelper.cs @@ -2,7 +2,15 @@ using System.Collections.Generic; namespace mbts.spark { - static class SecurityDataHelper { + static class SecurityDataHelper { + // Ice + public static string market_description(this SecurityImmutable security) => security.HasIce ? security.Ice.MarketDescription : string.Empty; + public static string product_name(this SecurityImmutable security) => security.HasIce ? security.Ice.ProductName : string.Empty; + public static string cleared_alias(this SecurityImmutable security) => security.HasIce ? security.Ice.ClearedAlias : string.Empty; + public static string hub_alias(this SecurityImmutable security) => security.HasIce ? security.Ice.HubAlias : string.Empty; + public static string strip_name(this SecurityImmutable security) => security.HasIce ? security.Ice.StripName : string.Empty; + public static string mic_code(this SecurityImmutable security) => security.HasIce ? security.Ice.MicCode : string.Empty; + public static class EqualityComparer { public static readonly IEqualityComparer MDComparer = bts.utils.EqualityComparer.Create(Equals, GetHashCode); public static bool Equals(SecurityMD x, SecurityMD y) => x.security.Id == y.security.Id; diff --git a/src/client/spark/view/Spark/Utilities/WindowSettingsDialogVM.cs b/src/client/spark/view/Spark/Utilities/WindowSettingsDialogVM.cs index d8c45d21f..4340f2724 100644 --- a/src/client/spark/view/Spark/Utilities/WindowSettingsDialogVM.cs +++ b/src/client/spark/view/Spark/Utilities/WindowSettingsDialogVM.cs @@ -17,7 +17,7 @@ namespace mbts.spark { readonly DelegateProperty> _left_skirt_items; readonly List _resources = new List(2); // initialize with 2 capacity bc the only potential disposables are the instance/default vms - public WindowSettingsDialogVM(IWindowSettingsManager settings_manager, Func get_factory_settings, string settings_file_ext, Func vm_factory, Func merge_with_current = null) { + public WindowSettingsDialogVM(IWindowSettingsManager settings_manager, Func get_factory_settings, string settings_file_ext, Func vm_factory, Func merge_with_current = null, bool show_save_as_defaults = true) { if (merge_with_current == null) merge_with_current = s => s; // by default, each new window will use their own instance settings @@ -76,7 +76,8 @@ namespace mbts.spark { void close() => RequestClose?.Invoke(this, new EventArgs()); IEnumerable left_skirt_factory() { - yield return _apply_to_defaults_item; + if (show_save_as_defaults) + yield return _apply_to_defaults_item; }; } diff --git a/src/client/spark/view/Utility/CollectionViewSource.cs b/src/client/spark/view/Utility/CollectionViewSource.cs index 8df671001..ad36ee9de 100644 --- a/src/client/spark/view/Utility/CollectionViewSource.cs +++ b/src/client/spark/view/Utility/CollectionViewSource.cs @@ -1,17 +1,27 @@ -using System.ComponentModel; +using System; +using System.ComponentModel; using System.Windows.Data; -namespace mbts.ui.utility -{ - public class CollectionViewSource : CollectionViewSource where TView : class, ICollectionView - { +namespace mbts.ui.utility { + class CollectionViewSource : CollectionViewSource where TView : class, ICollectionView { + public CollectionViewSource() : base() { + using (_init()) + CollectionViewType = typeof(TView); + } + public CollectionViewSource(object source) { - ((ISupportInitialize)this).BeginInit(); - Source = source; - CollectionViewType = typeof(TView); - ((ISupportInitialize)this).EndInit(); + using (_init()) { + Source = source; + CollectionViewType = typeof(TView); + } } public new TView View => base.View as TView; + + IDisposable _init() { + var si = (ISupportInitialize)this; + si.BeginInit(); + return Disposable.Create(si.EndInit); + } } } \ No newline at end of file diff --git a/src/client/spark/view/Utility/CommandHelper.cs b/src/client/spark/view/Utility/CommandHelper.cs index 8e45c2c52..3a3a076a3 100644 --- a/src/client/spark/view/Utility/CommandHelper.cs +++ b/src/client/spark/view/Utility/CommandHelper.cs @@ -1,10 +1,17 @@ -using System.Windows; +using mbts.ui.converters; +using System.Globalization; +using System.Windows; +using System.Windows.Data; using System.Windows.Input; -namespace mbts.ui.utilities -{ - static class CommandHelper - { +namespace mbts.ui.utilities { + static class CommandHelper { + public static readonly IMultiValueConverter + DescriptionConverter = ValueConverter.create(fmt); + + public static string fmt(string title, KeyGesture key_gesture) => + key_gesture == null ? title : $"{title} ({key_gesture.GetDisplayStringForCulture(CultureInfo.CurrentCulture)})"; + #region Paraphrased from https://referencesource.microsoft.com/#PresentationFramework/src/Framework/MS/Internal/Commands/CommandHelpers.cs public static bool CanExecuteCommandSource(ICommandSource commandSource) { diff --git a/src/client/spark/view/Utility/CommandWithActionWrapper.cs b/src/client/spark/view/Utility/CommandWithActionWrapper.cs new file mode 100644 index 000000000..a8ef5e669 --- /dev/null +++ b/src/client/spark/view/Utility/CommandWithActionWrapper.cs @@ -0,0 +1,25 @@ +using mbts.ui.converters; +using System; +using System.Windows.Data; +using System.Windows.Input; + +namespace mbts.ui.utilities { + static class CommandWithActionWrapper { + public static IValueConverter mk_wrap_converter(Action action) => + ValueConverter.create(cmd => wrap(cmd, action)); + + public static ICommand wrap(ICommand command, Action action) { + var wrapped_cmd = new DelegateCommand(execute, command.CanExecute); + command.CanExecuteChanged += on_can_execute_changed; + return wrapped_cmd; + + void execute(object parameter) { + command.Execute(parameter); + action(); + } + + void on_can_execute_changed(object sender, EventArgs e) => + wrapped_cmd.RaiseCanExecuteChanged(); + } + } +} diff --git a/src/client/spark/view/Utility/DisplayNameHelper.cs b/src/client/spark/view/Utility/DisplayNameHelper.cs index fdcbaf35d..d86a70310 100644 --- a/src/client/spark/view/Utility/DisplayNameHelper.cs +++ b/src/client/spark/view/Utility/DisplayNameHelper.cs @@ -1,9 +1,11 @@ -using bts.utils; +using bts.collections; +using bts.utils; using mbts.ui.converters; using System; using System.Collections.Generic; using System.Globalization; using System.Linq; +using System.Text; using System.Text.RegularExpressions; using System.Windows.Data; @@ -37,7 +39,7 @@ namespace mbts.ui.utilities { public static string snake_to_title_case(string name) { if (name != null) { - var m = Regex.Match(name, @"[A-Za-z1-9_\-]*"); + var m = Regex.Match(name, @"[A-Za-z1-9_\-\s\(\)]*"); if (m.Success) { name = Regex.Replace(m.Value, @"(_|-)*(.*)", "$+"); name = name.Replace('_', ' '); @@ -73,7 +75,39 @@ namespace mbts.ui.utilities { return bpos == b.Length ? 0 : -1; } - public static Dictionary get_logical_abbreviations(IEnumerable names) { + public static Dictionary get_word_tree_abbreviations(IEnumerable names) => + get_word_tree_abbreviations(names, n => n, EqualityComparer.Default); + + public static Dictionary get_word_tree_abbreviations(IEnumerable keys, Func fmt) => + get_word_tree_abbreviations(keys, fmt, EqualityComparer.Default); + + public static Dictionary get_word_tree_abbreviations(IEnumerable keys, Func fmt, IEqualityComparer key_comparer) { + var rv = new Dictionary(key_comparer); + var abbrevs = new List<(T key, Abbrev abb)>(keys.Select(n => (n, new Abbrev(fmt(n))))); + int char_count = 1; + while (abbrevs.Count > 0) { + int i = 0; + do { + string candidate; + if (char_count == abbrevs[i].abb.full_name.Length) { + candidate = abbrevs[i].abb.full_name; + } else { + candidate = abbrevs[i].abb.abbreviate_str(char_count); + //var matches = abbrevs.Select(a => a.abb.abbreviate_str(char_count)) + if (abbrevs.ExceptAt(i).Any(a => candidate == a.abb.abbreviate_str(char_count))) { + i++; + continue; + } + } + rv.Add(abbrevs[i].key, candidate); + abbrevs.RemoveAt(i); + } while (i < abbrevs.Count); + char_count++; + } + return rv; + } + + static Dictionary get_logical_abbreviations(IEnumerable names) { var rv = new Dictionary(); var name_list = names.Where(n => !string.IsNullOrEmpty(n)).ToList(); switch (name_list.Count) { @@ -156,5 +190,90 @@ namespace mbts.ui.utilities { result = 0; return false; } + + struct Abbrev { + public readonly string full_name; + + public Abbrev(string full_name) { + this.full_name = full_name; + } + + public IEnumerable words { + get { + using (var en = full_name.GetEnumerator()) { + if (en.MoveNext()) { + char prev = en.Current; + prev = char.ToUpper(prev); + var word = new StringBuilder(); + word.Append(prev); + while (en.MoveNext()) { + if (!char.IsUpper(en.Current)) { + word.Append(en.Current); + } else { + if (char.IsUpper(prev)) { + word.Append(en.Current); + } else { + yield return word.ToString(); + word.Clear(); + word.Append(en.Current); + } + } + prev = en.Current; + } + string end = word.ToString(); + if (string.IsNullOrEmpty(end)) { + bts.Log.assert(false, "Empty End"); + } + yield return end; + } + } + } + } + + public string abbreviate_str(int count) { + char[] res = new char[count]; + int pos = 0; + var abb = abbreviate(count); + foreach (char c in abb) + res[pos++] = c; + return new string(res); + } + + public IEnumerable abbreviate(int count) { + if (count >= full_name.Length) { + foreach (char c in full_name) + yield return c; + yield break; + } + var word_list = this.words.ToList(); + if (count < word_list.Count) { + for (int i = 0; i < count; i++) { + yield return word_list[i][0]; + } + yield break; + } + var chars_per_word = new int[word_list.Count]; + int res_count = 0; + while (res_count < count) { + // use progress marker as safe guard against the dreaded infinite loop + int progress_marker = res_count; + for (int w = 0; w < word_list.Count; w++) { + if (word_list[w].Length > chars_per_word[w]) { + chars_per_word[w]++; + res_count++; + } + } + if (progress_marker == res_count) { + // no progress was made, let's bail! + break; + } + } + for (int w = 0; w < word_list.Count; w++) { + for (int c = 0; c < chars_per_word[w]; c++) { + yield return word_list[w][c]; + } + } + } + } } } \ No newline at end of file diff --git a/src/client/spark/view/Utility/EnumHelper.cs b/src/client/spark/view/Utility/EnumHelper.cs index b545c6395..b2043831b 100644 --- a/src/client/spark/view/Utility/EnumHelper.cs +++ b/src/client/spark/view/Utility/EnumHelper.cs @@ -5,6 +5,7 @@ using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Linq; +using System.Reactive.Linq; using System.Reflection; namespace mbts.ui.utility { @@ -41,6 +42,18 @@ namespace mbts.ui.utility { return Activator.CreateInstance(enum_type); } + public static T try_convert(object value) { + var numeric_type = Enum.GetUnderlyingType(typeof(T)); + var numeric_value = Convert.ChangeType(value, numeric_type); + return (T)Convert.ChangeType(numeric_value, typeof(T)); + } + + public static Func get_has_flags_delegate(Type enum_type) => + EnumDescriptorStore.descriptor(enum_type).has_flags; + + public static bool has_flags(TEnum value, TEnum flags) => + EnumDescriptorStore.descriptor.has_flags(value, flags); + public static string get_display_name(object enum_obj, TextCapitalizationFormat capitalization_format = TextCapitalizationFormat.Default) { string str = enum_obj.ToString(); MemberInfo[] mi = enum_obj.GetType().GetMember(str); @@ -58,13 +71,6 @@ namespace mbts.ui.utility { return mi.Length > 0 ? mi[0].GetCustomAttribute() : null; } - public static bool includes_flag(TEnum flags, TEnum value) { - if (!typeof(TEnum).IsEnum) throw new InvalidOperationException("Type is not an Enum."); - long lflags = Convert.ToInt64(flags); - long lvalue = Convert.ToInt64(value); - return (lflags & lvalue) == lvalue; - } - // though it isn't hard to write "flags & TEnum.Foo != 0," split_flags offers a less error-prone alternative in terms of typeos. // (less likely that code calling this method will have a typeo, than code checking flags in the traditional manner described above) public static IEnumerable split_flags(TEnum flags) where TEnum : struct { @@ -75,5 +81,196 @@ namespace mbts.ui.utility { yield return e; } } + + public static IObservable observe_result(this EnumMaskInt32 mask) where T : struct => + Observable.Create(o => { + mask.result_changed += notify; + o.OnNext(mask.result); + return Disposable.Create(() => mask.result_changed -= notify); + void notify(int result) => + o.OnNext(mask.result); + }); + + struct EnumDescriptor { + public readonly Func has_flags; + + public EnumDescriptor(Func has_flags) => + this.has_flags = has_flags; + } + + static class EnumDescriptorStore { + [ThreadStatic] + static Dictionary _type_index_backing; + + static Dictionary _type_index => + _type_index_backing ?? (_type_index_backing = new Dictionary()); + + public static EnumDescriptor descriptor(Type enum_type) => + _type_index.GetOrAdd(enum_type, t => (EnumDescriptor) + typeof(EnumDescriptorStore<>).MakeGenericType(enum_type) + .GetField(nameof(EnumDescriptorStore.descriptor), BindingFlags.Static | BindingFlags.Public) + .GetValue(null)); + } + + static class EnumDescriptorStore { + public static readonly EnumDescriptor descriptor; + + static EnumDescriptorStore() { + Func has_flags; + if (!typeof(T).IsEnum) { + // N/A + has_flags = Impl.as_none_has_flags; + } + var numeric_type = Enum.GetUnderlyingType(typeof(T)); + if (numeric_type == typeof(byte)) { + // byte + has_flags = Impl.as_byte_has_flags; + } else if (numeric_type == typeof(short)) { + // short + has_flags = Impl.as_int16_has_flags; + } else if (numeric_type == typeof(int)) { + // int + has_flags = Impl.as_int32_has_flags; + } else if (numeric_type == typeof(long)) { + // long + has_flags = Impl.as_int64_has_flags; + } else if (numeric_type == typeof(ushort)) { + // ushort + has_flags = Impl.as_uint16_has_flags; + } else if (numeric_type == typeof(uint)) { + // uint + has_flags = Impl.as_uint32_has_flags; + } else if (numeric_type == typeof(ulong)) { + // ulong + has_flags = Impl.as_uint64_has_flags; + } else { + // ? + has_flags = Impl.as_none_has_flags; + } + descriptor = new EnumDescriptor(has_flags); + } + + static class Impl { + public static bool as_none_has_flags(object value, object flags) => false; + // byte + public static bool as_byte_has_flags(object value, object flags) { + byte value_as_byte = (byte)Convert.ChangeType(value, typeof(byte)); + byte flags_as_byte = (byte)Convert.ChangeType(flags, typeof(byte)); + return (value_as_byte & flags_as_byte) == flags_as_byte; + } + // short + public static bool as_int16_has_flags(object value, object flags) { + short value_as_short = (short)Convert.ChangeType(value, typeof(short)); + short flags_as_short = (short)Convert.ChangeType(flags, typeof(short)); + return (value_as_short & flags_as_short) == flags_as_short; + } + // int + public static bool as_int32_has_flags(object value, object flags) { + int value_as_byte = (int)Convert.ChangeType(value, typeof(int)); + int flags_as_byte = (int)Convert.ChangeType(flags, typeof(int)); + return (value_as_byte & flags_as_byte) == flags_as_byte; + } + // long + public static bool as_int64_has_flags(object value, object flags) { + long value_as_long = (long)Convert.ChangeType(value, typeof(long)); + long flags_as_long = (long)Convert.ChangeType(flags, typeof(long)); + return (value_as_long & flags_as_long) == flags_as_long; + } + // ushort + public static bool as_uint16_has_flags(object value, object flags) { + ushort value_as_ushort = (ushort)Convert.ChangeType(value, typeof(ushort)); + ushort flags_as_ushort = (ushort)Convert.ChangeType(flags, typeof(ushort)); + return (value_as_ushort & flags_as_ushort) == flags_as_ushort; + } + // uint + public static bool as_uint32_has_flags(object value, object flags) { + uint value_as_uint = (uint)Convert.ChangeType(value, typeof(uint)); + uint flags_as_uint = (uint)Convert.ChangeType(flags, typeof(uint)); + return (value_as_uint & flags_as_uint) == flags_as_uint; + } + // ulong + public static bool as_uint64_has_flags(object value, object flags) { + ulong value_as_ulong = (ulong)Convert.ChangeType(value, typeof(ulong)); + ulong flags_as_ulong = (ulong)Convert.ChangeType(flags, typeof(ulong)); + return (value_as_ulong & flags_as_ulong) == flags_as_ulong; + } + } + } + } + + interface IMaskIndexInt32 { + T from_int(int i); + int to_int(T value); + } + + class MaskIndexInt32 : IMaskIndexInt32 { + public readonly IReadOnlyDictionary lookup; + public readonly IReadOnlyDictionary reverse_lookup; + + public MaskIndexInt32(IReadOnlyList items) { + const int maskable_bits = 31; + if (items.Count > maskable_bits) + throw new ArgumentException($"Number of elements exceeds the number of maskable bits for {typeof(int)} ({maskable_bits})."); + lookup = items.Select((v, i) => (v, i)).ToDictionary(t => 1 << t.i, t => t.v); + reverse_lookup = lookup.ToDictionary(kv => kv.Value, kv => kv.Key); + } + + public T from_int(int i) => + lookup.TryGetValue(i, out T value) ? value : default; + + public int to_int(T value) => + reverse_lookup.TryGetValue(value, out int i) ? i : 0; + } + + static class EnumMaskIndexInt32 { + static readonly MaskIndexInt32 _instance = new MaskIndexInt32(EnumHelper.get_values().ToList()); + + public static T from_int(int i) => + _instance.lookup.TryGetValue(i, out T value) ? value : default; + + public static int to_int(T value) => + _instance.reverse_lookup[value]; + } + + class MaskInt32 { + int _mask = int.MaxValue, _raw; + + public event Action result_changed; + + public int mask { + get => _mask; + set { + using (_update()) + _mask = value; + } + } + public int raw { + get => _raw; + set { + using (_update()) + _raw = value; + } + } + public int result => _raw & _mask; + + IDisposable _update() { + int old_result = result; + return Disposable.Create(() => { + if (result != old_result) + result_changed?.Invoke(result); + }); + } + } + + sealed class EnumMaskInt32 : MaskInt32 where T : struct { + public new T mask { + get => (T)(object)base.mask; + set => base.mask = (int)(object)value; + } + public new T raw { + get => (T)(object)base.raw; + set => base.raw = (int)(object)value; + } + public new T result => (T)(object)base.result; } } \ No newline at end of file diff --git a/src/client/spark/view/Utility/ICollectionView.cs b/src/client/spark/view/Utility/ICollectionView.cs index b1f0d8ef5..e9025555a 100644 --- a/src/client/spark/view/Utility/ICollectionView.cs +++ b/src/client/spark/view/Utility/ICollectionView.cs @@ -30,6 +30,8 @@ namespace mbts.ui.utility { } } + public ICollectionView AsCollectionView() => this; + IEnumerator IEnumerable.GetEnumerator() { var en = base.GetEnumerator(); while (en.MoveNext()) diff --git a/src/client/spark/view/Utility/KeyedStyleSelector.cs b/src/client/spark/view/Utility/KeyedStyleSelector.cs index fdfb1a8c6..be8fe33d5 100644 --- a/src/client/spark/view/Utility/KeyedStyleSelector.cs +++ b/src/client/spark/view/Utility/KeyedStyleSelector.cs @@ -1,7 +1,6 @@ -using System; +using bts.collections; +using System; using System.Collections; -using System.Collections.Generic; -using System.Collections.ObjectModel; using System.Windows; using System.Windows.Controls; using System.Windows.Markup; @@ -13,13 +12,13 @@ namespace mbts.ui { [ContentProperty(nameof(Map))] class KeyedStyleSelectorBase : StyleSelector { - NamedStyleCollection _c = new NamedStyleCollection(); + KeyedCollection, TKey> _c = new KeyedCollection, TKey>(kv => kv.Key); public IList Map => _c; public Style Default { get; set; } public override Style SelectStyle(object item, DependencyObject container) { - if (_try_get_item_key(item, out TKey k) && _c.TryGetItem(k, out StyleSelectorKeyValueBase result)) + if (_try_get_item_key(item, out TKey k) && _c.TryGetValue(k, out StyleSelectorKeyValueBase result)) return result.Value; else return Default; } @@ -32,10 +31,6 @@ namespace mbts.ui { result = default; return false; } - - class NamedStyleCollection : KeyedCollection> { - protected override TKey GetKeyForItem(StyleSelectorKeyValueBase item) => item.Key; - } } [ContentProperty(nameof(Value))] diff --git a/src/client/spark/view/Utility/KeyedTemplateSelector.cs b/src/client/spark/view/Utility/KeyedTemplateSelector.cs index 074007c57..fad5918bd 100644 --- a/src/client/spark/view/Utility/KeyedTemplateSelector.cs +++ b/src/client/spark/view/Utility/KeyedTemplateSelector.cs @@ -1,6 +1,5 @@ -using System.Collections; -using System.Collections.Generic; -using System.Collections.ObjectModel; +using bts.collections; +using System.Collections; using System.Windows; using System.Windows.Controls; using System.Windows.Markup; @@ -12,20 +11,16 @@ namespace mbts.ui { [ContentProperty(nameof(Map))] class KeyedTemplateSelector : DataTemplateSelector { - NamedTemplateCollection _c = new NamedTemplateCollection(); + KeyedCollection _c = new KeyedCollection(kv => kv.Key); public IList Map => _c; public DataTemplate Default { get; set; } public override DataTemplate SelectTemplate(object item, DependencyObject container) { - if (item is ITemplateSelectorKey k && k.key != null && _c.TryGetItem(k.key, out TemplateSelectorKeyValue result)) + if (item is ITemplateSelectorKey k && k.key != null && _c.TryGetValue(k.key, out TemplateSelectorKeyValue result)) return result.Value; else return Default; } - - class NamedTemplateCollection : KeyedCollection { - protected override string GetKeyForItem(TemplateSelectorKeyValue item) => item.Key; - } } [ContentProperty(nameof(Value))] diff --git a/src/client/spark/view/Utility/LazyPropagator.cs b/src/client/spark/view/Utility/LazyPropagator.cs new file mode 100644 index 000000000..f66686f98 --- /dev/null +++ b/src/client/spark/view/Utility/LazyPropagator.cs @@ -0,0 +1,47 @@ +using System; +using System.Collections.Generic; + +namespace mbts.ui.utilities { + class LazyPropagator { + readonly Action _assign; + readonly IEqualityComparer _comparer; + readonly IEqualityComparer _target_comparer; + Value _value; + Target _target; + + public LazyPropagator(Action assign) + : this(assign, default) { } + + public LazyPropagator(Action assign, Value init) + : this(assign, init, EqualityComparer.Default, EqualityComparer.Default) { } + + public LazyPropagator(Action assign, Value init, IEqualityComparer comparer, IEqualityComparer target_comparer) { + _assign = assign; + _value = init; + _comparer = comparer; + _target_comparer = target_comparer; + } + + public Target target { + get => _target; + set { + if (!_target_comparer.Equals(_target, value)) { + _target = value; + if (value != null) + _assign(value, _value); + } + } + } + + public Value value { + get => _value; + set { + if (!_comparer.Equals(value, _value)) { + _value = value; + if (_target != null) + _assign(_target, value); + } + } + } + } +} \ No newline at end of file diff --git a/src/client/spark/view/Utility/NavigationHelper.cs b/src/client/spark/view/Utility/NavigationHelper.cs new file mode 100644 index 000000000..e201502e7 --- /dev/null +++ b/src/client/spark/view/Utility/NavigationHelper.cs @@ -0,0 +1,56 @@ +using mbts.ui.extensions; +using System; +using System.Windows; +using System.Windows.Input; + +namespace mbts.ui { + static class NavigationHelper { + public static readonly RoutedCommand MoveFocusCommand = new RoutedCommand(); + public static readonly ExecutedRoutedEventHandler + KeyboardMoveFocusExecuted = (s, e) => { + if (e.Parameter is FocusNavigationDirection d) + (Keyboard.FocusedElement as UIElement)?.MoveFocus(new TraversalRequest(d)); + }; + + public static FocusNavigationDirection? get_direction_for_key(Key key) { + switch (key) { + case Key.Left: return FocusNavigationDirection.Left; + case Key.Up: return FocusNavigationDirection.Up; + case Key.Right: return FocusNavigationDirection.Right; + case Key.Down: return FocusNavigationDirection.Down; + case Key.Tab: return (Keyboard.Modifiers & ModifierKeys.Shift) != 0 ? FocusNavigationDirection.Previous : FocusNavigationDirection.Next; + default: return null; + } + } + + public static bool keyboard_move_focus(FocusNavigationDirection direction) => + (Keyboard.FocusedElement as UIElement)?.MoveFocus(new TraversalRequest(direction)) ?? false; + + public static IDisposable connect_navigation(FrameworkElement element, FrameworkElement left, FrameworkElement up, FrameworkElement right, FrameworkElement down, ModifierKeys? modifier_keys = null) => + connect_navigation(element, () => left, () => up, () => right, () => down, modifier_keys); + + public static IDisposable connect_navigation(FrameworkElement element, Func left, Func up, Func right, Func down, ModifierKeys? modifier_keys = null) => + connect_navigation(element, _ => element, _ => left(), _ => up(), _ => right(), _ => down(), modifier_keys); + + public static IDisposable connect_navigation( + FrameworkElement element, + Func get_source, + Func left, + Func up, + Func right, + Func down, + ModifierKeys? modifier_keys = null) => + element.SubscribePreviewKeyDown((s, e) => { + if (modifier_keys.HasValue && Keyboard.Modifiers != modifier_keys.Value) + return; + switch (e.Key) { + case Key.Left: move_focus(left(get_source(e))); break; + case Key.Up: move_focus(up(get_source(e))); break; + case Key.Right: move_focus(right(get_source(e))); break; + case Key.Down: move_focus(down(get_source(e))); break; + } + void move_focus(FrameworkElement target) => + e.Handled = target?.Focus() ?? false; + }); + } +} \ No newline at end of file diff --git a/src/client/spark/view/Utility/PropertyUpdateGate.cs b/src/client/spark/view/Utility/PropertyUpdateGate.cs index 100267764..318c68493 100644 --- a/src/client/spark/view/Utility/PropertyUpdateGate.cs +++ b/src/client/spark/view/Utility/PropertyUpdateGate.cs @@ -2,12 +2,15 @@ namespace mbts.ui.utility { class PropertyUpdateGate { + readonly string _reentrancy_error_msg; + + public PropertyUpdateGate(string reentrancy_error_msg = "Already updating property.") => + _reentrancy_error_msg = reentrancy_error_msg; + public bool is_updating { get; private set; } - public IDisposable update() { - if (is_updating) throw new InvalidOperationException("Already updating property."); - return _update(); - } + public IDisposable update() => + is_updating ? throw new InvalidOperationException(_reentrancy_error_msg) : _update(); public bool try_update(Action update) { if (!is_updating) { diff --git a/src/client/spark/view/Utility/RXCollection.cs b/src/client/spark/view/Utility/RXCollection.cs index 45b597fcb..f5d8f76b1 100644 --- a/src/client/spark/view/Utility/RXCollection.cs +++ b/src/client/spark/view/Utility/RXCollection.cs @@ -1,8 +1,7 @@ -using bts.api.core; -using bts.collections; -using bts.utils; +using bts.collections; using mbts.utils; using System; +using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Collections.Specialized; @@ -10,10 +9,6 @@ using System.Linq; using System.Reactive.Linq; namespace mbts.ui.utility { - interface IReadOnlyObservableCollection : IReadOnlyList, IReadOnlyCollection, INotifyCollectionChanged { } - - interface IObservableCollection : IList, INotifyCollectionChanged { } - interface IRXCollection : IList, IObservableCollection, INotifyCollectionChanged, IDisposable { } interface ITableUpdateCollection : IRXCollection where TKey : IEquatable { @@ -108,69 +103,24 @@ namespace mbts.ui.utility { public void Dispose() => Disposable.dispose(ref _sub); } - } - class RXOperableCollection : ObservableCollection where TKey : IEquatable { - readonly Func _factory; - readonly Func _key; - readonly IEqualityComparer _eq_comparer; - IReadOnlyDictionary _map = DictionaryHelper.empty(); + public static class ReadOnly { + public static IReadOnlyObservableCollection Empty() => Impl.instance; - SortedList _sorted_items; - Func _filter; - IComparer _comparer; - - public RXOperableCollection(Func factory, Func key, IComparer comparer) { - _factory = factory; - _key = key; - _eq_comparer = EqualityComparer.Create(key); - _sorted_items = new SortedList(comparer ?? throw new ArgumentNullException(nameof(comparer))); - } - - public IComparer comparer { get => _comparer; set => _set_comparer(value); } - public Func filter { get => _filter; set => _set_filter(value); } - - public void reset(IComparer comparer, Func filter) { - _filter = filter; - _comparer = comparer; - _reset(new SortedList(filter == null ? _map.Values : _map.Values.Where(filter), comparer)); - } - - public void update(TableUpdate table) { - _map = table.state; - IEnumerable added, removed; - if (filter == null) { - added = table.added.Concat(table.changed); - removed = table.removed.Concat(table.changes.Select(ch => ch.Old)); - } else { - added = table.added.Where(filter).Concat(table.changed.Where(filter)); - removed = table.removed.Where(filter).Concat(table.changes.Select(ch => ch.Old).Where(filter)); + class Impl : IReadOnlyObservableCollection { + public static readonly IReadOnlyObservableCollection instance = new Impl(); + public T this[int index] => throw new IndexOutOfRangeException(); + public int Count => 0; + public event NotifyCollectionChangedEventHandler CollectionChanged; + public IEnumerator GetEnumerator() { yield break; } + IEnumerator IEnumerable.GetEnumerator() { yield break; } + void _raise_collection_changed() { + if (CollectionChanged == null) { + // shutup compiler + } + } + //CollectionChanged?.Invoke(this, new NotifyCollectionChangedEventArgs()); } - foreach (var v in removed) { - _sorted_items.Remove(v, out int? old_pos); - // don't bother checking 'old_pos.HasValue' - removes should always be successful (if not, an exception should be thrown anyways bc the situation is untenable). - RemoveAt(old_pos.Value); - } - foreach (var v in added) { - _sorted_items.Add(v, out int new_pos); - Insert(new_pos, _factory(v, _key(v))); - } - } - - void _set_comparer(IComparer new_comp) { - _comparer = new_comp ?? throw new ArgumentNullException(nameof(new_comp)); - _reset(new SortedList(_sorted_items, new_comp)); - } - - void _set_filter(Func filter) { - _filter = filter; - _reset(new SortedList(filter == null ? _map.Values : _map.Values.Where(filter), comparer)); - } - - void _reset(SortedList new_sorted_items) { - var changes = Diff.diff(_sorted_items, new_sorted_items, _eq_comparer).ToList(); - _sorted_items = new_sorted_items; - Diff.apply_diff(this, _sorted_items, changes, m => _factory(m, _key(m))); } } } \ No newline at end of file diff --git a/src/client/spark/view/Utility/RadioButtonGroupManager.cs b/src/client/spark/view/Utility/RadioButtonGroupManager.cs index 267e5144c..626b1d066 100644 --- a/src/client/spark/view/Utility/RadioButtonGroupManager.cs +++ b/src/client/spark/view/Utility/RadioButtonGroupManager.cs @@ -1,4 +1,12 @@ -using System.Collections.Generic; +using bts; +using mbts.ui.extensions; +using mbts.ui.utility; +using mbts.utils; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Reactive.Disposables; +using System.Reactive.Linq; using System.Windows; using System.Windows.Controls; using System.Windows.Controls.Primitives; @@ -11,11 +19,9 @@ namespace mbts.ui.controls { public static readonly DependencyProperty GroupManagerMapProperty = DependencyProperty.Register("GroupManagerMap", typeof(RadioButtonGroupManagerMap), typeof(RadioButtonGroupManagerMap), new PropertyMetadata((d, e) => { - if (d is RadioButton tb) { - var k = GetGroupKey(tb); - if (e.OldValue is RadioButtonGroupManagerMap old_man) old_man._leave(tb, k); - if (e.NewValue is RadioButtonGroupManagerMap new_man) new_man._join(tb, k); - } + var k = GetGroupKey(d); + if (e.OldValue is RadioButtonGroupManagerMap old_man) old_man._leave(d, k); + if (e.NewValue is RadioButtonGroupManagerMap new_man) new_man._join(RadioButtonGroupManager.mk_member(d), k); })); public static RadioButtonGroupManagerMap GetGroupManagerMap(DependencyObject d) => d.GetValue(GroupManagerMapProperty) as RadioButtonGroupManagerMap; @@ -29,9 +35,9 @@ namespace mbts.ui.controls { new PropertyMetadata((d, e) => { var man_map = GetGroupManagerMap(d); if (man_map != null) { - var tb = (ToggleButton)d; - man_map._leave(tb, e.OldValue); - man_map._join(tb, e.NewValue); + var m = RadioButtonGroupManager.mk_member(d); + man_map._leave(m, e.OldValue); + man_map._join(m, e.NewValue); } })); @@ -42,18 +48,21 @@ namespace mbts.ui.controls { public bool TryGetManager(object group_key, out RadioButtonGroupManager result) => _managers.TryGetValue(group_key, out result); - public void join(ToggleButton tb, object group_key) => - _join(tb, group_key); + public void join(RadioButtonGroupManager.Member member, object group_key) => + _join(member, group_key); - void _join(ToggleButton tb, object group_key) { + void _join(RadioButtonGroupManager.Member member, object group_key) { if (group_key == null) return; - _managers.GetOrAdd(group_key, _ => new RadioButtonGroupManager()).join(tb); + _managers.GetOrAdd(group_key, _ => new RadioButtonGroupManager()).join(member); } - void _leave(ToggleButton tb, object group_key) { + void _leave(DependencyObject d, object group_key) => _leave(group_key, man => man.leave(d)); + void _leave(RadioButtonGroupManager.Member member, object group_key) => _leave(group_key, man => man.leave(member)); + + void _leave(object group_key, Action leave) { if (group_key == null) return; if (_managers.TryGetValue(group_key, out RadioButtonGroupManager man)) { - man.leave(tb); + leave(man); if (man.is_empty) _managers.Remove(group_key); } @@ -65,10 +74,8 @@ namespace mbts.ui.controls { public static readonly DependencyProperty ManagerProperty = DependencyProperty.RegisterAttached("Manager", typeof(RadioButtonGroupManager), typeof(RadioButtonGroupManager), new PropertyMetadata((d, e) => { - if (d is ToggleButton tb) { - if (e.OldValue is RadioButtonGroupManager old_man) old_man.leave(tb); - if (e.NewValue is RadioButtonGroupManager new_man) new_man.join(tb); - } + if (e.OldValue is RadioButtonGroupManager old_man) old_man.leave(d); + if (e.NewValue is RadioButtonGroupManager new_man) new_man.join(mk_member(d)); })); public static RadioButtonGroupManager GetManager(DependencyObject d) => d.GetValue(ManagerProperty) as RadioButtonGroupManager; @@ -90,16 +97,27 @@ namespace mbts.ui.controls { public static void RemoveValueChangedHandler(DependencyObject d, RoutedEventHandler handler) => (d as UIElement)?.RemoveHandler(ValueChangedEvent, handler); #endregion - readonly List _members = new List(); + readonly ObservableCollection _members = new ObservableCollection(); + + public RadioButtonGroupManager() { + ObservableAutoWrapper.connect_item_hooks(_members, m => { + m.el.DataContextChanged += _member_DataContextChanged; + return new CompositeDisposable( + m.subscribe().Subscribe(is_checked => { + if (is_checked) + _member_Checked(m, new RoutedEventArgs()); + })) { + () => m.el.DataContextChanged -= _member_DataContextChanged + }; + }); + } public static readonly DependencyProperty SelectedItemProperty = DependencyProperty.Register(nameof(SelectedItem), typeof(object), typeof(RadioButtonGroupManager), new PropertyMetadata((d, e) => { var group = (RadioButtonGroupManager)d; - foreach (var tb in group._members) { - tb.Checked -= group._member_Checked; - var val = group._get_member_value(tb); - tb.set_current_if_changed(ToggleButton.IsCheckedProperty, Equals(e.NewValue, val)); - tb.Checked += group._member_Checked; + foreach (var m in group._members) { + var val = group._get_member_value(m); + m.IsChecked = Equals(e.NewValue, val); } })); @@ -107,56 +125,89 @@ namespace mbts.ui.controls { public bool is_empty => _members.Count == 0; - public void join(ToggleButton tb) { - if (!_members.Contains(tb)) { - _members.Add(tb); - tb.SetCurrentValue(ToggleButton.IsCheckedProperty, Equals(SelectedItem, _get_member_value(tb))); - tb.Checked += _member_Checked; - tb.DataContextChanged += _member_DataContextChanged; - AddValueChangedHandler(tb, _on_value_changed); + public static Member mk_member(DependencyObject element) { + return OneOf.infer(element, toggle_button, menu_item); + // toggle button + Member toggle_button(ToggleButton tb) => + new Member(tb, ToggleButton.IsCheckedProperty, tb.ObserveIsChecked); + // menu item + Member menu_item(MenuItem mi) => + new Member(mi, MenuItem.IsCheckedProperty, mi.ObserveIsChecked); + } + + public void join(Member m) { + if (m == null) + return; + if (!_members.Contains(m)) { + _members.Add(m); + m.IsChecked = Equals(SelectedItem, _get_member_value(m)); + AddValueChangedHandler(m.el, _on_value_changed); } } void _on_value_changed(object sender, RoutedEventArgs e) => - _update_member_value((ToggleButton)sender); + _update_member_value((Member)sender); - public void leave(ToggleButton tb) { - if (_members.Remove(tb)) { - tb.Checked -= _member_Checked; - tb.DataContextChanged -= _member_DataContextChanged; - RemoveValueChangedHandler(tb, _on_value_changed); - if (Equals(SelectedItem, tb.DataContext)) + public void leave(DependencyObject d) => + leave(_members.FirstOrDefault(m => m.el == d)); + + public void leave(Member m) { + if (m == null) + return; + if (_members.Remove(m)) { + RemoveValueChangedHandler(m.el, _on_value_changed); + if (Equals(SelectedItem, m.el.DataContext)) SetCurrentValue(SelectedItemProperty, null); } } + static bool _is_checked((FrameworkElement el, DependencyProperty dp) member) => + member.el.GetValue(member.dp) is bool b && b; + void _member_Checked(object sender, RoutedEventArgs e) { - var tb = (ToggleButton)sender; - if (tb.IsChecked ?? false) - SetCurrentValue(SelectedItemProperty, _get_member_value(tb)); + var m = (Member)sender; + if (m.IsChecked) + SetCurrentValue(SelectedItemProperty, _get_member_value(m)); } void _member_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e) => - _update_member_value((ToggleButton)sender); + _update_member_value((Member)sender); - void _update_member_value(ToggleButton tb) { - var val = RadioButtonGroupManager.GetValue(tb); + void _update_member_value(Member m) { + var val = GetValue(m.el); if (!_is_value_valid(val)) { - val = tb.DataContext; + val = m.el.DataContext; if (!_is_value_valid(val)) return; } - if (tb.IsChecked ?? false) + if (m.IsChecked) SetCurrentValue(SelectedItemProperty, val); } - object _get_member_value(ToggleButton tb) { - var val = RadioButtonGroupManager.GetValue(tb); + object _get_member_value(Member m) { + var val = GetValue(m.el); if (!_is_value_valid(val)) - val = tb.DataContext; + val = m.el.DataContext; return _is_value_valid(val) ? val : null; } bool _is_value_valid(object value) => value != null && !value.Equals(DependencyProperty.UnsetValue); + + public class Member { + public readonly FrameworkElement el; + public readonly DependencyProperty dp; + public readonly Func> subscribe; + + public Member(FrameworkElement el, DependencyProperty dp, Func> subscribe) { + this.el = el; + this.dp = dp; + this.subscribe = subscribe; + } + + public bool IsChecked { + get => el.GetValue(dp) is bool b && b; + set => el.SetCurrentValue(dp, value); + } + } } -} \ No newline at end of file +} diff --git a/src/client/spark/view/Utility/StateManager.cs b/src/client/spark/view/Utility/StateManager.cs index 9659a3a24..ddcd63094 100644 --- a/src/client/spark/view/Utility/StateManager.cs +++ b/src/client/spark/view/Utility/StateManager.cs @@ -1,14 +1,280 @@ -using System; -using System.Collections.Generic; +using bts; +using bts.utils; +using mbts.ui.extensions; +using mbts.ui.shell; +using mbts.ui.utility; +using System; using System.Collections.ObjectModel; using System.Collections.Specialized; -using System.Linq; +using System.Reactive.Disposables; +using System.Reactive.Linq; using System.Text; -using System.Threading.Tasks; using System.Windows; +using System.Windows.Controls; +using System.Windows.Controls.Primitives; +using System.Windows.Data; +using System.Windows.Input; +using System.Windows.Markup; + +namespace mbts.ui { + class StateDefinitionCollection : ObservableCollection { } + + [ContentProperty(nameof(State))] + class StateDefinition : DependencyObject { + public static readonly DependencyProperty StateProperty = + WPFHelper.create_dp(nameof(State), (o, oldval, newval) => o.StateChanged?.Invoke(oldval, newval)); + + public string State { get => GetValue(StateProperty) as string; set => SetValue(StateProperty, value); } + + public static readonly DependencyProperty GroupProperty = + WPFHelper.create_dp(nameof(Group)); + + public StateGroupsManager Group { + get => GetValue(GroupProperty) as StateGroupsManager; + set => SetValue(GroupProperty, value); + } + + public event PropertyChange StateChanged; + } + + class MouseStateDefinition : StateDefinition { + IDisposable _mouse_hook; + + static MouseStateDefinition() { + StateProperty.OverrideMetadata(typeof(MouseStateDefinition), StateProperty.DefaultMetadata.with(coerce_state)); + object coerce_state(DependencyObject d, object baseValue) { + var msd = (MouseStateDefinition)d; + return new StringBuilderEx( + msd.Mode?.ToString() ?? string.Empty, + msd.MouseSource?.IsMouseOver ?? false ? + (Mouse.LeftButton == MouseButtonState.Pressed ? msd.PressedState : msd.HoverState) : + msd.NormalState).ToString(); + } + } + + #region MouseSource + public static readonly DependencyProperty MouseSourceProperty = + WPFHelper.create_dp( + nameof(MouseSource), + (o, v) => o._on_mouse_source_changed(v)); + + public FrameworkElement MouseSource { + get => GetValue(MouseSourceProperty) as FrameworkElement; + set => SetValue(MouseSourceProperty, value); + } + #endregion + + #region Mode + public static readonly DependencyProperty ModeProperty = + WPFHelper.create_dp(nameof(Mode), new PropertyMetadata(null, OnModeChanged)); + + static void OnModeChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) => d.CoerceValue(StateProperty); + + public object Mode { + get => GetValue(ModeProperty); + set => SetValue(ModeProperty, value); + } + #endregion + + public string HoverState { get; set; } = "MouseOver"; + public string PressedState { get; set; } = "Pressed"; + public string NormalState { get; set; } = "Normal"; + + void _on_mouse_source_changed(FrameworkElement mouse_source) { + if (mouse_source == null) { + Disposable.dispose(ref _mouse_hook); + this.set_current_if_changed(StateProperty, NormalState); + } else { + Disposable.replace(ref _mouse_hook, + Disposable.Create( + mouse_source.SubscribeMouseEnter(on_mouse_event), + mouse_source.SubscribeMouseMove(on_mouse_event), + mouse_source.SubscribeMouseLeave(on_mouse_event), + mouse_source.SubscribePreviewMouseDown(on_mouse_button_event), + mouse_source.SubscribePreviewMouseUp(on_mouse_button_event))); + CoerceValue(StateProperty); + void on_mouse_event(object sender, MouseEventArgs e) => CoerceValue(StateProperty); + void on_mouse_button_event(object sender, MouseButtonEventArgs e) => CoerceValue(StateProperty); + } + } + } + + class CheckedStateDefinition : StateDefinition { + public static readonly Func FindMenuItemAncestor = + target => target?.find_ancestor_of_type(); + + IDisposable _checkable_source_hook; + bool _is_checked; + + static CheckedStateDefinition() { + StateProperty.OverrideMetadata(typeof(CheckedStateDefinition), StateProperty.DefaultMetadata.with(coerce_state)); + object coerce_state(DependencyObject d, object baseValue) { + var csd = (CheckedStateDefinition)d; + return new StringBuilderEx( + csd.Mode?.ToString() ?? string.Empty, + csd._is_checked ? csd.CheckedState : csd.UncheckedState).ToString(); + } + } + + #region Mode + public static readonly DependencyProperty ModeProperty = + WPFHelper.create_dp(nameof(Mode), new PropertyMetadata(null, OnModeChanged)); + + static void OnModeChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) => d.CoerceValue(StateProperty); + + public object Mode { + get => GetValue(ModeProperty); + set => SetValue(ModeProperty, value); + } + #endregion + + #region CheckableSource + public static readonly DependencyProperty CheckableSourceProperty = + WPFHelper.create_dp( + nameof(CheckableSource), + (o, v) => o._on_checkable_source_changed(v)); + + public FrameworkElement CheckableSource { + get => GetValue(CheckableSourceProperty) as FrameworkElement; + set => SetValue(CheckableSourceProperty, value); + } + #endregion + + public string CheckedState { get; set; } = "Checked"; + public string UncheckedState { get; set; } = "Unchecked"; + + void _on_checkable_source_changed(FrameworkElement checkable_source) { + Disposable.replace(ref _checkable_source_hook, + OneOf.infer, ToggleButton, MenuItem>( + checkable_source, subscribe_toggle_button, subscribe_menu_item) + ?.Subscribe(on_checked_changed)); + + IObservable subscribe_toggle_button(ToggleButton tb) { + on_checked_changed(tb.IsChecked ?? false); + return tb.ObserveIsChecked(); + } + + IObservable subscribe_menu_item(MenuItem mi) { + on_checked_changed(mi.IsChecked); + return mi.ObserveIsChecked(); + } + + void on_checked_changed(bool is_checked) { + _is_checked = is_checked; + CoerceValue(StateProperty); + } + } + } + + class ModalStateDefinition : StateDefinition { + StateDefinition _source; + + static ModalStateDefinition() { + StateProperty.OverrideMetadata(typeof(ModalStateDefinition), new PropertyMetadata( + StateProperty.DefaultMetadata.DefaultValue, + StateProperty.DefaultMetadata.PropertyChangedCallback, + coerce_state)); + + object coerce_state(DependencyObject d, object base_value) { + var sb = new StringBuilder(); + if (d is ModalStateDefinition msd) { + sb.Append(msd.Mode?.ToString()); + sb.Append(msd.Source?.State); + } + return sb.ToString(); + } + } + + #region Mode + public static readonly DependencyProperty ModeProperty = + WPFHelper.create_dp(nameof(Mode), new PropertyMetadata(null, OnModeChanged)); + + static void OnModeChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) => d.CoerceValue(StateProperty); + + public object Mode { + get => GetValue(ModeProperty); + set => SetValue(ModeProperty, value); + } + #endregion + + public StateDefinition Source { + get => _source; + set { + if (_source == value) return; + if (_source != null) + _source.StateChanged -= _on_source_state_changed; + _source = value; + if (_source != null) { + BindingOperations.SetBinding(_source, GroupProperty, new Binding(nameof(Group)) { Source = this, Mode = BindingMode.OneWay }); + _source.StateChanged += _on_source_state_changed; + } + CoerceValue(StateProperty); + } + } + + void _on_source_state_changed(string oldval, string newval) => + CoerceValue(StateProperty); + } + + [ContentProperty(nameof(StateDefinitions))] + class StateGroupsManager : DependencyObject { + IDisposable _state_definitions_hook; + + public bool OverrideTarget { get; set; } + + #region Target + public static readonly DependencyProperty TargetProperty = + WPFHelper.create_dp(nameof(Target), (o, v) => _reset(o, v, o.StateDefinitions)); + + public FrameworkElement Target { get => GetValue(TargetProperty) as FrameworkElement; set => SetValue(TargetProperty, value); } + #endregion + + #region StateDefinitions + public static readonly DependencyProperty StateDefinitionsProperty = + WPFHelper.create_dp(nameof(StateDefinitions), (o, v) => _reset(o, o.Target, v)); + + public StateDefinitionCollection StateDefinitions { get => GetValue(StateDefinitionsProperty) as StateDefinitionCollection; set => SetValue(StateDefinitionsProperty, value); } + #endregion + + /// It is assumed that , and will be assigned at most once (in xaml), before the Target property ever changes. + /// If these properties are assigned after , they will bear no effect. + /// If this causes problems, should be called inside the setters. + public bool AttachToMembers { get; set; } + + static void _reset(StateGroupsManager state_group, FrameworkElement target, StateDefinitionCollection state_defs) { + if (state_group == null) + return; + Disposable.dispose(ref state_group._state_definitions_hook); + if (target == null || state_defs == null) + return; + state_group._state_definitions_hook = ObservableAutoWrapper.connect_item_hooks(state_defs, sd => { + int version = int.MinValue; + transition(sd.State); + sd.StateChanged += on_state_changed; + return Disposable.Create(() => sd.StateChanged -= on_state_changed); + void on_state_changed(string oldval, string newval) => transition(newval); + async void transition(string state) { + version++; + if (target.IsLoaded) + StateManager.GoToState(target, state); + else { + int v = version; + await target.LoadedAsync(); + if (v == version) + StateManager.GoToState(target, state); + } + } + }); + if (state_group.AttachToMembers) { + state_group._state_definitions_hook = new CompositeDisposable( + state_group._state_definitions_hook, + ObservableAutoWrapper.connect_item_actions( + state_defs, + sd => sd.SetCurrentValue(StateDefinition.GroupProperty, state_group))); + } + } + } -namespace mbts.ui -{ // With this utility we can create a ViewModel with a ViewState (string) property // Then in the View simply set StateManager.VisualState = "{binding ViewState}" // @@ -20,8 +286,18 @@ namespace mbts.ui // // // - public class StateManager : DependencyObject - { + class StateManager : DependencyObject { + #region Groups + public static readonly DependencyProperty GroupsProperty = + DependencyProperty.RegisterAttached("Groups", typeof(StateGroupsManager), typeof(StateManager), new PropertyMetadata((d, e) => { + if (d is FrameworkElement el && e.NewValue is StateGroupsManager m && !m.OverrideTarget) + m.SetCurrentValue(StateGroupsManager.TargetProperty, el); + })); + + public static StateGroupsManager GetGroups(DependencyObject d) => d.GetValue(GroupsProperty) as StateGroupsManager; + public static void SetGroups(DependencyObject d, StateGroupsManager value) => d.SetValue(GroupsProperty, value); + #endregion + public static string GetVisualState(DependencyObject obj) { return (string)obj.GetValue(VisualStateProperty); } @@ -68,7 +344,7 @@ namespace mbts.ui static void GoToState(object o, DependencyPropertyChangedEventArgs args) => GoToState(o as FrameworkElement, args.NewValue as string); - static void GoToState(FrameworkElement frameworkElement, string state) { + public static void GoToState(FrameworkElement frameworkElement, string state) { if (frameworkElement != null && !string.IsNullOrEmpty(state)) { if (frameworkElement.IsLoaded) { try { diff --git a/src/client/spark/view/Utility/TextUtils.cs b/src/client/spark/view/Utility/TextUtils.cs index 2ec2cea09..808fe462a 100644 --- a/src/client/spark/view/Utility/TextUtils.cs +++ b/src/client/spark/view/Utility/TextUtils.cs @@ -136,7 +136,9 @@ namespace mbts.ui.utility.text { public static class RegexFilters { public static readonly Regex PriceInput = new Regex(@"^-?\d*((-|\.)\d*)?$"), - Integer = new Regex(@"^\d*$"); + Decimal = new Regex(@"^-?\d*\.?\d*$"), + SignedInteger = new Regex(@"^-?\d*$"), + UnsignedInteger = new Regex(@"^\d*$"); public static class Time { public static readonly Regex diff --git a/src/client/spark/view/Utility/VisualDictionary.cs b/src/client/spark/view/Utility/VisualDictionary.cs index aa7d325a1..dc57afa39 100644 --- a/src/client/spark/view/Utility/VisualDictionary.cs +++ b/src/client/spark/view/Utility/VisualDictionary.cs @@ -1,6 +1,5 @@ using System.Collections; using System.Collections.Generic; -using System.Linq; using System.Windows.Media; namespace mbts.ui { @@ -10,7 +9,7 @@ namespace mbts.ui { /// class VisualDictionary : IDictionary where TValue : Visual { readonly VisualCollection _collection; - readonly Dictionary _dictionary = new Dictionary(); + readonly IDictionary _dictionary = new Dictionary(); public VisualDictionary(Visual parent) => _collection = new VisualCollection(parent); @@ -20,7 +19,7 @@ namespace mbts.ui { set { if (_dictionary.TryGetValue(key, out TValue v)) _collection.Remove(v); - _dictionary[key] = v; + _dictionary[key] = value; _collection.Add(value); } } @@ -40,7 +39,7 @@ namespace mbts.ui { public bool Contains(KeyValuePair item) => _dictionary.Contains(item); public bool ContainsKey(TKey key) => _dictionary.ContainsKey(key); public void CopyTo(KeyValuePair[] array, int arrayIndex) { - ((ICollection>)_dictionary).CopyTo(array, arrayIndex); + _dictionary.CopyTo(array, arrayIndex); } public IEnumerator> GetEnumerator() => _dictionary.GetEnumerator(); public bool Remove(TKey key) { @@ -49,7 +48,7 @@ namespace mbts.ui { return _dictionary.Remove(key); } public bool Remove(KeyValuePair item) { - if (((ICollection>)_dictionary).Remove(item)) { + if (_dictionary.Remove(item)) { _collection.Remove(item.Value); return true; } @@ -59,4 +58,4 @@ namespace mbts.ui { public Visual VisualAtIndex(int index) => _collection[index]; IEnumerator IEnumerable.GetEnumerator() => _dictionary.GetEnumerator(); } -} \ No newline at end of file +} diff --git a/src/client/spark/view/Utility/WPFHelper.cs b/src/client/spark/view/Utility/WPFHelper.cs index 352d11228..b1aea246d 100644 --- a/src/client/spark/view/Utility/WPFHelper.cs +++ b/src/client/spark/view/Utility/WPFHelper.cs @@ -1,14 +1,14 @@ using bts.utils; -using mbts.spark.utilities; -using mbts.ui.utility; using mbts.utils; using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.Linq; +using System.Reactive.Disposables; using System.Windows; using System.Windows.Controls; +using System.Windows.Data; using System.Windows.Input; using System.Windows.Threading; @@ -43,6 +43,9 @@ namespace mbts.ui { public static DependencyProperty create_dp(string name, FrameworkPropertyMetadataOptions options, PropertyChangedCallback callback, TValue default_value = default) => DependencyProperty.Register(name, typeof(TValue), typeof(TOwner), new FrameworkPropertyMetadata(default_value, options, prop_changed_callback(callback))); + public static DependencyProperty create_dp(string name, PropertyMetadata metadata) => + DependencyProperty.Register(name, typeof(TValue), typeof(TOwner), metadata); + public static DependencyPropertyKey create_ro_dp(string name, TValue default_value = default) => DependencyProperty.RegisterReadOnly(name, typeof(TValue), typeof(TOwner), new PropertyMetadata(default_value)); @@ -67,6 +70,12 @@ namespace mbts.ui { public static void override_metadata(DependencyProperty property, FrameworkPropertyMetadataOptions flags, Action callback, TValue default_value = default) => property.OverrideMetadata(typeof(TOwner), new FrameworkPropertyMetadata(default_value, flags, prop_changed_callback(callback))); + public static PropertyMetadata with(this PropertyMetadata property_metadata, CoerceValueCallback coerce_value_callback) => + new PropertyMetadata( + property_metadata.DefaultValue, + property_metadata.PropertyChangedCallback, + coerce_value_callback); + public static bool apply_style(ref T element, Style style) where T : FrameworkElement { if (element != null) { if (style != null) { @@ -239,6 +248,45 @@ namespace mbts.ui { r.Height = new GridLength(r.Height.Value - marginal_adjustment, GridUnitType.Star); } + /// + /// Responds to visibility changes of each component. Visible components shall occupy consecutive rows on the top, while hidden ones are moved to the bottom. + /// As visible components are always adjacent to one another, the s may always be dragged freely. + /// + /// The binding source of the height properties for each component. + /// The row definitions of the Grid which is the visual parent of the component views. + /// The zero-based index of the top-most row, with respect to the . + /// The components themselves; each consisting of a , height prop to bind to, and an observable 'show' source. + /// + public static IDisposable connect_vertical_splitter_components(object vm, RowDefinitionCollection row_defs, int offset, params (FrameworkElement element, string prop, IObservable show_source)[] components) { + bool[] show_comps = new bool[components.Length]; + return new CompositeDisposable(components.Select((c, i) => c.show_source.Subscribe(show => { + show_comps[i] = show; + reset_all(show); + }))); + void reset_all(bool _) { + // Clear all bindings to get a clean slate. This avoids forwarding heights of 0 to the viewmodel for hidden components (when the component is made visible again, it should snap back to it's previous height). + for (int i = 0; i < components.Length; i++) + clear_height(offset + (i * 2)); + int vis_pos = 0; + for (int pos = 0; pos < components.Length; pos++) { + if (show_comps[pos]) { + int row = offset + (vis_pos * 2); + bind_height(row, components[pos].prop); + components[pos].element.SetCurrentValue(Grid.RowProperty, row); + set_current_if_changed(components[pos].element, UIElement.VisibilityProperty, Visibility.Visible); + vis_pos++; + } else { + set_current_if_changed(components[pos].element, UIElement.VisibilityProperty, Visibility.Collapsed); + } + } + for (; vis_pos < components.Length; vis_pos++) + set_height(offset + (vis_pos * 2), 0); + } + void bind_height(int i, string prop) => row_defs[i].SetBinding(RowDefinition.HeightProperty, new Binding(prop) { Source = vm, Converter = ui.converters.GridLengthConverter.StarConverter, Mode = BindingMode.TwoWay }); + void set_height(int i, double value) => row_defs[i].SetCurrentValue(RowDefinition.HeightProperty, new GridLength(value, GridUnitType.Star)); + void clear_height(int i) => row_defs[i].ClearValue(RowDefinition.HeightProperty); + } + public static IDisposable listen_for_clear_focus_requests(FrameworkElement element) { ExceptionAssert.Argument.NotNull(element, nameof(element)); IDisposable hook = null; @@ -393,6 +441,8 @@ namespace mbts.ui { resultant_size = new Size(result_width, result_height); } + public static string join_binding_paths(params string[] paths) => string.Join(".", paths); + public static class Hooks { public static void exchange_is_keyboard_focused_within(FrameworkElement oldval, FrameworkElement newval, DependencyPropertyChangedEventHandler handler) { if (oldval != null) oldval.IsKeyboardFocusWithinChanged -= handler; diff --git a/src/client/spark_api/Co2/Co2NativeMethods.cs b/src/client/spark_api/Co2/Co2NativeMethods.cs index f744b9963..b2ae76044 100644 --- a/src/client/spark_api/Co2/Co2NativeMethods.cs +++ b/src/client/spark_api/Co2/Co2NativeMethods.cs @@ -67,6 +67,10 @@ namespace mbts.co2 [DllImport("libspark")] internal unsafe static extern void md_consumer_get_system_md_symbols(raw_usersymbol_callback cb); + + [DllImport("libspark")] + internal unsafe static extern void dump_co2_memory_to_disk(IntPtr consumer, string path); + // // Relay control diff --git a/src/client/spark_api/Co2/MDConsumer.cs b/src/client/spark_api/Co2/MDConsumer.cs index 439d65af0..3d92f6e69 100644 --- a/src/client/spark_api/Co2/MDConsumer.cs +++ b/src/client/spark_api/Co2/MDConsumer.cs @@ -37,7 +37,10 @@ namespace mbts.co2 unsafe void init() { _raw_sec_cb = (key, buf, len, handle) => { var security = Co2NativeMethods.deserialize(buf, len); - var next = new SecurityAndHandle() { security = security, handle = new MDConsumerHandle(handle) }; + var next = new SecurityAndHandle() { + security = security, + handle = new MDConsumerHandle(_consumer, security, handle) + }; _securities.Add(next); _on_security?.Invoke(new List(1) { next }); }; @@ -67,7 +70,7 @@ namespace mbts.co2 public MDConsumerHandle try_get_handle(security_key key) { Co2NativeMethods.BlitPointerTuple raw; if (Co2NativeMethods.md_consumer_get_handle(_consumer, key, out raw)) { - return new MDConsumerHandle(raw); + return new MDConsumerHandle(this._consumer, null, raw); } return null; } @@ -77,7 +80,10 @@ namespace mbts.co2 List result = new List(); Co2NativeMethods.raw_security_callback cb = (key, buf, len, handle) => { var security = Co2NativeMethods.deserialize(buf, len); - result.Add(new SecurityAndHandle() { security = new Security(security), handle = new MDConsumerHandle(handle) }); + result.Add( + new SecurityAndHandle() { + security = new Security(security), + handle = new MDConsumerHandle(_consumer, security, handle) }); }; Co2NativeMethods.md_consumer_walk_security_list(_consumer, cb); return result; diff --git a/src/client/spark_api/Co2/MDConsumerHandle.cs b/src/client/spark_api/Co2/MDConsumerHandle.cs index 4a12f2f99..7b03bdaee 100644 --- a/src/client/spark_api/Co2/MDConsumerHandle.cs +++ b/src/client/spark_api/Co2/MDConsumerHandle.cs @@ -156,13 +156,22 @@ namespace mbts.co2 { // // Internal - internal MDConsumerHandle(Co2NativeMethods.BlitPointerTuple tuple) { + internal MDConsumerHandle( + IntPtr consumer, + Security security, + Co2NativeMethods.BlitPointerTuple tuple) { _header = (ColdHeader*)tuple.cold_header.ToPointer(); _cold = (ColdEntry*)tuple.cold_data.ToPointer(); if (has_depth) { _hot_depth = (HotDepthEntry*)tuple.hot.ToPointer(); - Log.assert(_hot_depth->key == _cold->security_key); + if (_hot_depth->key != _cold->security_key) { + var temp_path = Path.Combine(Path.GetTempPath(), "btsshm"); + Co2NativeMethods.dump_co2_memory_to_disk(consumer, temp_path); + Log.assert( + _hot_depth->key == _cold->security_key, + $"Please attach the contents of '${temp_path}' to the bug report you are about to file. security:{security?.Id} cold:{_cold->security_key} hot:{_hot->key}"); + } } else { _hot = (HotEntry*)tuple.hot.ToPointer(); diff --git a/src/client/spark_api/api/Channels/QuickBusClientChannel.cs b/src/client/spark_api/api/Channels/QuickBusClientChannel.cs index 593edf9f7..6fae3ce12 100644 --- a/src/client/spark_api/api/Channels/QuickBusClientChannel.cs +++ b/src/client/spark_api/api/Channels/QuickBusClientChannel.cs @@ -67,8 +67,8 @@ namespace bts.api.core { while (true) { var response = await check_stream_access(method_id, qualifier); if (response.success) { - if (response.value.Authorized) { - // success. Break loop and subscribe + if (response.value.Authorized) { + // success. Break loop and subscribe break; } else { @@ -94,7 +94,8 @@ namespace bts.api.core { // Authorized. Stream events unsubscribe_temp_sub(); return SubscribeNative(method, qualifier, parser, converter, observer); - }); + }); + Log.QBus.diag($"Subscribing for sub: '{method}/{qualifier}'"); return result; } private Task> check_stream_access(int method_id, string qualifier) { @@ -145,6 +146,7 @@ namespace bts.api.core { }; var subscription = ApiNativeMethods.api_client_subscribe(_client, method, qualifier, cb, IntPtr.Zero); return FinalizeableAnonymousDisposable.Create((disposing) => { + Log.QBus.diag($"Unsubscribing for sub: '{method}/{qualifier}'"); ApiNativeMethods.api_client_unsubscribe(_client, subscription); subscription = IntPtr.Zero; GC.KeepAlive(cb); diff --git a/src/client/spark_api/api/Update.cs b/src/client/spark_api/api/Update.cs index 1c751e774..7f31478f3 100644 --- a/src/client/spark_api/api/Update.cs +++ b/src/client/spark_api/api/Update.cs @@ -1,4 +1,5 @@ -using System; +using bts.utils; +using System; using System.Collections; using System.Collections.Generic; using System.Collections.Immutable; @@ -205,6 +206,8 @@ namespace bts.api.core { } public class TableUpdate where TKey : IEquatable { + // warning: this does not have a key_extractor + public static readonly TableUpdate empty = new TableUpdate(ImmutableDictionary.Empty, Array.Empty(), Array.Empty>(), Array.Empty(), null); readonly ImmutableDictionary _state; @@ -253,6 +256,7 @@ namespace bts.api.core { if (new_state.TryGetValue(kv.Key, out T new_val)) { if (!value_comparer.Equals(kv.Value, new_val)) { changes.Add(new Change(kv.Value, new_val)); + builder[kv.Key] = new_val; } } else { removed.Add(kv.Value); @@ -277,6 +281,74 @@ namespace bts.api.core { internal Builder to_builder() => new Builder(this); + public static class FilterHelper { + internal static TableUpdate on_source_changed(TableUpdate filtered_target, IEnumerable raw_added, IEnumerable> raw_changes, IEnumerable raw_removed, Func predicate) { + var builder = filtered_target._state.ToBuilder(); + List added, removed; + List> changes; + if (predicate == null) { + added = raw_added.ToList(); + removed = raw_removed.ToList(); + changes = raw_changes.ToList(); + } else { + added = new List(raw_added.Where(predicate)); + removed = new List(raw_removed.Where(predicate)); + changes = new List>(); + foreach (var ch in raw_changes) { + if (predicate(ch.Old)) { + if (predicate(ch.New)) { + changes.Add(ch); + } else { + removed.Add(ch.Old); + } + } else if (predicate(ch.New)) { + added.Add(ch.New); + } + } + } + var key = filtered_target.key_extractor; + builder.RemoveRange(removed.Select(key)); + foreach (var ch in changes) + builder[key(ch.New)] = ch.New; + builder.AddRange(added.Select(v => new KeyValuePair(key(v), v))); + return new TableUpdate(builder.ToImmutable(), added, changes, removed, key); + } + + internal static TableUpdate on_predicate_changed(TableUpdate filtered_target, IReadOnlyDictionary unfiltered_state, Func old_predicate, Func new_predicate) { + var added = new List(); + var removed = new List(); + if (new_predicate == old_predicate) { + // nothing changed - this method probably shouldn't be called when nothing changes. Having said that, it doesn't really hurt anything, + // so don't throw a metaphorical wrench into the gears by throwing a literal exception. Just return the table as is. + if (filtered_target.has_changes()) + filtered_target = new TableUpdate(filtered_target._state, Enumerable.Empty(), Enumerable.Empty>(), Enumerable.Empty(), filtered_target.key_extractor); + return filtered_target; + } + if (old_predicate == null) { + removed.AddRange(filtered_target.state.Values.Where(v => !new_predicate(v))); + } else if (new_predicate == null) { + added.AddRange(unfiltered_state.Values.Where(v => !old_predicate(v))); + } else { + foreach (var kv in unfiltered_state) { + if (old_predicate(kv.Value)) { + if (new_predicate(kv.Value)) { + continue; + } else { + removed.Add(kv.Value); + } + } else if (new_predicate(kv.Value)) { + added.Add(kv.Value); + } + } + } + var builder = filtered_target._state.ToBuilder(); + var key = filtered_target.key_extractor; + builder.RemoveRange(removed.Select(key)); + builder.AddRange(added.Select(v => new KeyValuePair(key(v), v))); + return new TableUpdate(builder.ToImmutable(), added, Array.Empty>(), removed, key); + } + } + /// /// This class is used to aggregate a series of changes into a single update. /// @@ -331,6 +403,17 @@ namespace bts.api.core { builder.AddRange(_added); return new TableUpdate(builder.ToImmutableDictionary(), _added.Values, _changes.Values, _removed.Values, _state.key_extractor); } + + public TableUpdate to_table_checked(IEqualityComparer comparer) { + var builder = _state._state.ToBuilder(); + builder.RemoveRange(_removed.Keys); + foreach (var kv in _changes) { + if (!comparer.Equals(kv.Value.Old, kv.Value.New)) + builder[kv.Key] = kv.Value.New; + } + builder.AddRange(_added); + return new TableUpdate(builder.ToImmutableDictionary(), _added.Values, _changes.Values, _removed.Values, _state.key_extractor); + } } } @@ -347,6 +430,16 @@ namespace bts.api.core { } public static class ObservableUpdateExtensions { + public static IEnumerable Old(this IEnumerable> changes) { + foreach (var ch in changes) + yield return ch.Old; + } + + public static IEnumerable New(this IEnumerable> changes) { + foreach (var ch in changes) + yield return ch.New; + } + internal static bool has_changes(this TableUpdate table) where TKey : IEquatable => table.added.Any() || table.changes.Any() || table.removed.Any(); @@ -512,6 +605,51 @@ namespace bts.api.core { public static IObservable> Filter(this IObservable> source, Func predicate, Func key) where TKey : IEquatable => source.Scan(TableUpdate.mk_empty(key), (src, tgt) => _apply_predicate(src, tgt, predicate, key)); + public static IObservable> Filter(this IObservable> table_source, IObservable> predicate_source, Func key) where TKey : IEquatable => + Filter(table_source, predicate_source, key, _ => true); + + public static IObservable> Filter(this IObservable> table_source, IObservable> predicate_source, Func key, Func init_predicate) where TKey : IEquatable => + table_source.AggregateLatest(predicate_source, + (tout, tin, pred) => TableUpdate.FilterHelper.on_source_changed(tout, tin.New.added, tin.New.changes, tin.New.removed, pred), + (tout, tin, pred) => TableUpdate.FilterHelper.on_predicate_changed(tout, tin.state, pred.Old, pred.New), + () => TableUpdate.mk_empty(key), + TableUpdate.mk_empty(key), + init_predicate); + + public static IObservable<(TableUpdate filtered, TableUpdate raw)> FilterWithRaw(this IObservable> table_source, IObservable> predicate_source, Func key, Func init_predicate) where TKey : IEquatable { + var empty = TableUpdate.mk_empty(key); + return table_source.AggregateLatest, Func, (TableUpdate filtered, TableUpdate raw)>(predicate_source, + (tout, tin, pred) => { + var filtered = TableUpdate.FilterHelper.on_source_changed(tout.filtered, tin.New.added, tin.New.changes, tin.New.removed, pred); + return (filtered, tin.New); + }, + (tout, tin, pred) => { + var filtered = TableUpdate.FilterHelper.on_predicate_changed(tout.filtered, tin.state, pred.Old, pred.New); + return (filtered, tin); + }, + () => (empty, empty), + empty, + init_predicate); + } + + public static IObservable AggregateLatest(this IObservable source, IObservable right, + Func, TRight, TAggregate> update_left, Func, TAggregate> update_right, Func seed_factory, TLeft init_left = default, TRight init_right = default) => + Observable.Create(o => { + Log.DataFlow.diag($"Create AggregateLatest (Left: {typeof(TLeft)}, Right: {typeof(TRight)})."); + var aggregator = new ConcurrentAggregator(update_left, update_right, o.OnNext, seed_factory(), init_left, init_right); + return new CompositeDisposable(source.Subscribe(aggregator.on_left), right.Subscribe(aggregator.on_right)); + }); + + public static IObservable AggregateLatest(this IObservable source, IObservable right, + Func, TRight, TAggregate> update_left, Func, TAggregate> update_right, TAggregate seed, + Func result_selector, + TLeft init_left = default, TRight init_right = default) => + Observable.Create(o => { + Log.DataFlow.diag($"Create AggregateLatest (Left: {typeof(TLeft)}, Right: {typeof(TRight)})."); + var aggregator = new ConcurrentAggregator(update_left, update_right, agg => o.OnNext(result_selector(agg)), seed, init_left, init_right); + return new CompositeDisposable(source.Subscribe(aggregator.on_left), right.Subscribe(aggregator.on_right)); + }); + static TableUpdate _apply_predicate(TableUpdate tgt_table, TableUpdate src_table, Func predicate, Func key) where TKey : IEquatable { var added = src_table.added.Where(predicate).ToList(); var removed = src_table.removed.Where(predicate).ToList(); @@ -621,22 +759,20 @@ namespace bts.api.core { }); } - public static IConnectableObservable> LeftJoin(this IObservable> left_source, IObservable> right_source, + public static IObservable> LeftJoin(this IObservable> left_source, IObservable> right_source, Func left_key, Func right_key, TRight right_default = default) where TKey : IEquatable => - new TableUpdateLeftJoin( - left_source, right_source, left_key, right_key, left_key, (lv, lk, rv, rk) => (lv, rv), (lv, lk, rk) => (lv, right_default), t => left_key(t.left)); + LeftJoin(left_source, right_source, left_key, right_key, left_key, (lv, lk, rv, rk) => (lv, rv), (lv, lk, rk) => (lv, right_default), t => left_key(t.left)); - public static IConnectableObservable> LeftJoin(this IObservable> left_source, IObservable> right_source, + public static IObservable> LeftJoin(this IObservable> left_source, IObservable> right_source, Func left_key, Func right_key, Func result_selector, Func absent_right_result_selector, Func result_key) where TKey : IEquatable => - new TableUpdateLeftJoin( - left_source, right_source, left_key, right_key, left_key, (lv, lk, rv, rk) => result_selector(lv, lk, rv), (lv, lk, rk) => absent_right_result_selector(lv, lk), result_key); + LeftJoin(left_source, right_source, left_key, right_key, left_key, (lv, lk, rv, rk) => result_selector(lv, lk, rv), (lv, lk, rk) => absent_right_result_selector(lv, lk), result_key); - public static IConnectableObservable> LeftJoin(this IObservable> left_source, IObservable> right_source, - Func key, Func right_key, Func join_key, Func result_selector, Func absent_result_selector, Func result_key) + public static IObservable> LeftJoin(this IObservable> left_source, IObservable> right_source, + Func left_key, Func right_key, Func join_key, Func result_selector, Func absent_right_result_selector, Func result_key) where TLeftKey : IEquatable where TRightKey : IEquatable => - new TableUpdateLeftJoin(left_source, right_source, key, right_key, join_key, result_selector, absent_result_selector, result_key); + TableUpdateLeftJoin.Create(left_source, right_source, left_key, right_key, join_key, result_selector, absent_right_result_selector, result_key); } -} \ No newline at end of file +} diff --git a/src/client/spark_api/api/Update/TableUpdateLeftJoin.cs b/src/client/spark_api/api/Update/TableUpdateLeftJoin.cs index 377caadd0..1b6832260 100644 --- a/src/client/spark_api/api/Update/TableUpdateLeftJoin.cs +++ b/src/client/spark_api/api/Update/TableUpdateLeftJoin.cs @@ -1,223 +1,89 @@ using System; using System.Collections.Generic; using System.Linq; -using System.Reactive.Disposables; using System.Reactive.Linq; -using System.Reactive.Subjects; -using System.Threading; namespace bts.api.core { - class TableUpdateLeftJoin : IConnectableObservable> - where TLeftKey : IEquatable - where TRightKey : IEquatable { - // left - readonly Func _left_key; - readonly IObservable> _left_source; - // right - readonly Func _right_key; - readonly IObservable> _right_source; - // join - readonly Func _result_selector; - readonly Func _absent_right_result_selector; - readonly Func _join_key; - readonly Dictionary> _join_index = new Dictionary>(); - readonly Subject> _subject = new Subject>(); - // state - TableUpdate _table; - Dictionary _right_state = new Dictionary(); - IReadOnlyDictionary _left_state = new Dictionary(); - - IDisposable _subscriptions = mbts.Disposable.empty; - int _connection; // unconnected = 0, connected == 1 - Queue<_Op> _buffer = new Queue<_Op>(); - bool _is_updating, _left_completed, _right_completed; - - public TableUpdateLeftJoin(IObservable> left_source, IObservable> right_source, Func left_key, Func right_key, - Func join_key, Func result_selector, Func absent_right_result_selector, Func result_key) { - _left_source = left_source; - _left_key = left_key; - _right_source = right_source; - _right_key = right_key; - _join_key = join_key; - _result_selector = result_selector; - _absent_right_result_selector = absent_right_result_selector; - _table = TableUpdate.mk_empty(result_key); - } - - public IDisposable Connect() { - if (Interlocked.CompareExchange(ref _connection, 1, 0) == 0) { - _subscriptions = new CompositeDisposable( - _left_source.Subscribe(_on_left_update, _on_left_completed), - _right_source.Subscribe(_on_right_update, _on_right_completed)); - } - return Disposable.Create(() => { - if (Interlocked.CompareExchange(ref _connection, 0, 1) == 1) - _subscriptions.Dispose(); - }); - } - - public IDisposable Subscribe(IObserver> observer) { - lock (this) { - if (_is_updating) { - var sub = new LazySubscription(() => _subscribe_core(observer)); - _buffer.Enqueue(new _Op(sub)); - return sub; + static class TableUpdateLeftJoin { + public static IObservable> Create( + IObservable> left_source, + IObservable> right_source, + Func left_key, + Func right_key, + Func join_key, + Func result_selector, + Func absent_right_result_selector, + Func result_key) + where TLeftKey : IEquatable + where TRightKey : IEquatable { + return left_source.AggregateLatest, TableUpdate, (TableUpdate result, Dictionary> join_index), TableUpdate>( + right_source, + process_left, + process_right, + (TableUpdate.mk_empty(result_key), new Dictionary>()), + state => state.result, + TableUpdate.mk_empty(left_key), + TableUpdate.mk_empty(right_key)); + // process left + (TableUpdate result, Dictionary> join_index) process_left( + (TableUpdate result, Dictionary> join_index) state, + Change> change, + TableUpdate right) { + var left_update = change.New; + var join_index = state.join_index; + var builder = state.result.to_builder(); + foreach (var v in left_update.removed) { + var lk = left_key(v); + builder.remove(lk); + var rk = join_key(v); + var joined = join_index[rk]; + if (joined.Remove(lk) && joined.Count == 0) + join_index.Remove(rk); } - return _subscribe_core(observer); - } - } - - IDisposable _subscribe_core(IObserver> observer) { - observer.OnNext(_table.as_snapshot()); - return _subject.Subscribe(observer); - } - - #region Left - void _on_left_completed() { - lock (this) { - _left_completed = true; - if (_right_completed) - _subject.OnCompleted(); - } - } - void _on_left_update(TableUpdate left_update) { - lock (this) { - if (_is_updating) { - _buffer.Enqueue(new _Op(left_update)); - return; + foreach (var v in left_update.added.Concat(left_update.changed)) { + var lk = left_key(v); + var rk = join_key(v); + var result = right.state.TryGetValue(rk, out TRight r) ? result_selector(v, lk, r, rk) : absent_right_result_selector(v, lk, rk); + builder.add_or_update(lk, result); + if (!join_index.TryGetValue(rk, out HashSet joined)) + join_index.Add(rk, joined = new HashSet()); + joined.Add(lk); } - _is_updating = true; + return (builder.to_table(), join_index); } - _process_left(left_update); - } - - void _process_left(TableUpdate left_update) { - var builder = _table.to_builder(); - foreach (var v in left_update.removed) { - var lk = _left_key(v); - builder.remove(lk); - var rk = _join_key(v); - var joined = _join_index[rk]; - if (joined.Remove(lk) && joined.Count == 0) - _join_index.Remove(rk); - } - foreach (var v in left_update.added.Concat(left_update.changed)) { - var lk = _left_key(v); - var rk = _join_key(v); - var result = _right_state.TryGetValue(rk, out TRight r) ? _result_selector(v, lk, r, rk) : _absent_right_result_selector(v, lk, rk); - builder.add_or_update(lk, result); - if (!_join_index.TryGetValue(rk, out HashSet joined)) - _join_index.Add(rk, joined = new HashSet()); - joined.Add(lk); - } - _left_state = left_update.state; - _table = builder.to_table(); - _subject.OnNext(_table); - _on_op_completed(); - } - #endregion - - #region Right - void _on_right_completed() { - lock (this) { - _right_completed = true; - if (_left_completed) - _subject.OnCompleted(); - } - } - - void _on_right_update(TableUpdate right_update) { - lock (this) { - if (_is_updating) { - _buffer.Enqueue(new _Op(right_update)); - return; - } - _is_updating = true; - } - _process_right(right_update); - } - - void _process_right(TableUpdate right_update) { - var builder = _table.to_builder(); - foreach (var v in right_update.removed) { - var rkey = _right_key(v); - if (_join_index.TryGetValue(rkey, out HashSet lkeys)) { - foreach (var k in lkeys) { - var lval = _left_state[k]; - var result = _absent_right_result_selector(lval, k, rkey); - builder.add_or_update(k, result); + // process right + (TableUpdate result, Dictionary> join_index) process_right( + (TableUpdate result, Dictionary> join_index) state, + TableUpdate left, + Change> change) { + var right_update = change.New; + var join_index = state.join_index; + var builder = state.result.to_builder(); + foreach (var v in right_update.removed) { + var rkey = right_key(v); + if (join_index.TryGetValue(rkey, out HashSet lkeys)) { + foreach (var k in lkeys) { + var lval = left.state[k]; + var result = absent_right_result_selector(lval, k, rkey); + builder.add_or_update(k, result); + } + if (lkeys.Count == 0) + join_index.Remove(rkey); } - if (lkeys.Count == 0) - _join_index.Remove(rkey); } - _right_state.Remove(rkey); - } - foreach (var v in right_update.added.Concat(right_update.changed)) { - var rkey = _right_key(v); - if (_join_index.TryGetValue(rkey, out HashSet lkeys)) { - foreach (var k in lkeys) { - var lval = _left_state[k]; - var result = _result_selector(lval, k, v, rkey); - builder.add_or_update(k, result); + foreach (var v in right_update.added.Concat(right_update.changed)) { + var rkey = right_key(v); + if (join_index.TryGetValue(rkey, out HashSet lkeys)) { + foreach (var k in lkeys) { + var lval = left.state[k]; + var result = result_selector(lval, k, v, rkey); + builder.add_or_update(k, result); + } + } else { + join_index.Add(rkey, new HashSet()); } - } else { - _join_index.Add(rkey, new HashSet()); - } - _right_state[rkey] = v; - } - _table = builder.to_table(); - if (_table.has_changes()) { - _subject.OnNext(_table); - } - _on_op_completed(); - } - #endregion - - void _on_op_completed() { - Log.assert(_is_updating); - _Op buffered_op; - lock (this) { - if (_buffer.Count == 0) { - _is_updating = false; - return; - } - buffered_op = _buffer.Dequeue(); - } - switch (buffered_op.update_case) { - case _Op.UpdateOneofCase.Left: - _process_left(buffered_op.left); - break; - case _Op.UpdateOneofCase.Right: - _process_right(buffered_op.right); - break; - case _Op.UpdateOneofCase.Subscription: - buffered_op.subscription.connect(); - _on_op_completed(); - break; - } - } - - class _Op { - public readonly TableUpdate left; - public readonly TableUpdate right; - public readonly LazySubscription subscription; - - public _Op(TableUpdate left) => this.left = left; - public _Op(TableUpdate right) => this.right = right; - public _Op(LazySubscription subscription) => - this.subscription = subscription; - - public enum UpdateOneofCase { - Left, Right, Subscription - } - - public UpdateOneofCase update_case { - get { - if (left != null) return UpdateOneofCase.Left; - if (right != null) return UpdateOneofCase.Right; - if (subscription != null) return UpdateOneofCase.Subscription; - throw new InvalidOperationException("Unexpected state."); } + return (builder.to_table(), join_index); } } } diff --git a/src/client/spark_api/utils/ConcurrentAggregator.cs b/src/client/spark_api/utils/ConcurrentAggregator.cs new file mode 100644 index 000000000..cb63e17f9 --- /dev/null +++ b/src/client/spark_api/utils/ConcurrentAggregator.cs @@ -0,0 +1,51 @@ +using bts.api.core; +using System; + +namespace bts.utils { + class ConcurrentAggregator { + readonly Func, TRight, TAggregate> _update_left; + readonly Func, TAggregate> _update_right; + readonly Action _on_update_completed; + readonly ConcurrentOpGate<(TLeft lval, TRight rval, bool is_left)> gate = new ConcurrentOpGate<(TLeft lval, TRight rval, bool is_left)>(); + + TAggregate _seed; + TLeft _left; + TRight _right; + + public ConcurrentAggregator( + Func, TRight, TAggregate> update_left, Func, TAggregate> update_right, Action on_update_completed, TAggregate seed, TLeft init_left = default, TRight init_right = default) { + _update_left = update_left; + _update_right = update_right; + _on_update_completed = on_update_completed; + _seed = seed; + _left = init_left; + _right = init_right; + } + + public void on_left(TLeft lval) { + if (gate.try_enter((lval, default, true))) + process_left(lval); + } + public void process_left(TLeft lval) { + _seed = _update_left(_seed, new Change(_left, _left = lval), _right); + _on_op_completed(); + } + public void on_right(TRight rval) { + if (gate.try_enter((default, rval, false))) + process_right(rval); + } + public void process_right(TRight rval) { + _seed = _update_right(_seed, _left, new Change(_right, _right = rval)); + _on_op_completed(); + } + + void _on_op_completed() { + _on_update_completed(_seed); + if (!gate.try_exit(out (TLeft lval, TRight rval, bool is_left) next_op)) { + if (next_op.is_left) + process_left(next_op.lval); + else process_right(next_op.rval); + } + } + } +} \ No newline at end of file diff --git a/src/client/spark_api/utils/ConcurrentOpGate.cs b/src/client/spark_api/utils/ConcurrentOpGate.cs new file mode 100644 index 000000000..25ef1b168 --- /dev/null +++ b/src/client/spark_api/utils/ConcurrentOpGate.cs @@ -0,0 +1,31 @@ +using System.Collections.Generic; + +namespace bts.utils { + class ConcurrentOpGate { + bool _is_busy; + readonly Queue _op_queue = new Queue(); + + public bool try_enter(T op) { + lock (_op_queue) { + if (_is_busy) { + _op_queue.Enqueue(op); + return false; + } + _is_busy = true; + } + return true; + } + + public bool try_exit(out T continue_with) { + lock (_op_queue) { + if (_op_queue.Count > 0) { + continue_with = _op_queue.Dequeue(); + return false; + } + _is_busy = false; + } + continue_with = default; + return true; + } + } +} \ No newline at end of file diff --git a/src/client/spark_api/utils/EqualityComparer.cs b/src/client/spark_api/utils/EqualityComparer.cs index 799fc111f..685b69387 100644 --- a/src/client/spark_api/utils/EqualityComparer.cs +++ b/src/client/spark_api/utils/EqualityComparer.cs @@ -30,6 +30,9 @@ namespace bts.utils { public static IEqualityComparer null_check_wrapper(IEqualityComparer comparer) where T : class => new AnonymousEqualityComparer((a, b) => NullCheckEquals(a, b, comparer.Equals), comparer.GetHashCode); + public static IEqualityComparer to_safe(this IEqualityComparer comparer) where T : class => + new SafeComparerWrapper(comparer); + public static bool safe_sequence_equals(IEnumerable source, IEnumerable other) => NullCheckEquals(source, other, (a, b) => a.SequenceEqual(b)); @@ -121,5 +124,15 @@ namespace bts.utils { bool IEqualityComparer.Equals(object x, object y) => x is T xt && y is T yt && _equals(xt, yt); int IEqualityComparer.GetHashCode(object obj) => throw new NotImplementedException(); } + + struct SafeComparerWrapper : IEqualityComparer where T : class { + readonly IEqualityComparer _comparer; + + public SafeComparerWrapper(IEqualityComparer comparer) => + _comparer = comparer; + + public bool Equals(T x, T y) => x == null ? y == null : y != null && _comparer.Equals(x, y); + public int GetHashCode(T obj) => obj == null ? 0 : _comparer.GetHashCode(obj); + } } } \ No newline at end of file diff --git a/src/client/spark_api/utils/MathUtils.cs b/src/client/spark_api/utils/MathUtils.cs index 19e04f065..7c2ebfaf4 100644 --- a/src/client/spark_api/utils/MathUtils.cs +++ b/src/client/spark_api/utils/MathUtils.cs @@ -5,6 +5,8 @@ using System.Linq; namespace bts.utils { static class MathUtils { public const double epsilon = 1E-12; + public static readonly IEqualityComparer epsilon_comparer = new EpsilonComparer(); + public static bool epsilon_equals(double x, double y) => Math.Abs(x - y) < epsilon; @@ -51,6 +53,10 @@ namespace bts.utils { for (int i = 1; i < num2; i++) if ((num1 * i) % num2 == 0) return i * num1; return num1 * num2; } + + public static bool is_within_range(this double value, double min, double max) => + value >= min && value <= max; + public static int within_range(int min, int max, int value) { if (value < min) return min; if (value > max) return max; @@ -110,5 +116,10 @@ namespace bts.utils { P_1276777 = 1276777, P_2492003 = 2492003; } + + struct EpsilonComparer : IEqualityComparer { + public bool Equals(double x, double y) => x.Equals(y) || Math.Abs(x - y) < epsilon; + public int GetHashCode(double d) => Convert.ToInt32(d); + } } -} +} \ No newline at end of file diff --git a/src/client/spark_core/Collections/Extensions/ArrayExtensions.cs b/src/client/spark_core/Collections/Extensions/ArrayExtensions.cs new file mode 100644 index 000000000..b4479a476 --- /dev/null +++ b/src/client/spark_core/Collections/Extensions/ArrayExtensions.cs @@ -0,0 +1,23 @@ +namespace bts.collections { + public static class ArrayExtensions { + public static T at_or_nearest(this T[] array, int index) { + if (index < 0) { + return array.Length > 0 ? array[0] : default; + } else if (index >= array.Length) { + return array[array.Length - 1]; + } else return array[index]; + } + + public static bool try_get_at_index(this T[] array, int index, out T result) { + if (array.within_range(index)) { + result = array[index]; + return true; + } + result = default; + return false; + } + + public static bool within_range(this T[] array, int index) => + index >= 0 && index < array.Length; + } +} \ No newline at end of file diff --git a/src/client/spark_core/Collections/Extensions/CollectionExtensions.cs b/src/client/spark_core/Collections/Extensions/CollectionExtensions.cs index 257db9087..fd935a060 100644 --- a/src/client/spark_core/Collections/Extensions/CollectionExtensions.cs +++ b/src/client/spark_core/Collections/Extensions/CollectionExtensions.cs @@ -2,7 +2,25 @@ namespace bts.collections { public static class CollectionExtensions { + public static void AddRange(this ICollection collection, params T[] items) { + foreach (T item in items) + collection.Add(item); + } + + public static void AddRange(this ICollection collection, IEnumerable items) { + foreach (T item in items) + collection.Add(item); + } + public static bool check_index(this ICollection collection, int index) => index >= 0 && index < collection.Count; + + public static void SetItems(this ICollection collection, IEnumerable items) { + collection.Clear(); + collection.AddRange(items); + } + + public static bool within_range(this ICollection collection, int index) => + index >= 0 && index < collection.Count; } } \ No newline at end of file diff --git a/src/client/spark_core/Collections/Extensions/DictionaryExtensions.cs b/src/client/spark_core/Collections/Extensions/DictionaryExtensions.cs index e44283c14..296d85640 100644 --- a/src/client/spark_core/Collections/Extensions/DictionaryExtensions.cs +++ b/src/client/spark_core/Collections/Extensions/DictionaryExtensions.cs @@ -1,4 +1,5 @@ -using System.Collections.ObjectModel; +using bts.collections; +using System.Collections.ObjectModel; using System.Linq; namespace System.Collections.Generic { @@ -29,12 +30,40 @@ namespace System.Collections.Generic { else dictionary[key] = update_value(key, value); } + public static void AddOrUpdate(this IDictionary dictionary, TKey key, Action update_existing, Func create_new) { + if (dictionary.TryGetValue(key, out TValue curr)) update_existing(curr); + else dictionary.Add(key, create_new()); + } + + public static TValue? GetNullable(this IDictionary dictionary, TKey key) where TValue : struct { + if (dictionary.TryGetValue(key, out TValue result)) + return result; + else return null; + } + public static TValue GetOrAdd(this IDictionary dictionary, TKey key, Func add_value_factory) { if (!dictionary.TryGetValue(key, out TValue value)) dictionary.Add(key, value = add_value_factory(key)); return value; } + #region GetValueOrDefault + public static TValue GetValueOrDefault(this IReadOnlyDictionary dictionary, TKey key) => + dictionary.TryGetValue(key, out TValue result) ? result : default; + + public static TValue GetValueOrDefault(this IDictionary dictionary, TKey key) => + dictionary.TryGetValue(key, out TValue result) ? result : default; + + public static TValue GetValueOrDefault(this IDictionary dictionary, TKey key, TValue default_value) => + dictionary.TryGetValue(key, out TValue result) ? result : default_value; + + public static TValue GetValueOrDefault(this IDictionary dictionary, TKey key, Func default_factory) => + dictionary.TryGetValue(key, out TValue result) ? result : default_factory(key); + + public static TValue GetValueOrDefault(this Dictionary dictionary, TKey key) => + dictionary.TryGetValue(key, out TValue result) ? result : default; + #endregion + public static IReadOnlyDictionary Join(this IReadOnlyDictionary dictionary, IReadOnlyDictionary merge_target) => Join(dictionary, merge_target, (v1, v2) => (v1, v2)); @@ -113,14 +142,123 @@ namespace System.Collections.Generic { return null; } + public static void sync_with( + this IDictionary dictionary, + Dictionary source, + Func selector + ) => _sync_with(dictionary, source, selector); + + public static void sync_with( + this IDictionary dictionary, + IDictionary source, + Func selector + ) => _sync_with(dictionary, source, selector); + + public static void sync_with( + this IDictionary dictionary, + IReadOnlyDictionary source, + Func selector + ) => _sync_with_ro(dictionary, source, selector); + + public static void sync_with_demux( + this IDictionary dictionary, + Dictionary source, + Func, TKey> key_selector, + Func>, TValue> value_selector, + Action, IEnumerable>> update + ) => _sync_with_demux(dictionary, source, key_selector, value_selector, update); + + public static void sync_with_demux( + this IDictionary dictionary, + IDictionary source, + Func, TKey> key_selector, + Func>, TValue> value_selector, + Action, IEnumerable>> update + ) => _sync_with_demux(dictionary, source, key_selector, value_selector, update); + + public static void sync_with_demux( + this IDictionary dictionary, + IReadOnlyDictionary source, + Func, TKey> key_selector, + Func>, TValue> value_selector, + Action, IEnumerable>> update + ) => _sync_with_demux_ro(dictionary, source, key_selector, value_selector, update); + + static void _sync_with(IDictionary dictionary, IDictionary source, Func selector) { + var removes = dictionary.Keys.Except(source.Keys).ToList(); + foreach (var k in removes) + dictionary.Remove(k); + var adds = source.Except(dictionary.Keys, kv => kv.Key).ToList(); + foreach (var kv in adds) + dictionary.Add(kv.Key, selector(kv.Key, kv.Value)); + } + + static void _sync_with_ro(IDictionary dictionary, IReadOnlyDictionary source, Func selector) { + var removes = dictionary.Keys.Except(source.Keys).ToList(); + foreach (var k in removes) + dictionary.Remove(k); + var adds = source.Except(dictionary.Keys, kv => kv.Key).ToList(); + foreach (var kv in adds) + dictionary.Add(kv.Key, selector(kv.Key, kv.Value)); + } + + static void _sync_with_demux( + IDictionary dictionary, + IDictionary source, + Func, TKey> key_selector, + Func>, TValue> value_selector, + Action, IEnumerable>> update) { + var source_lookup = source.ToLookup(key_selector); + HashSet changes = new HashSet(), removes = new HashSet(); + foreach (var kv in dictionary) { + if (source_lookup.TryGetValue(kv.Key, out IEnumerable> result)) { + update(kv, result); + changes.Add(kv.Key); + } else { + removes.Add(kv.Key); + } + } + foreach (var k in removes) + dictionary.Remove(k); + foreach (var g in source_lookup) { + if (!changes.Contains(g.Key)) + dictionary.Add(g.Key, value_selector(g)); + } + } + + static void _sync_with_demux_ro( + IDictionary dictionary, + IReadOnlyDictionary source, + Func, TKey> key_selector, + Func>, TValue> value_selector, + Action, IEnumerable>> update + ) { + var source_lookup = source.ToLookup(key_selector); + HashSet changes = new HashSet(), removes = new HashSet(); + foreach (var kv in dictionary) { + if (source_lookup.TryGetValue(kv.Key, out IEnumerable> result)) { + update(kv, result); + changes.Add(kv.Key); + } else { + removes.Add(kv.Key); + } + } + foreach (var k in removes) + dictionary.Remove(k); + foreach (var g in source_lookup) { + if (!changes.Contains(g.Key)) + dictionary.Add(g.Key, value_selector(g)); + } + } } public static class DictionaryHelper { - public static Dictionary empty() => + public static IReadOnlyDictionary empty() => Empty.value; static class Empty { - public static readonly Dictionary value = new Dictionary(0); + public static readonly IReadOnlyDictionary value = + new ReadOnlyDictionary(new Dictionary(0)); } } } \ No newline at end of file diff --git a/src/client/spark/core/GlobalExtensions/GenericCollectionExtensions.cs b/src/client/spark_core/Collections/Extensions/EnumerableExtensions.cs similarity index 54% rename from src/client/spark/core/GlobalExtensions/GenericCollectionExtensions.cs rename to src/client/spark_core/Collections/Extensions/EnumerableExtensions.cs index f74496007..d2f85f273 100644 --- a/src/client/spark/core/GlobalExtensions/GenericCollectionExtensions.cs +++ b/src/client/spark_core/Collections/Extensions/EnumerableExtensions.cs @@ -1,751 +1,520 @@ -using bts.utils; -using mbts.utils; -using System; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Collections.Specialized; -using System.Linq; -using System.Reactive.Linq; - -namespace System.Collections.Generic { - public static class EnumerableExtensions { - #region Ordered - public static IOrderedEnumerable Ordered(this IEnumerable enumerable) => - enumerable.OrderBy(t => t); - - public static IEnumerable Ordered(this IEnumerable enumerable, Func compare) => - enumerable.Ordered(Comparer.Create(new Comparison(compare))); - - public static IEnumerable Ordered(this IEnumerable enumerable, IComparer comparer) => - enumerable.OrderBy(t => t, comparer); - #endregion - - public static IEnumerable DistinctOn(this IEnumerable enumerable, Func key_selector) => - enumerable.Distinct(EqualityComparer.Create((x, y) => key_selector(x).Equals(key_selector(y)), x => key_selector(x).GetHashCode())); - - public static IEnumerable Except(this IEnumerable enumerable, IEnumerable second, Func key_selector) => - enumerable.Where(t => !second.Contains(key_selector(t))); - - public static IEnumerable Intersect(this IEnumerable enumerable, IEnumerable second, Func key_selector) => - enumerable.Where(t => second.Contains(key_selector(t))); - - public static T[] ToLArray(this IEnumerable enumerable) => - enumerable.ToList().ToArray(); - - public static TAccumulate AggregateWhile(this IEnumerable source, TAccumulate seed, Func aggregate, Func predicate) => - AggregateWhile(source, seed, aggregate, predicate, (curr, el, next) => curr); - - public static TAccumulate AggregateWhile(this IEnumerable source, TAccumulate seed, Func aggregate, Func predicate, TAccumulate early_break_rv) => - AggregateWhile(source, seed, aggregate, predicate, (curr, el, next) => early_break_rv); - - public static TAccumulate AggregateWhile(this IEnumerable source, TAccumulate seed, Func aggregate, Func predicate, Func sanitize_on_early_break) { - TAccumulate rv = seed; - foreach (T el in source) { - var next = aggregate(rv, el); - if (predicate(next, el)) - rv = next; - else return sanitize_on_early_break(rv, el, next); - } - return rv; - } - - // use "new [] { item }" - avoid putting this on the intellisense for every item everywhere - //public static IEnumerable ToIEnumerable(this T item) { - // yield return item; - //} - - public static IEnumerable TakeWhile(this IEnumerable source, TAccumulate seed, Func accumulate, Func predicate) { - TAccumulate a = seed; - foreach (T el in source) { - if (!predicate(a, el)) - break; - a = accumulate(a, el); - yield return el; - } - } - - public static bool TryGetFirst(this IEnumerable source, Func predicate, out T result) { - if (source == null) throw new ArgumentNullException(nameof(source)); - foreach (T element in source) - if (predicate(element)) { - result = element; - return true; - } - result = default; - return false; - } - - public static bool TryGetFirst(this IEnumerable source, Func predicate, Func select, out TResult result) { - if (source == null) throw new ArgumentNullException(nameof(source)); - foreach (T element in source) - if (predicate(element)) { - result = select(element); - return true; - } - result = default; - return false; - } - - public static T FirstOrDefault(this IEnumerable source, Func predicate, T default_rv) { - if (source == null) throw new ArgumentNullException(nameof(source)); - foreach (T element in source) - if (predicate(element)) - return element; - return default_rv; - } - - public static T FirstOrDefault(this IEnumerable source, Func predicate, Func default_rv) { - if (source == null) throw new ArgumentNullException(nameof(source)); - foreach (T element in source) - if (predicate(element)) - return element; - return default_rv(); - } - - public static TResult SelectFirstOrDefault(this IEnumerable source, Func predicate, Func select) { - if (source == null) throw new ArgumentNullException(nameof(source)); - foreach (T element in source) - if (predicate(element)) - return select(element); - return default; - } - - public static TResult FirstOrDefault(this IEnumerable source, Func predicate, Func select, TResult default_rv) { - if (source == null) throw new ArgumentNullException(nameof(source)); - foreach (T element in source) - if (predicate(element)) - return select(element); - return default_rv; - } - - public static T FirstOrDefault(this IEnumerable source, params Func[] predicates_ordered_by_preference) { - foreach (var p in predicates_ordered_by_preference) { - foreach (var el in source) { - if (p(el)) - return el; - } - } - return default; - } - - public static T LastOrDefault(this IEnumerable source, T default_rv) { - if (source == null) throw new ArgumentNullException(nameof(source)); - var list = source as IList; - if (list != null) { - int count = list.Count; - if (count > 0) return list[count - 1]; - } else { - using (var e = source.GetEnumerator()) - if (e.MoveNext()) { - T result; - do result = e.Current; - while (e.MoveNext()); - return result; - } - } - return default_rv; - } - - public static T LastOrDefault(this IEnumerable source, Func predicate, T default_rv) { - if (source == null) throw new ArgumentNullException(nameof(source)); - if (predicate == null) throw new ArgumentNullException(nameof(predicate)); - T rv = default_rv; - foreach (T element in source) - if (predicate(element)) rv = element; - return rv; - } - - public static TResult LastOrDefault(this IEnumerable source, Func select, Func predicate) => - LastOrDefault(source, select, predicate, default); - - public static TResult LastOrDefault(this IEnumerable source, Func select, Func predicate, TResult default_rv) { - if (source == null) throw new ArgumentNullException(nameof(source)); - if (select == null) throw new ArgumentNullException(nameof(select)); - if (predicate == null) throw new ArgumentNullException(nameof(predicate)); - TResult rv = default_rv; - foreach (T element in source) { - TResult r = select(element); - if (predicate(r)) rv = r; - } - return rv; - } - - public static bool AtLeast(this IEnumerable source, int count) { - if (count < 1) - throw new ArgumentException("Cannot be less than 1.", nameof(count)); - int n = 0; - foreach (T item in source) { - if (++n == count) - return true; - } - return false; - } - - public static bool AtLeast(this IEnumerable source, int count, Func where) { - if (count < 1) - throw new ArgumentException("Cannot be less than 1.", nameof(count)); - int n = 0; - foreach (T item in source) { - if (where(item)) { - if (++n == count) - return true; - } - } - return false; - } - - /// - /// Simply returns enumerable.ToList(), under the guise ofo IReadOnlyList<> - /// - public static IReadOnlyList ToReadOnlyList(this IEnumerable enumerable) => - enumerable.ToList(); - - public static Dictionary ToDictionary(this IEnumerable> key_values) => - key_values.ToDictionary(kv => kv.Key, kv => kv.Value); - - public static Dictionary ToDictionaryCrushed(this IEnumerable source, Func key_selector) { - var rv = new Dictionary(); - foreach (T v in source) - rv[key_selector(v)] = v; - return rv; - } - - public static Dictionary ToDictionaryCrushed(this IEnumerable source, Func key_selector, Func element_selector) { - var rv = new Dictionary(); - foreach (T v in source) - rv[key_selector(v)] = element_selector(v); - return rv; - } - - public static ReadOnlyDictionary ToReadOnlyDictionary(this IEnumerable enumerable, Func key_selector) => - new ReadOnlyDictionary(enumerable.ToDictionary(key_selector)); - - public static ReadOnlyDictionary ToReadOnlyDictionary(this IEnumerable enumerable, Func key_selector, IEqualityComparer comparer) => - new ReadOnlyDictionary(enumerable.ToDictionary(key_selector, comparer)); - - public static ReadOnlyDictionary ToReadOnlyDictionary(this IEnumerable enumerable, Func key_selector, Func element_selector) => - new ReadOnlyDictionary(enumerable.ToDictionary(key_selector, element_selector)); - - public static ReadOnlyDictionary ToReadOnlyDictionary(this IEnumerable enumerable, Func key_selector, Func element_selector, IEqualityComparer comparer) => - new ReadOnlyDictionary(enumerable.ToDictionary(key_selector, element_selector, comparer)); - - public static ILookup ToFlatLookup(this IEnumerable source, Func key_selector, Func> selector) => - source.SelectMany(v => { - var k = key_selector(v); - return selector(v).Select(el => (k, el)); - }).ToLookup(t => t.k, t => t.el); - #region Min - public static T Min(this IEnumerable enumerable, Func select_value) where T : IComparable => - Min(enumerable, select_value, default(T)); - - public static T Min(this IEnumerable enumerable, Func select_value, T return_if_empty) where T : IComparable { - var etr = enumerable.GetEnumerator(); - if (!etr.MoveNext()) return return_if_empty; - T min = select_value(etr.Current); - while (etr.MoveNext()) { - T val = select_value(etr.Current); - if (val.CompareTo(min) == -1) min = val; - } - return min; - } - - public static T Min(this IEnumerable enumerable, Func select_value, Comparison comparison) => - Min(enumerable, select_value, comparison, default); - - public static T Min(this IEnumerable enumerable, Func select_value, Comparison comparison, T return_if_empty) { - var etr = enumerable.GetEnumerator(); - if (!etr.MoveNext()) return return_if_empty; - T min = select_value(etr.Current); - while (etr.MoveNext()) { - T val = select_value(etr.Current); - if (comparison(val, min) == -1) min = val; - } - return min; - } - #endregion - - #region MinElement - public static TElement MinElement(this IEnumerable enumerable, Func select_value) where T : IComparable => - MinElement(enumerable, select_value, default(TElement)); - - public static TElement MinElement(this IEnumerable enumerable, Func select_value, TElement return_if_empty) where T : IComparable { - var etr = enumerable.GetEnumerator(); - if (!etr.MoveNext()) return return_if_empty; - TElement min_el = etr.Current; - T min = select_value(min_el); - while (etr.MoveNext()) { - T val = select_value(etr.Current); - if (val.CompareTo(min) == -1) { - min_el = etr.Current; - min = val; - } - } - return min_el; - } - - public static TElement MinElement(this IEnumerable enumerable, Func select_value, Comparison comparison) => - MinElement(enumerable, select_value, comparison, default); - - public static TElement MinElement(this IEnumerable enumerable, Func select_value, Comparison comparison, TElement return_if_empty) { - var etr = enumerable.GetEnumerator(); - if (!etr.MoveNext()) return return_if_empty; - TElement min_el = etr.Current; - T min = select_value(etr.Current); - while (etr.MoveNext()) { - T val = select_value(etr.Current); - if (comparison(val, min) == -1) { - min_el = etr.Current; - min = val; - } - } - return min_el; - } - #endregion - - #region Max - public static T Max(this IEnumerable enumerable, Func select_value, T return_if_empty) where T : IComparable { - var etr = enumerable.GetEnumerator(); - if (!etr.MoveNext()) return return_if_empty; - T max = select_value(etr.Current); - while (etr.MoveNext()) { - T val = select_value(etr.Current); - if (val.CompareTo(max) == 1) max = val; - } - return max; - } - - public static T Max(this IEnumerable enumerable, Func select_value, Comparison comparison) => - Max(enumerable, select_value, comparison, default); - - - public static T Max(this IEnumerable enumerable, Func select_value, Comparison comparison, T return_if_empty) { - var etr = enumerable.GetEnumerator(); - if (!etr.MoveNext()) return return_if_empty; - T max = select_value(etr.Current); - while (etr.MoveNext()) { - T val = select_value(etr.Current); - if (comparison(val, max) == 1) max = val; - } - return max; - } - #endregion - - #region MaxElement - public static TElement MaxElement(this IEnumerable enumerable, Func select_value) where T : IComparable => - MaxElement(enumerable, select_value, default(TElement)); - - public static TElement MaxElement(this IEnumerable enumerable, Func select_value, TElement return_if_empty) where T : IComparable { - var etr = enumerable.GetEnumerator(); - if (!etr.MoveNext()) return return_if_empty; - TElement max_el = etr.Current; - T max = select_value(max_el); - while (etr.MoveNext()) { - T val = select_value(etr.Current); - if (val.CompareTo(max) == 1) { - max_el = etr.Current; - max = val; - } - } - return max_el; - } - - public static TElement MaxElement(this IEnumerable enumerable, Func select_value, Comparison comparison) => - MaxElement(enumerable, select_value, comparison, default); - - public static TElement MaxElement(this IEnumerable enumerable, Func select_value, Comparison comparison, TElement return_if_empty) { - var etr = enumerable.GetEnumerator(); - if (!etr.MoveNext()) return return_if_empty; - TElement max_el = etr.Current; - T max = select_value(etr.Current); - while (etr.MoveNext()) { - T val = select_value(etr.Current); - if (comparison(val, max) == 1) { - max_el = etr.Current; - max = val; - } - } - return max_el; - } - #endregion - - #region Sum - public static uint Sum(this IEnumerable enumerable, Func select) => - Sum(enumerable.Select(select)); - - public static uint Sum(this IEnumerable enumerable) { - uint sum = 0; - foreach (uint val in enumerable) sum += val; - return sum; - } - #endregion - - public static bool is_null_or_empty(this IEnumerable source) => - source == null || !source.Any(); - - public static IEnumerable empty_if_null(this IEnumerable source) => - source ?? Enumerable.Empty(); - - public static void DisposeAll(this IEnumerable source) { - foreach (IDisposable d in source) - d.Dispose(); - } - - public static IEnumerable return_if(bool condition, Func get_value) { - if (condition) - yield return get_value(); - } - - /// - /// Uses to convert the elements of an to the specified type. - /// - /// The type to convert the elements of source to. - /// The that contains the elements to be cast to type - /// An that contains each element of the source sequence cast to the specified type. - /// is null. - public static IEnumerable convert(this IEnumerable source) { - ExceptionAssert.Argument.NotNull(source, nameof(source)); - foreach (object obj in source) - yield return ConvertUtils.try_convert(obj); - } - } - - public static class CollectionExtensions - { - #region AddRange - public static void AddRange(this ICollection collection, params T[] items) { - foreach (T item in items) collection.Add(item); - } - - public static void AddRange(this ICollection collection, IEnumerable items) { - foreach (T item in items) collection.Add(item); - } - #endregion - - public static void SetItems(this ICollection collection, IEnumerable items) { - collection.Clear(); - collection.AddRange(items); - } - - public static bool within_range(this ICollection collection, int index) => - index >= 0 && index < collection.Count; - - public static bool within_range(this T[] array, int index) => - index >= 0 && index < array.Length; - - public static T at_or_nearest(this T[] array, int index) { - if (index < 0) { - return array.Length > 0 ? array[0] : default; - } else if (index >= array.Length) { - return array[array.Length - 1]; - } else return array[index]; - } - - public static bool try_get_at_index(this T[] array, int index, out T result) { - if (array.within_range(index)) { - result = array[index]; - return true; - } - result = default; - return false; - } - - public static bool TryGetItem(this KeyedCollection keyed_collection, TKey key, out TItem result) { - if (keyed_collection.Contains(key)) { - result = keyed_collection[key]; - return true; - } - result = default; - return false; - } - } - - public static class ListExtensions - { - #region InserSorted - public static void InsertSorted(this IList list, T item) => - list.InsertSorted(item, Comparer.Default); - - public static void InsertSorted(this IList list, T item, IComparer comparer) { - for (int i = 0; i < list.Count; i++) - if (comparer.Compare(list[i], item) > 0) { - list.Insert(i, item); - return; - } - list.Add(item); - } - #endregion - - #region Pop - public static T Pop(this IList list, int index) { - T rv = list.ElementAt(index); - list.RemoveAt(index); - return rv; - } - - public static bool Pop(this IList list, TKey key, Func key_selector, out T result) { - for(int i = 0; i < list.Count; i++) { - if (key_selector(list[i]).Equals(key)) { - result = list[i]; - return true; - } - } - result = default(T); - return false; - } - #endregion - - public static bool PopDispose(this IList list, TKey key, Func key_selector) where T : IDisposable { - if (list.Pop(key, key_selector, out T result)) { - result.Dispose(); - return true; - } - return false; - } - - public static bool IsNullOrEmpty(IList source) => - source == null || source.Count == 0; - } -} - -namespace System.Collections.ObjectModel -{ - public static class ObservableCollectionExtensions - { - public static int RemoveAll(this ObservableCollection collection, Func match) { - if (collection == null) return 0; - // In terms of allocations we could do this more efficiently by copying items from the end of the - // collection in (see https://referencesource.microsoft.com/#q=RemoveAll) but that would allow - // transient duplication in the list which could be observed from the outside - // Better to generate Remove events rather than move+delete events - var to_remove = collection.Where(match).ToList(); - foreach (var item in to_remove) { - collection.Remove(item); - } - return to_remove.Count; - } - - public static void ReflectChange(this ObservableCollection target, IEnumerable source, Func create_item, NotifyCollectionChangedEventArgs e) => - ReflectChange(target, source, create_item, null, e); - - public static void ReflectChange(this ObservableCollection target, IEnumerable source, Func create_item, Action item_destroyed, NotifyCollectionChangedEventArgs e) { - try { - switch (e.Action) { - case NotifyCollectionChangedAction.Add: - int i = e.NewStartingIndex; - foreach (TData d in e.NewItems) { - T item = create_item(d); - target.Insert(i++, item); - } - break; - case NotifyCollectionChangedAction.Move: target.Move(e.OldStartingIndex, e.NewStartingIndex); break; - case NotifyCollectionChangedAction.Remove: - for (int x = 0; x < e.OldItems.Count; x++) { - T item = target[e.OldStartingIndex]; - target.RemoveAt(e.OldStartingIndex); - item_destroyed?.Invoke(item); - } - break; - case NotifyCollectionChangedAction.Replace: - i = e.NewStartingIndex; - foreach (TData d in e.NewItems) { - T old_item = target[i]; - target[i++] = create_item(d); - item_destroyed?.Invoke(old_item); - } - break; - case NotifyCollectionChangedAction.Reset: - var old_views = target.ToArray(); - target.Clear(); - if (item_destroyed != null) foreach (T item in old_views) item_destroyed(item); - foreach (TData d in source) target.Add(create_item(d)); - break; - } - }catch (Exception ex) { - if (ex == null) { - - } - } - } - - public static IList AsList(this ObservableCollection collection) => collection; - - public static IObservable> ObserveSelf(this ObservableCollection collection) => - Observable.FromEvent(cb => (s, e) => cb(e), h => collection.CollectionChanged += h, h => collection.CollectionChanged -= h).Select(_ => collection); - - public static IObservable> ObserveSelf(this ObservableCollection collection, bool start_with_current) { - var src = ObserveSelf(collection); - return start_with_current? src.StartWith(collection) : src; - } - } -} - -namespace mbts.collections.extensions { - public static class HashSetExtensions { - public static void reflect_change(this HashSet self, IEnumerable source, NotifyCollectionChangedEventArgs e) { - ExceptionAssert.Argument.NotNull(source, nameof(source)); - ExceptionAssert.Argument.NotNull(self, nameof(self)); - switch (e.Action) { - case NotifyCollectionChangedAction.Add: - foreach (T item in e.NewItems) - self.Add(item); - break; - case NotifyCollectionChangedAction.Remove: - foreach (T item in e.OldItems) - self.Remove(item); - break; - case NotifyCollectionChangedAction.Replace: - foreach (T item in e.OldItems) - self.Remove(item); - foreach (T item in e.NewItems) - self.Add(item); - break; - case NotifyCollectionChangedAction.Reset: - self.Clear(); - foreach (T item in source) - self.Add(item); - break; - } - } - } - - public static class DictionaryExtensions - { - #region GetValueOrDefault - public static TValue GetValueOrDefault(this IReadOnlyDictionary dictionary, TKey key) => - dictionary.TryGetValue(key, out TValue result) ? result : default; - - public static TValue GetValueOrDefault(this IDictionary dictionary, TKey key) => - dictionary.TryGetValue(key, out TValue result) ? result : default; - - public static TValue GetValueOrDefault(this IDictionary dictionary, TKey key, TValue default_value) => - dictionary.TryGetValue(key, out TValue result) ? result : default_value; - - public static TValue GetValueOrDefault(this IDictionary dictionary, TKey key, Func default_factory) => - dictionary.TryGetValue(key, out TValue result) ? result : default_factory(key); - - public static TValue GetValueOrDefault(this Dictionary dictionary, TKey key) => - dictionary.TryGetValue(key, out TValue result) ? result : default; - - #endregion - - public static TValue? GetNullable(this IDictionary dictionary, TKey key) where TValue : struct { - if (dictionary.TryGetValue(key, out TValue result)) - return result; - else return null; - } - - public static void AddOrUpdate(this IDictionary dictionary, TKey key, Action update_existing, Func create_new) { - if (dictionary.TryGetValue(key, out TValue curr)) update_existing(curr); - else dictionary.Add(key, create_new()); - } - - public static void sync_with( - this IDictionary dictionary, - Dictionary source, - Func selector - ) => _sync_with(dictionary, source, selector); - - public static void sync_with( - this IDictionary dictionary, - IDictionary source, - Func selector - ) => _sync_with(dictionary, source, selector); - - public static void sync_with( - this IDictionary dictionary, - IReadOnlyDictionary source, - Func selector - ) => _sync_with_ro(dictionary, source, selector); - - public static void sync_with_demux( - this IDictionary dictionary, - Dictionary source, - Func, TKey> key_selector, - Func>, TValue> value_selector, - Action, IEnumerable>> update - ) => _sync_with_demux(dictionary, source, key_selector, value_selector, update); - - public static void sync_with_demux( - this IDictionary dictionary, - IDictionary source, - Func, TKey> key_selector, - Func>, TValue> value_selector, - Action, IEnumerable>> update - ) => _sync_with_demux(dictionary, source, key_selector, value_selector, update); - - public static void sync_with_demux( - this IDictionary dictionary, - IReadOnlyDictionary source, - Func, TKey> key_selector, - Func>, TValue> value_selector, - Action, IEnumerable>> update - ) => _sync_with_demux_ro(dictionary, source, key_selector, value_selector, update); - - static void _sync_with(IDictionary dictionary, IDictionary source, Func selector) { - var removes = dictionary.Keys.Except(source.Keys).ToList(); - foreach (var k in removes) - dictionary.Remove(k); - var adds = source.Except(dictionary.Keys, kv => kv.Key).ToList(); - foreach (var kv in adds) - dictionary.Add(kv.Key, selector(kv.Key, kv.Value)); - } - - static void _sync_with_ro(IDictionary dictionary, IReadOnlyDictionary source, Func selector) { - var removes = dictionary.Keys.Except(source.Keys).ToList(); - foreach (var k in removes) - dictionary.Remove(k); - var adds = source.Except(dictionary.Keys, kv => kv.Key).ToList(); - foreach (var kv in adds) - dictionary.Add(kv.Key, selector(kv.Key, kv.Value)); - } - - static void _sync_with_demux( - IDictionary dictionary, - IDictionary source, - Func, TKey> key_selector, - Func>, TValue> value_selector, - Action, IEnumerable>> update) { - var source_lookup = source.ToLookup(key_selector); - HashSet changes = new HashSet(), removes = new HashSet(); - foreach (var kv in dictionary) { - if (source_lookup.TryGetValue(kv.Key, out IEnumerable> result)) { - update(kv, result); - changes.Add(kv.Key); - } else { - removes.Add(kv.Key); - } - } - foreach (var k in removes) - dictionary.Remove(k); - foreach (var g in source_lookup) { - if (!changes.Contains(g.Key)) - dictionary.Add(g.Key, value_selector(g)); - } - } - - static void _sync_with_demux_ro( - IDictionary dictionary, - IReadOnlyDictionary source, - Func, TKey> key_selector, - Func>, TValue> value_selector, - Action, IEnumerable>> update - ) { - var source_lookup = source.ToLookup(key_selector); - HashSet changes = new HashSet(), removes = new HashSet(); - foreach (var kv in dictionary) { - if (source_lookup.TryGetValue(kv.Key, out IEnumerable> result)) { - update(kv, result); - changes.Add(kv.Key); - } else { - removes.Add(kv.Key); - } - } - foreach (var k in removes) - dictionary.Remove(k); - foreach (var g in source_lookup) { - if (!changes.Contains(g.Key)) - dictionary.Add(g.Key, value_selector(g)); - } - } - } +using bts.utils; +using mbts.utils; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.Reactive.Linq; + +namespace System.Collections.Generic { + public static class EnumerableExtensions { + #region Ordered + public static IOrderedEnumerable Ordered(this IEnumerable enumerable) => + enumerable.OrderBy(t => t); + + public static IEnumerable Ordered(this IEnumerable enumerable, Func compare) => + enumerable.Ordered(Comparer.Create(new Comparison(compare))); + + public static IEnumerable Ordered(this IEnumerable enumerable, IComparer comparer) => + enumerable.OrderBy(t => t, comparer); + #endregion + + public static IEnumerable DistinctOn(this IEnumerable enumerable, Func key_selector) => + enumerable.Distinct(EqualityComparer.Create((x, y) => key_selector(x).Equals(key_selector(y)), x => key_selector(x).GetHashCode())); + + public static IEnumerable Except(this IEnumerable enumerable, IEnumerable second, Func key_selector) => + enumerable.Where(t => !second.Contains(key_selector(t))); + + public static IEnumerable Intersect(this IEnumerable enumerable, IEnumerable second, Func key_selector) => + enumerable.Where(t => second.Contains(key_selector(t))); + + public static IEnumerable OfTypeSafe(this IEnumerable source) => + source == null ? Enumerable.Empty() : source.OfType(); + + public static TAccumulate AggregateWhile(this IEnumerable source, TAccumulate seed, Func aggregate, Func predicate) => + AggregateWhile(source, seed, aggregate, predicate, (curr, el, next) => curr); + + public static TAccumulate AggregateWhile(this IEnumerable source, TAccumulate seed, Func aggregate, Func predicate, TAccumulate early_break_rv) => + AggregateWhile(source, seed, aggregate, predicate, (curr, el, next) => early_break_rv); + + public static TAccumulate AggregateWhile(this IEnumerable source, TAccumulate seed, Func aggregate, Func predicate, Func sanitize_on_early_break) { + TAccumulate rv = seed; + foreach (T el in source) { + var next = aggregate(rv, el); + if (predicate(next, el)) + rv = next; + else return sanitize_on_early_break(rv, el, next); + } + return rv; + } + + public static bool CountAtLeast(this IEnumerable source, int count) { + if (count < 0) + throw new ArgumentException(ExceptionBuilder.Format.LessThan(0), nameof(count)); + if (count == 0) + return true; + foreach (var v in source) { + if (--count == 0) + return true; + } + return false; + } + + public static bool CountAtMost(this IEnumerable source, int count) { + if (count < 0) + throw new ArgumentException(ExceptionBuilder.Format.LessThan(0), nameof(count)); + foreach (var v in source) { + if (--count == -1) + return false; + } + return true; + } + + public static IEnumerable Convert(this IEnumerable source) { + foreach (var v in source) + yield return ConvertUtils.try_convert(v); + } + + public static IEnumerable ExceptNull(this IEnumerable source) where T : class { + foreach (var v in source) { + if (v != null) + yield return v; + } + } + + /// + /// Checks if implements or . If so, the resultant Count is returned, otherwise null (will not enumerate through any items). + /// + /// The type of elements of source. + /// A sequence that contains elements to be counted, if possible without enumeration. + /// The number of elements in the input sequence, if the sequence implemented or , otherwise null. + public static int? SoftCount(this IEnumerable source) => + new EnumerableCount(source).Count; + + // use "new [] { item }" - avoid putting this on the intellisense for every item everywhere + //public static IEnumerable ToIEnumerable(this T item) { + // yield return item; + //} + + public static T SafeSingleOrDefault(this IEnumerable source) { + using (var en = source.GetEnumerator()) { + if (en.MoveNext()) { + var rv_candidate = en.Current; + if (!en.MoveNext()) + return rv_candidate; + } + } + return default; + } + + public static T SafeSingleOrDefault(this IEnumerable source, T default_value) { + using (var en = source.GetEnumerator()) { + if (en.MoveNext()) { + var rv_candidate = en.Current; + if (!en.MoveNext()) + return rv_candidate; + } + } + return default_value; + } + + public static IEnumerable TakeWhile(this IEnumerable source, TAccumulate seed, Func accumulate, Func predicate) { + TAccumulate a = seed; + foreach (T el in source) { + if (!predicate(a, el)) + break; + a = accumulate(a, el); + yield return el; + } + } + + public static bool TryGetFirst(this IEnumerable source, out T result) { + if (source == null) throw new ArgumentNullException(nameof(source)); + using (var en = source.GetEnumerator()) { + if (en.MoveNext()) { + result = en.Current; + return true; + } + } + result = default; + return false; + } + + public static bool TryGetFirst(this IEnumerable source, Func predicate, out T result) { + if (source == null) throw new ArgumentNullException(nameof(source)); + foreach (T element in source) + if (predicate(element)) { + result = element; + return true; + } + result = default; + return false; + } + + public static bool TryGetFirst(this IEnumerable source, Func predicate, Func select, out TResult result) { + if (source == null) throw new ArgumentNullException(nameof(source)); + foreach (T element in source) + if (predicate(element)) { + result = select(element); + return true; + } + result = default; + return false; + } + + public static bool TryGetSingle(this IEnumerable source, out T result) { + if (source == null) throw new ArgumentNullException(nameof(source)); + using (var en = source.GetEnumerator()) { + if (en.MoveNext()) { + result = en.Current; + if (!en.MoveNext()) + return true; + } + } + result = default; + return false; + } + + public static bool TryGetSingle(this IEnumerable source, Func predicate, Func convert, out TResult result) { + if (TryGetSingle(source.Where(predicate), out T v)) { + result = convert(v); + return true; + } + result = default; + return false; + } + + public static T FirstOrDefault(this IEnumerable source, Func predicate, T default_rv) { + if (source == null) throw new ArgumentNullException(nameof(source)); + foreach (T element in source) + if (predicate(element)) + return element; + return default_rv; + } + + public static T FirstOrDefault(this IEnumerable source, Func predicate, Func default_rv) { + if (source == null) throw new ArgumentNullException(nameof(source)); + foreach (T element in source) + if (predicate(element)) + return element; + return default_rv(); + } + + public static TResult SelectFirstOrDefault(this IEnumerable source, Func predicate, Func select) { + if (source == null) throw new ArgumentNullException(nameof(source)); + foreach (T element in source) + if (predicate(element)) + return select(element); + return default; + } + + public static TResult FirstOrDefault(this IEnumerable source, Func predicate, Func select, TResult default_rv) { + if (source == null) throw new ArgumentNullException(nameof(source)); + foreach (T element in source) + if (predicate(element)) + return select(element); + return default_rv; + } + + public static T FirstOrDefault(this IEnumerable source, params Func[] predicates_ordered_by_preference) { + foreach (var p in predicates_ordered_by_preference) { + foreach (var el in source) { + if (p(el)) + return el; + } + } + return default; + } + + public static T LastOrDefault(this IEnumerable source, T default_rv) { + if (source == null) throw new ArgumentNullException(nameof(source)); + var list = source as IList; + if (list != null) { + int count = list.Count; + if (count > 0) return list[count - 1]; + } else { + using (var e = source.GetEnumerator()) + if (e.MoveNext()) { + T result; + do result = e.Current; + while (e.MoveNext()); + return result; + } + } + return default_rv; + } + + public static T LastOrDefault(this IEnumerable source, Func predicate, T default_rv) { + if (source == null) throw new ArgumentNullException(nameof(source)); + if (predicate == null) throw new ArgumentNullException(nameof(predicate)); + T rv = default_rv; + foreach (T element in source) + if (predicate(element)) rv = element; + return rv; + } + + public static TResult LastOrDefault(this IEnumerable source, Func select, Func predicate) => + LastOrDefault(source, select, predicate, default); + + public static TResult LastOrDefault(this IEnumerable source, Func select, Func predicate, TResult default_rv) { + if (source == null) throw new ArgumentNullException(nameof(source)); + if (select == null) throw new ArgumentNullException(nameof(select)); + if (predicate == null) throw new ArgumentNullException(nameof(predicate)); + TResult rv = default_rv; + foreach (T element in source) { + TResult r = select(element); + if (predicate(r)) rv = r; + } + return rv; + } + + public static bool AtLeast(this IEnumerable source, int count) { + if (count < 1) + throw new ArgumentException("Cannot be less than 1.", nameof(count)); + int n = 0; + foreach (T item in source) { + if (++n == count) + return true; + } + return false; + } + + public static bool AtLeast(this IEnumerable source, int count, Func where) { + if (count < 1) + throw new ArgumentException("Cannot be less than 1.", nameof(count)); + int n = 0; + foreach (T item in source) { + if (where(item)) { + if (++n == count) + return true; + } + } + return false; + } + + /// + /// Simply returns enumerable.ToList(), under the guise ofo IReadOnlyList<> + /// + public static IReadOnlyList ToReadOnlyList(this IEnumerable enumerable) => + enumerable.ToList(); + + public static Dictionary ToDictionary(this IEnumerable> key_values) => + key_values.ToDictionary(kv => kv.Key, kv => kv.Value); + + public static Dictionary ToDictionaryCrushed(this IEnumerable source, Func key_selector) { + var rv = new Dictionary(); + foreach (T v in source) + rv[key_selector(v)] = v; + return rv; + } + + public static Dictionary ToDictionaryCrushed(this IEnumerable source, Func key_selector, Func element_selector) { + var rv = new Dictionary(); + foreach (T v in source) + rv[key_selector(v)] = element_selector(v); + return rv; + } + + public static ReadOnlyDictionary ToReadOnlyDictionary(this IEnumerable enumerable, Func key_selector) => + new ReadOnlyDictionary(enumerable.ToDictionary(key_selector)); + + public static ReadOnlyDictionary ToReadOnlyDictionary(this IEnumerable enumerable, Func key_selector, IEqualityComparer comparer) => + new ReadOnlyDictionary(enumerable.ToDictionary(key_selector, comparer)); + + public static ReadOnlyDictionary ToReadOnlyDictionary(this IEnumerable enumerable, Func key_selector, Func element_selector) => + new ReadOnlyDictionary(enumerable.ToDictionary(key_selector, element_selector)); + + public static ReadOnlyDictionary ToReadOnlyDictionary(this IEnumerable enumerable, Func key_selector, Func element_selector, IEqualityComparer comparer) => + new ReadOnlyDictionary(enumerable.ToDictionary(key_selector, element_selector, comparer)); + + public static ILookup ToFlatLookup(this IEnumerable source, Func key_selector, Func> selector) => + source.SelectMany(v => { + var k = key_selector(v); + return selector(v).Select(el => (k, el)); + }).ToLookup(t => t.k, t => t.el); + #region Min + public static T Min(this IEnumerable enumerable, Func select_value) where T : IComparable => + Min(enumerable, select_value, default(T)); + + public static T Min(this IEnumerable enumerable, Func select_value, T return_if_empty) where T : IComparable { + var etr = enumerable.GetEnumerator(); + if (!etr.MoveNext()) return return_if_empty; + T min = select_value(etr.Current); + while (etr.MoveNext()) { + T val = select_value(etr.Current); + if (val.CompareTo(min) == -1) min = val; + } + return min; + } + + public static T Min(this IEnumerable enumerable, Func select_value, Comparison comparison) => + Min(enumerable, select_value, comparison, default); + + public static T Min(this IEnumerable enumerable, Func select_value, Comparison comparison, T return_if_empty) { + var etr = enumerable.GetEnumerator(); + if (!etr.MoveNext()) return return_if_empty; + T min = select_value(etr.Current); + while (etr.MoveNext()) { + T val = select_value(etr.Current); + if (comparison(val, min) == -1) min = val; + } + return min; + } + #endregion + + #region MinElement + public static TElement MinElement(this IEnumerable enumerable, Func select_value) where T : IComparable => + MinElement(enumerable, select_value, default(TElement)); + + public static TElement MinElement(this IEnumerable enumerable, Func select_value, TElement return_if_empty) where T : IComparable { + var etr = enumerable.GetEnumerator(); + if (!etr.MoveNext()) return return_if_empty; + TElement min_el = etr.Current; + T min = select_value(min_el); + while (etr.MoveNext()) { + T val = select_value(etr.Current); + if (val.CompareTo(min) == -1) { + min_el = etr.Current; + min = val; + } + } + return min_el; + } + + public static TElement MinElement(this IEnumerable enumerable, Func select_value, Comparison comparison) => + MinElement(enumerable, select_value, comparison, default); + + public static TElement MinElement(this IEnumerable enumerable, Func select_value, Comparison comparison, TElement return_if_empty) { + var etr = enumerable.GetEnumerator(); + if (!etr.MoveNext()) return return_if_empty; + TElement min_el = etr.Current; + T min = select_value(etr.Current); + while (etr.MoveNext()) { + T val = select_value(etr.Current); + if (comparison(val, min) == -1) { + min_el = etr.Current; + min = val; + } + } + return min_el; + } + #endregion + + #region Max + public static T Max(this IEnumerable enumerable, Func select_value, T return_if_empty) where T : IComparable { + var etr = enumerable.GetEnumerator(); + if (!etr.MoveNext()) return return_if_empty; + T max = select_value(etr.Current); + while (etr.MoveNext()) { + T val = select_value(etr.Current); + if (val.CompareTo(max) == 1) max = val; + } + return max; + } + + public static T Max(this IEnumerable enumerable, Func select_value, Comparison comparison) => + Max(enumerable, select_value, comparison, default); + + + public static T Max(this IEnumerable enumerable, Func select_value, Comparison comparison, T return_if_empty) { + var etr = enumerable.GetEnumerator(); + if (!etr.MoveNext()) return return_if_empty; + T max = select_value(etr.Current); + while (etr.MoveNext()) { + T val = select_value(etr.Current); + if (comparison(val, max) == 1) max = val; + } + return max; + } + #endregion + + #region MaxElement + public static TElement MaxElement(this IEnumerable enumerable, Func select_value) where T : IComparable => + MaxElement(enumerable, select_value, default(TElement)); + + public static TElement MaxElement(this IEnumerable enumerable, Func select_value, TElement return_if_empty) where T : IComparable { + var etr = enumerable.GetEnumerator(); + if (!etr.MoveNext()) return return_if_empty; + TElement max_el = etr.Current; + T max = select_value(max_el); + while (etr.MoveNext()) { + T val = select_value(etr.Current); + if (val.CompareTo(max) == 1) { + max_el = etr.Current; + max = val; + } + } + return max_el; + } + + public static TElement MaxElement(this IEnumerable enumerable, Func select_value, Comparison comparison) => + MaxElement(enumerable, select_value, comparison, default); + + public static TElement MaxElement(this IEnumerable enumerable, Func select_value, Comparison comparison, TElement return_if_empty) { + var etr = enumerable.GetEnumerator(); + if (!etr.MoveNext()) return return_if_empty; + TElement max_el = etr.Current; + T max = select_value(etr.Current); + while (etr.MoveNext()) { + T val = select_value(etr.Current); + if (comparison(val, max) == 1) { + max_el = etr.Current; + max = val; + } + } + return max_el; + } + #endregion + + #region Sum + public static uint Sum(this IEnumerable enumerable, Func select) => + Sum(enumerable.Select(select)); + + public static uint Sum(this IEnumerable enumerable) { + uint sum = 0; + foreach (uint val in enumerable) sum += val; + return sum; + } + #endregion + + public static bool is_null_or_empty(this IEnumerable source) => + source == null || !source.Any(); + + public static IEnumerable empty_if_null(this IEnumerable source) => + source ?? Enumerable.Empty(); + + public static void DisposeAll(this IEnumerable source) { + foreach (IDisposable d in source) + d.Dispose(); + } + + public static IEnumerable return_if(bool condition, Func get_value) { + if (condition) + yield return get_value(); + } + + /// + /// Uses to convert the elements of an to the specified type. + /// + /// The type to convert the elements of source to. + /// The that contains the elements to be cast to type + /// An that contains each element of the source sequence cast to the specified type. + /// is null. + public static IEnumerable convert(this IEnumerable source) { + ExceptionAssert.Argument.NotNull(source, nameof(source)); + foreach (object obj in source) + yield return ConvertUtils.try_convert(obj); + } + + struct EnumerableCount { + readonly ICollection _collection; + readonly IReadOnlyCollection _ro_collection; + + public EnumerableCount(IEnumerable source) { + _collection = source as ICollection; + _ro_collection = _collection == null ? source as IReadOnlyCollection : null; + } + + public int? Count => _collection?.Count ?? _ro_collection?.Count; + } + } } \ No newline at end of file diff --git a/src/client/spark_core/Collections/Extensions/ILookupExtensions.cs b/src/client/spark_core/Collections/Extensions/ILookupExtensions.cs new file mode 100644 index 000000000..3171c587e --- /dev/null +++ b/src/client/spark_core/Collections/Extensions/ILookupExtensions.cs @@ -0,0 +1,14 @@ +using System.Collections.Generic; +using System.Linq; + +namespace bts.collections { + public static class ILookupExtensions { + public static bool TryGetValue(this ILookup self, TKey key, out IEnumerable value) { + bool has_value = self.Contains(key); + if (has_value) { + value = self[key]; + } else { value = Enumerable.Empty(); } + return has_value; + } + } +} \ No newline at end of file diff --git a/src/client/spark_core/Collections/Extensions/ListExtensions.cs b/src/client/spark_core/Collections/Extensions/ListExtensions.cs index 54a3aa42c..00ab07626 100644 --- a/src/client/spark_core/Collections/Extensions/ListExtensions.cs +++ b/src/client/spark_core/Collections/Extensions/ListExtensions.cs @@ -5,6 +5,58 @@ using System.Linq; namespace bts.collections { public static class ListExtensions { + public static void InsertSorted(this IList list, T item) => + list.InsertSorted(item, Comparer.Default); + + public static void InsertSorted(this IList list, T item, IComparer comparer) { + for (int i = 0; i < list.Count; i++) + if (comparer.Compare(list[i], item) > 0) { + list.Insert(i, item); + return; + } + list.Add(item); + } + + public static void InsertSorted(this List list, T value, IComparer comparer) { + int i = list.BinarySearch(value, comparer); + list.Insert(i < 0 ? ~i : i, value); + } + + public static T Pop(this IList list, int index) { + T rv = list.ElementAt(index); + list.RemoveAt(index); + return rv; + } + + public static bool Pop(this IList list, TKey key, Func key_selector, out T result) { + for(int i = 0; i < list.Count; i++) { + if (key_selector(list[i]).Equals(key)) { + result = list[i]; + return true; + } + } + result = default(T); + return false; + } + + public static bool PopDispose(this IList list, TKey key, Func key_selector) where T : IDisposable { + if (list.Pop(key, key_selector, out T result)) { + result.Dispose(); + return true; + } + return false; + } + + public static bool IsNullOrEmpty(this IList source) => + source == null || source.Count == 0; + + public static IEnumerable ExceptAt(this List list, int index) { + for (int i = 0; i < index; i++) + yield return list[i]; + for (int i = index + 1; i < list.Count; i++) + yield return list[i]; + } + public static void RemoveWhere(this IList list, Func where) { foreach (var r in list.Where(where).ToList()) list.Remove(r); } public static void RemoveWhere(this IList list, Func where, Action on_remove) { @@ -19,6 +71,18 @@ namespace bts.collections { } } + public static bool TryGetAt(this IList list, int index, out T value) { + if (index >= 0 && index < list.Count) { + value = list[index]; + return true; + } + value = default; + return false; + } + + public static IList WrapValue(T value) => + new ValueListWrapper(value); + public static IList WrapType(this IList list) => new TypeWrapper(list); @@ -62,6 +126,36 @@ namespace bts.collections { return -1; } + // unlike new T[] { value }, this struct prohibits changing the value at index 0. + struct ValueListWrapper : IList { + readonly T _value; + + public ValueListWrapper(T value) => + _value = value; + + public T this[int index] { + get => index == 0 ? _value : throw new IndexOutOfRangeException(); + set => throw new NotSupportedException(); + } + public int Count => 1; + public bool IsReadOnly => true; + + void ICollection.Add(T item) => throw new NotSupportedException(); + void ICollection.Clear() => throw new NotSupportedException(); + public bool Contains(T item) => _value.Equals(item); + public void CopyTo(T[] array, int arrayIndex) => array[arrayIndex] = _value; + public IEnumerator GetEnumerator() { + yield return _value; + } + public int IndexOf(T item) => _value.Equals(item) ? 0 : -1; + void IList.Insert(int index, T item) => throw new NotSupportedException(); + bool ICollection.Remove(T item) => throw new NotSupportedException(); + void IList.RemoveAt(int index) => throw new NotSupportedException(); + IEnumerator IEnumerable.GetEnumerator() { + yield return _value; + } + } + class TypeWrapper : IList, IReadOnlyList { readonly IList _source; diff --git a/src/client/spark_core/Collections/Extensions/ObservableCollectionExtensions.cs b/src/client/spark_core/Collections/Extensions/ObservableCollectionExtensions.cs new file mode 100644 index 000000000..33563d299 --- /dev/null +++ b/src/client/spark_core/Collections/Extensions/ObservableCollectionExtensions.cs @@ -0,0 +1,71 @@ +using System.Collections.Generic; +using System.Collections.Specialized; +using System.Linq; +using System.Reactive.Linq; + +namespace System.Collections.ObjectModel { + static class ObservableCollectionExtensions { + public static int RemoveAll(this ObservableCollection collection, Func match) { + if (collection == null) return 0; + // In terms of allocations we could do this more efficiently by copying items from the end of the + // collection in (see https://referencesource.microsoft.com/#q=RemoveAll) but that would allow + // transient duplication in the list which could be observed from the outside + // Better to generate Remove events rather than move+delete events + var to_remove = collection.Where(match).ToList(); + foreach (var item in to_remove) { + collection.Remove(item); + } + return to_remove.Count; + } + + public static void ReflectChange(this ObservableCollection target, IEnumerable source, Func create_item, NotifyCollectionChangedEventArgs e) => + ReflectChange(target, source, create_item, null, e); + + // TODO: remove this try/catch. first, must make sure that this isn't hiding any bugs. + public static void ReflectChange(this ObservableCollection target, IEnumerable source, Func create_item, Action item_destroyed, NotifyCollectionChangedEventArgs e) { + try { + switch (e.Action) { + case NotifyCollectionChangedAction.Add: + int i = e.NewStartingIndex; + foreach (TData d in e.NewItems) { + T item = create_item(d); + target.Insert(i++, item); + } + break; + case NotifyCollectionChangedAction.Move: target.Move(e.OldStartingIndex, e.NewStartingIndex); break; + case NotifyCollectionChangedAction.Remove: + for (int x = 0; x < e.OldItems.Count; x++) { + T item = target[e.OldStartingIndex]; + target.RemoveAt(e.OldStartingIndex); + item_destroyed?.Invoke(item); + } + break; + case NotifyCollectionChangedAction.Replace: + i = e.NewStartingIndex; + foreach (TData d in e.NewItems) { + T old_item = target[i]; + target[i++] = create_item(d); + item_destroyed?.Invoke(old_item); + } + break; + case NotifyCollectionChangedAction.Reset: + var old_views = target.ToArray(); + target.Clear(); + if (item_destroyed != null) foreach (T item in old_views) item_destroyed(item); + foreach (TData d in source) target.Add(create_item(d)); + break; + } + } catch { } + } + + public static IList AsList(this ObservableCollection collection) => collection; + + public static IObservable> ObserveSelf(this ObservableCollection collection) => + Observable.FromEvent(cb => (s, e) => cb(e), h => collection.CollectionChanged += h, h => collection.CollectionChanged -= h).Select(_ => collection); + + public static IObservable> ObserveSelf(this ObservableCollection collection, bool start_with_current) { + var src = ObserveSelf(collection); + return start_with_current? src.StartWith(collection) : src; + } + } +} diff --git a/src/client/spark_core/Collections/IObservableCollection.cs b/src/client/spark_core/Collections/IObservableCollection.cs new file mode 100644 index 000000000..99e4fdabd --- /dev/null +++ b/src/client/spark_core/Collections/IObservableCollection.cs @@ -0,0 +1,7 @@ +using System.Collections.Generic; +using System.Collections.Specialized; + +namespace bts.collections { + interface IReadOnlyObservableCollection : IReadOnlyList, IReadOnlyCollection, INotifyCollectionChanged { } + interface IObservableCollection : IList, INotifyCollectionChanged { } +} \ No newline at end of file diff --git a/src/client/spark_core/Collections/KeyedCollection.cs b/src/client/spark_core/Collections/KeyedCollection.cs new file mode 100644 index 000000000..7d21557c0 --- /dev/null +++ b/src/client/spark_core/Collections/KeyedCollection.cs @@ -0,0 +1,153 @@ +using mbts.utils; +using System; +using System.Collections; +using System.Collections.Generic; + +namespace bts.collections { + class KeyedCollection : IList, IList, IDictionary { + readonly Dictionary _dictionary; + readonly List _list = new List(); + readonly Func _key; + readonly IEqualityComparer _key_comparer; + IDictionary _idict_backing; + + public KeyedCollection(Func key) + : this(key, EqualityComparer.Default) { } + + public KeyedCollection(Func key, IEqualityComparer key_comparer) { + _key = key; + _dictionary = new Dictionary(_key_comparer = key_comparer); + } + + public T this[int index] { get => _list[index]; set => _list[index] = value; } + public int Count => _list.Count; + public bool IsReadOnly => false; + // avoid casting more than once + IDictionary _idict => _idict_backing ?? (_idict_backing = _dictionary); + + public void Add(T item) { + _dictionary.Add(_key(item), item); + _list.Add(item); + } + public IDictionary AsDictionary() => this; + public void Clear() { + _dictionary.Clear(); + _list.Clear(); + } + public bool Contains(T item) => _dictionary.ContainsKey(_key(item)); + public void CopyTo(T[] array, int arrayIndex) => _list.CopyTo(array, arrayIndex); + public IEnumerator GetEnumerator() => _list.GetEnumerator(); + public int IndexOf(T item) { + var k = _key(item); + if (_dictionary.ContainsKey(k)) { + for (int i = 0; i < _list.Count; i++) { + if (_key_comparer.Equals(k, _key(_list[i]))) + return i; + } + } + return -1; + } + public void Insert(int index, T item) { + _dictionary.Add(_key(item), item); + _list.Insert(index, item); + } + public bool Remove(T item) { + var k = _key(item); + if (_dictionary.Remove(k)) { + for (int i = 0; i < _list.Count; i++) { + if (_key_comparer.Equals(k, _key(_list[i]))) { + _list.RemoveAt(i); + return true; + } + } + throw _out_of_sync_ex(); + } + return false; + } + + public void RemoveAt(int index) { + var k = _key(_list[index]); + if (!_dictionary.Remove(_key(_list[index]))) + throw _out_of_sync_ex(); + _list.RemoveAt(index); + } + + #region IList (non-generic) members + object IList.this[int index] { + get => this[index]; + set => this[index] = ExceptionAssert.Argument.Is(value, nameof(value)); + } + int IList.Add(object value) { + Add(ExceptionAssert.Argument.Is(value, nameof(value))); + return Count - 1; + } + bool IList.Contains(object value) => Contains(ExceptionAssert.Argument.Is(value, nameof(value))); + int IList.IndexOf(object value) => IndexOf(ExceptionAssert.Argument.Is(value, nameof(value))); + void IList.Insert(int index, object value) => Insert(index, ExceptionAssert.Argument.Is(value, nameof(value))); + bool IList.IsFixedSize => false; + void IList.Remove(object value) => Remove(ExceptionAssert.Argument.Is(value, nameof(value))); + IEnumerator IEnumerable.GetEnumerator() => _list.GetEnumerator(); + #endregion + + #region ICollection (non-generic) members + void ICollection.CopyTo(Array array, int index) => throw new NotImplementedException(); + bool ICollection.IsSynchronized => false; + object ICollection.SyncRoot => ((ICollection)_list).SyncRoot; + #endregion + + #region IDictionary + public bool ContainsKey(TKey key) => _dictionary.ContainsKey(key); + public bool TryGetValue(TKey key, out T value) => _dictionary.TryGetValue(key, out value); + // explicit + T IDictionary.this[TKey key] { get => _dictionary[key]; set => _dictionary[key] = value; } + public ICollection Keys => _dictionary.Keys; + public ICollection Values => _dictionary.Values; + void IDictionary.Add(TKey key, T value) { + _assert_key_match(key, value); + _dictionary.Add(key, value); + _list.Add(value); + } + bool IDictionary.Remove(TKey key) { + if (_dictionary.TryGetValue(key, out T value)) { + _list.RemoveAt(_assert_index(key)); + _dictionary.Remove(key); + return true; + } + return false; + } + void ICollection>.Add(KeyValuePair item) { + _assert_key_match(item); + _dictionary.Add(item.Key, item.Value); + _list.Add(item.Value); + } + bool ICollection>.Contains(KeyValuePair item) { + _assert_key_match(item); + return _dictionary.ContainsKey(item.Key); + } + void ICollection>.CopyTo(KeyValuePair[] array, int arrayIndex) => _idict.CopyTo(array, arrayIndex); + bool ICollection>.Remove(KeyValuePair item) => _idict.Remove(item); + IEnumerator> IEnumerable>.GetEnumerator() => _idict.GetEnumerator(); + #endregion + + #region Private methods + static InvalidOperationException _out_of_sync_ex() => + new InvalidOperationException("Internal dictionary is out of sync with list."); + + int _assert_index(TKey k) { + if (_dictionary.ContainsKey(k)) { + for (int i = 0; i < _list.Count; i++) { + if (_key_comparer.Equals(k, _key(_list[i]))) + return i; + } + } + throw _out_of_sync_ex(); + } + + void _assert_key_match(TKey key, T value) { + if (!_key_comparer.Equals(key, _key(value))) + throw new ArgumentException("Key parameter does not match value's actual key."); + } + void _assert_key_match(KeyValuePair kv) => _assert_key_match(kv.Key, kv.Value); + #endregion + } +} \ No newline at end of file diff --git a/src/client/spark_core/Collections/ObservableTree/ImmutableUpdate.cs b/src/client/spark_core/Collections/ObservableTree/ImmutableUpdate.cs new file mode 100644 index 000000000..10a405076 --- /dev/null +++ b/src/client/spark_core/Collections/ObservableTree/ImmutableUpdate.cs @@ -0,0 +1,65 @@ +using bts.api.core; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Linq; +using System.Reactive.Linq; + +namespace bts.collections { + public struct ImmutableUpdate { + public static readonly ImmutableUpdate empty = + new ImmutableUpdate(ImmutableDictionary.Empty, ImmutableDictionary.Empty, ImmutableDictionary>.Empty, ImmutableDictionary.Empty); + + public readonly ImmutableDictionary added, removed; + public readonly ImmutableDictionary> changes; + public readonly ImmutableDictionary state; + + ImmutableUpdate(ImmutableDictionary added, ImmutableDictionary removed, ImmutableDictionary> changes, ImmutableDictionary state) { + this.added = added; + this.removed = removed; + this.changes = changes; + this.state = state; + } + + public bool has_changes => changes.Any() || added.Any() || removed.Any(); + + public ImmutableUpdate with_update(ImmutableUpdate update) { + var abuilder = added.ToBuilder(); + var rbuilder = removed.ToBuilder(); + var cbuilder = changes.ToBuilder(); + var sbuilder = state.ToBuilder(); + foreach (var kv in update.removed) { + rbuilder.Add(kv); + sbuilder.Remove(kv.Key); + } + foreach (var kv in update.changes) { + cbuilder.Add(kv); + sbuilder[kv.Key] = kv.Value.New; + } + foreach (var kv in update.added) { + abuilder.Add(kv); + sbuilder.Add(kv); + } + return new ImmutableUpdate(abuilder.ToImmutable(), rbuilder.ToImmutable(), cbuilder.ToImmutable(), sbuilder.ToImmutable()); + } + + public ImmutableUpdate with_added(IEnumerable> added) { + var abuilder = this.added.ToBuilder(); + var sbuilder = state.ToBuilder(); + foreach (var kv in added) { + abuilder.Add(kv); + sbuilder.Add(kv); + } + return new ImmutableUpdate(abuilder.ToImmutable(), removed, changes, sbuilder.ToImmutable()); + } + + public ImmutableUpdate with_removed(IEnumerable> removed) { + var rbuilder = this.removed.ToBuilder(); + var sbuilder = state.ToBuilder(); + foreach (var kv in removed) { + rbuilder.Add(kv); + sbuilder.Remove(kv); + } + return new ImmutableUpdate(added, rbuilder.ToImmutable(), changes, sbuilder.ToImmutable()); + } + } +} \ No newline at end of file diff --git a/src/client/spark_core/Collections/ObservableTree/ObservableNode.cs b/src/client/spark_core/Collections/ObservableTree/ObservableNode.cs new file mode 100644 index 000000000..6154a5067 --- /dev/null +++ b/src/client/spark_core/Collections/ObservableTree/ObservableNode.cs @@ -0,0 +1,174 @@ +/// 'ASSERT_ON_ERROR' is useful for diagnostic purposes. +/// CLR Exceptions thrown inside Reactive.Linq operators can be elusive, as cross-thread exception handling is inherently complicated. +/// Alternatively, immediately crashes the application and captures the call stack. +#define ASSERT_ON_ERROR +using mbts; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reactive.Linq; + +namespace bts.collections { + public class ObservableNode : IObservable> { + public readonly TKey key; + public readonly TValue value; + public readonly Dictionary> children; + + public ObservableNode(TKey key, TValue value) + : this(key, value, EqualityComparer.Default) { } + + public ObservableNode(TKey key, TValue value, IEqualityComparer comparer) + : this(key, value, null, new Dictionary>(comparer)) { } + + public ObservableNode(TKey key, TValue value, ObservableNode parent, Dictionary> children) { + this.key = key; + this.value = value; + this.parent = parent; + this.children = children; + } + + event Action> _child_added, _child_removed; + + public ObservableNode parent { get; private set; } + + public void add_child(ObservableNode node) { + if (node.parent != null) { + node.parent.remove_child(node.key); + } + lock (children) { + children.Add(node.key, node); + node.parent = this; + } + _child_added?.Invoke(node); + } + + public bool remove_child(TKey key) { + ObservableNode n; + lock (children) { + if (children.TryPopValue(key, out n)) { + n.parent = null; + } else { + return false; + } + } + _child_removed?.Invoke(n); + return true; + } + + public bool remove_child(TKey key, out ObservableNode child) { + lock (children) { + if (children.TryPopValue(key, out child)) { + child.parent = null; + } else { + return false; + } + } + _child_removed?.Invoke(child); + return true; + } + + public IObservable> subscribe_keys(ISet keys) => + Observable.Create>(observer => { + if (keys.Contains(key)) { + return Subscribe(observer); + } else { + var state = ImmutableUpdate.empty; + Dictionary subscriptions; + lock (children) { + subscriptions = children.ToDictionary(kv => kv.Key, kv => subscribe_node(kv.Value)); + _child_added += on_child_added; + _child_removed += on_child_removed; + } + return Disposable.Create(() => { + _child_added -= on_child_added; + _child_removed -= on_child_removed; + foreach (var s in subscriptions.Values) + s.Dispose(); + subscriptions = null; + }); + + void on_child_added(ObservableNode node) => + subscriptions.Add(node.key, subscribe_node(node)); + + void on_child_removed(ObservableNode node) { + if (subscriptions.TryPopValue(node.key, out IDisposable sub)) { + sub.Dispose(); + } else { + _on_error("Failed to dispose subscription to child node when child was removed."); + } + } + + IDisposable subscribe_node(ObservableNode node) { + var node_state = ImmutableUpdate.empty; + return node.subscribe_keys(keys).Subscribe(u => { + node_state = u; + if (u.has_changes) { + state = state.with_update(u); + observer.OnNext(state); + } + }, () => { + if (node_state.state.Any()) { + state = state.with_removed(node_state.state); + observer.OnNext(state); + } + }); + } + } + }); + + public IDisposable Subscribe(IObserver> observer) { + var state = ImmutableUpdate.empty.with_added(_enumerate_hierarchy(this)); + observer.OnNext(state); + Dictionary subscriptions; + lock (children) { + subscriptions = children.ToDictionary(kv => kv.Key, kv => subscribe_node(kv.Value)); + _child_added += on_child_added; + _child_removed += on_child_removed; + } + + return Disposable.Create(() => { + _child_added -= on_child_added; + _child_removed -= on_child_removed; + foreach (var s in subscriptions.Values) + s.Dispose(); + subscriptions = null; + }); + + void on_child_added(ObservableNode child) { + state = state.with_added(_enumerate_hierarchy(child)); + observer.OnNext(state); + subscriptions.Add(child.key, subscribe_node(child)); + } + + void on_child_removed(ObservableNode child) { + if (subscriptions.TryPopValue(child.key, out IDisposable sub)) { + state = state.with_removed(_enumerate_hierarchy(child)); + observer.OnNext(state); + sub.Dispose(); + } else Log.assert(false, "Failed to unsubscribe from child node."); + } + + IDisposable subscribe_node(ObservableNode node) => + node.Subscribe(u => { + state = state.with_update(u); + observer.OnNext(state); + }); + } + + static IEnumerable> _enumerate_hierarchy(ObservableNode node) { + yield return new KeyValuePair(node.key, node.value); + foreach (var child in node.children.Values) { + foreach (var grand_child in _enumerate_hierarchy(child)) + yield return grand_child; + } + } + + void _on_error(string msg) { +#if ASSERT_ON_ERROR + Log.assert(false, msg); +#else + throw new InvalidOperationException(msg); +#endif + } + } +} \ No newline at end of file diff --git a/src/client/spark_core/Collections/ObservableTree/ObservableTree.cs b/src/client/spark_core/Collections/ObservableTree/ObservableTree.cs new file mode 100644 index 000000000..f4f03d174 --- /dev/null +++ b/src/client/spark_core/Collections/ObservableTree/ObservableTree.cs @@ -0,0 +1,99 @@ +/// 'ASSERT_ON_ERROR' is useful for diagnostic purposes. +/// CLR Exceptions thrown inside Reactive.Linq operators can be elusive, as cross-thread exception handling is inherently complicated. +/// Alternatively, immediately crashes the application and captures the call stack. +#define ASSERT_ON_ERROR +using mbts; +using System; +using System.Collections.Generic; +using System.Reactive.Disposables; +using System.Reactive.Linq; + +namespace bts.collections { + public class ObservableTree { + readonly IEqualityComparer _comparer; + readonly TKey _no_parent_id; + readonly Func _key_selector, _parent_key_selector; + readonly ObservableNode _head; + readonly Dictionary> _index; + readonly Dictionary> _nursery; + + public ObservableTree(Func key_selector, Func parent_key_selector) + : this(key_selector, parent_key_selector, default, EqualityComparer.Default) { } + + public ObservableTree(Func key_selector, Func parent_key_selector, TKey no_parent_id, IEqualityComparer comparer) { + _parent_key_selector = parent_key_selector; + _key_selector = key_selector; + _no_parent_id = no_parent_id; + _comparer = comparer; + _head = new ObservableNode(no_parent_id, default, comparer); + _index = new Dictionary>(comparer); + _nursery = new Dictionary>(comparer); + } + + public void add(T value) { + TKey pk = _parent_key_selector(value); + TKey k = _key_selector(value); + var node = new ObservableNode(k, value, _comparer); + _index.Add(k, node); + if (_nursery.TryPopValue(k, out HashSet orphans)) { + foreach (var ok in orphans) { + if (_head.remove_child(ok, out ObservableNode orphan)) + node.add_child(orphan); + } + } + if (_comparer.Equals(pk, _no_parent_id)) { + _head.add_child(node); + } else if (_index.TryGetValue(pk, out ObservableNode pnode)) { + pnode.add_child(node); + } else { + _head.add_child(node); + if (_nursery.TryGetValue(pk, out HashSet orphan_siblings)) { + orphan_siblings.Add(k); + } else { + _nursery.Add(pk, new HashSet { k }); + } + } + } + + public bool remove(TKey key) { + if (_index.TryPopValue(key, out ObservableNode node)) { + if (!node.parent.remove_child(key)) { + _on_error("Failed to remove node from its parent, after it was successfully from the index."); + return false; + } + return true; + } + return false; + } + + public IObservable> subscribe() => _head; + + public IObservable> subscribe(ISet keys) => + _head.subscribe_keys(keys); + + public IObservable> subscribe(IObservable> keys_source) => + Observable.Create>(o => { + var state = ImmutableUpdate.empty; + var keys_sub_container = new DisposableContainer(); + return new CompositeDisposable(keys_source.Subscribe(on_keys), keys_sub_container); + void on_keys(ISet new_keys) { + //state = state.cleared(); + //o.OnNext(state); + keys_sub_container.replace(subscribe(new_keys).Subscribe(on_update)); + } + void on_update(ImmutableUpdate update) { + state = update; + if (state.has_changes) + o.OnNext(state); + } + }); + + void _on_error(string msg) { +#if ASSERT_ON_ERROR + Log.assert(false, msg); +#else + throw new InvalidOperationException(msg); +#endif + } + } +} \ No newline at end of file diff --git a/src/client/spark_core/Collections/Operable/Hierarchical/IHierarchicalRow.cs b/src/client/spark_core/Collections/Operable/Hierarchical/IHierarchicalRow.cs new file mode 100644 index 000000000..e00f22567 --- /dev/null +++ b/src/client/spark_core/Collections/Operable/Hierarchical/IHierarchicalRow.cs @@ -0,0 +1,18 @@ +namespace bts.collections { + interface IHierarchicalRow { + bool is_parent { get; } + bool is_expanded { get; } + int depth_level { get; } + /// To expand/collapse a row, call , + /// respectively. + /// Changing internally will not trigger any response in the collection model. + void on_is_parent_changed(bool is_parent); + void on_is_expanded_changed(bool is_expanded); + void on_depth_level_changed(int depth_level); + } + + interface IHierarchicalRow : IHierarchicalRow { + T value { get; } + void on_value_changed(T value); + } +} \ No newline at end of file diff --git a/src/client/spark_core/Collections/Operable/Hierarchical/OperableHierarchicalCollection.cs b/src/client/spark_core/Collections/Operable/Hierarchical/OperableHierarchicalCollection.cs new file mode 100644 index 000000000..61c1b8336 --- /dev/null +++ b/src/client/spark_core/Collections/Operable/Hierarchical/OperableHierarchicalCollection.cs @@ -0,0 +1,259 @@ +using bts.utils; +using mbts; +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.Specialized; +using System.ComponentModel; + +namespace bts.collections { + /// + /// This collection organizes rows in a sorted tree structure, and offers facilities to expand/collapse each node. + /// + /// The type of rows in the collection. + /// The type of underlying values used to create the rows. + /// The type of keys used to uniquely identify each row/value. + class OperableHierarchicalCollection : IReadOnlyObservableCollection, INotifyPropertyChanged where TKey : IEquatable where TRow : IHierarchicalRow { + const string _indexer_name = "Item[]"; + readonly TKey _no_parent_key; + readonly Func _key, _parent_key; + readonly DeferrableActionWrapper _refresh; + List _rows = new List(); + OperableHierarchicalCollectionModel _tree; + Func _filter; + + public OperableHierarchicalCollection(Func row_factory, Func key, Func parent_key, IComparer comparer, TKey no_parent_key = default) { + _key = key; + _parent_key = parent_key; + _no_parent_key = no_parent_key; + _tree = new OperableHierarchicalCollectionModel(row_factory, key, parent_key, no_parent_key, comparer); + int last_total_row_count = _tree.total_row_count; + _refresh = new DeferrableActionWrapper( + (RefreshFlags.Sync, sync_impl), + (RefreshFlags.Reset, reset_impl), + (RefreshFlags.TotalRowCount, total_row_count_impl)); + /// allows us to synchronize rows via , + /// without actually implementing IList, thus keeping this collection readonly, except through . + void sync_impl() => new ListWrapper(this).sync_with(_tree.rows); + void reset_impl() { + _rows.Clear(); + CollectionChanged?.Invoke(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset)); + _on_mutation(); + foreach (var r in _tree.rows) + _add(r); + } + void total_row_count_impl() { + if (last_total_row_count != total_row_count) { + last_total_row_count = total_row_count; + PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(total_row_count))); + } + } + } + + public event NotifyCollectionChangedEventHandler CollectionChanged; + public event PropertyChangedEventHandler PropertyChanged; + + public TRow this[int index] => _rows[index]; + public IComparer comparer { + get => _tree.comparer; + set { + _tree.comparer = value; + _reset(); + } + } + public Func filter { + get => _filter; + set { + _filter = value; + _tree.filter = value == null ? null : new Func(r => filter(r.value)); + _reset(); + } + } + public int Count => _rows.Count; + public int total_row_count => _tree.total_row_count; + + public IDisposable defer_refresh() => + _refresh.defer_execution(); + + public void update(IEnumerable added, IEnumerable changed, IEnumerable removed) { + _tree.update(added, changed, removed); + _sync(); + _refresh.execute(RefreshFlags.TotalRowCount); + } + + public TRow get_parent(TKey key) => _tree.get_parent(key); + public IEnumerable get_descendent_rows(TKey key) => _tree.get_descendent_rows(key); + + public void collapse_row(TKey key) { + _tree.collapse_row(key); + if (_refresh.is_execution_deferred) { + // Do NOT attempt any optimizations (this collection was already out of sync with the tree). + _sync(); + } else { + /// Rather than calling , this optimization leverages the fact that the relative order of the rows has not changed, and the only mutation will be removing a single continuous block of rows. + using (var en = _tree.rows.GetEnumerator()) { + int pos = 0; + while (en.MoveNext()) { + if (!pos_matches()) { + // found the beginning of the remove-block - remove each row until the keys match again + do _remove_at(pos); + while (!pos_matches()); + return; + } + pos++; + } + while (pos < Count) + _remove_at(pos); + bool pos_matches() => + _key(this[pos].value).Equals(_key(en.Current.value)); + } + } + } + + public void collapse_all() { + _tree.collapse_all(); + if (_refresh.is_execution_deferred) + // Do NOT attempt any optimizations (this collection was already out of sync with the tree). + _sync(); + else { + /// Rather than calling , this optimization leverages the fact that the relative order of the rows has not changed, and the only mutations will be removes. + using (var en = _tree.rows.GetEnumerator()) { + int pos = 0; + while (en.MoveNext()) { + while (!pos_matches()) + _remove_at(pos); + pos++; + } + while (pos < Count) + _remove_at(pos); + bool pos_matches() => + _key(this[pos].value).Equals(_key(en.Current.value)); + } + } + } + + public void expand_row(TKey key) { + _tree.expand_row(key); + if (_refresh.is_execution_deferred) { + // Do NOT attempt any optimizations (this collection was already out of sync with the tree). + _sync(); + } else { + /// Rather than calling , this optimization leverages the fact that the relative order of the rows has not changed, and the only mutation will be inserting a single continous block of rows. + using (var en = _tree.rows.GetEnumerator()) { + int pos = 0; + while (en.MoveNext()) { + if (!pos_matches()) { + // found the beginning of the insertion-block - add each row in the enumerator until the keys match again + do _insert(pos++, en.Current); + while (en.MoveNext() && !pos_matches()); + return; + } + if (++pos == Count) { + // the last row was expanded - add every row left in the enumerator + while (en.MoveNext()) + _add(en.Current); + break; + } + } + bool pos_matches() => + _key(this[pos].value).Equals(_key(en.Current.value)); + } + } + } + + public void expand_all() { + _tree.expand_all(); + if (_refresh.is_execution_deferred) { + // Do NOT attempt any optimizations (this collection was already out of sync with the tree). + _sync(); + } else if (Count > 0) { + /// Rather than calling , this optimization leverages the fact that the relative order of the rows has not changed, and the only mutations will be inserts. + using (var en = _tree.rows.GetEnumerator()) { + int pos = 0; + while (en.MoveNext()) { + if (!_key(this[pos].value).Equals(_key(en.Current.value))) + _insert(pos, en.Current); + if (++pos == Count) { + while (en.MoveNext()) + _add(en.Current); + break; + } + } + } + } + } + + public bool TryGetRow(TKey key, out TRow row) => + _tree.try_get_row(key, out row); + + public IEnumerator GetEnumerator() { + for (int i = 0; i < _rows.Count; i++) + yield return _rows[i]; + } + IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); + + void _add(TRow row) { + _rows.Add(row); + CollectionChanged?.Invoke(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, row, Count - 1)); + _on_mutation(); + } + + void _insert(int index, TRow row) { + _rows.Insert(index, row); + CollectionChanged?.Invoke(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, row, index)); + _on_mutation(); + } + + void _remove_at(int index) { + var cc = CollectionChanged; + if (cc == null) { + _rows.RemoveAt(index); + } else { + var r = _rows[index]; + _rows.RemoveAt(index); + cc(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, r, index)); + } + _on_mutation(); + } + + void _on_mutation() { + PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Count))); + PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(_indexer_name)); + } + + void _sync() => _refresh.execute(RefreshFlags.Sync); + void _reset() => _refresh.execute(RefreshFlags.Reset, RefreshFlags.Sync); + + struct ListWrapper : IList { + readonly OperableHierarchicalCollection _owner; + + public ListWrapper(OperableHierarchicalCollection owner) => + _owner = owner; + + public TRow this[int index] { get => _owner._rows[index]; set => throw new NotSupportedException(); } + public int Count => _owner.Count; + public bool IsReadOnly => true; + + public void Add(TRow item) => _owner._add(item); + public void Clear() => throw new NotSupportedException(); + public bool Contains(TRow item) => throw new NotImplementedException(); + public void CopyTo(TRow[] array, int arrayIndex) => throw new NotImplementedException(); + public IEnumerator GetEnumerator() { + for (int i = 0; i < _owner.Count; i++) + yield return _owner._rows[i]; + } + public int IndexOf(TRow item) => throw new NotImplementedException(); + public void Insert(int index, TRow item) => _owner._insert(index, item); + public bool Remove(TRow item) => throw new NotImplementedException(); + public void RemoveAt(int index) => _owner._remove_at(index); + IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); + } + + static class RefreshFlags { + public const int + Sync = 1, + Reset = 1 << 1, + TotalRowCount = 1 << 2; + } + } +} \ No newline at end of file diff --git a/src/client/spark_core/Collections/Operable/Hierarchical/OperableHierarchicalCollectionModel.cs b/src/client/spark_core/Collections/Operable/Hierarchical/OperableHierarchicalCollectionModel.cs new file mode 100644 index 000000000..3dd046b8d --- /dev/null +++ b/src/client/spark_core/Collections/Operable/Hierarchical/OperableHierarchicalCollectionModel.cs @@ -0,0 +1,131 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace bts.collections { + class OperableHierarchicalCollectionModel where TKey : IEquatable where TRow : IHierarchicalRow { + readonly Func _row_factory; + readonly Func _key; + SortedTree _tree; + IComparer _comparer; + Func _filter; + List> _cached_filtered = new List>(); + + public OperableHierarchicalCollectionModel(Func row_factory, Func key, Func parent_key, TKey no_parent_key, IComparer comparer) { + _row_factory = row_factory; + _tree = new SortedTree(_comparer = comparer, el => key(el.value), el => parent_key(el.value), no_parent_key); + _key = key; + } + + public IComparer comparer { + get => _comparer; + set { + _tree = _tree.Resort(_comparer = value); + _cached_filtered = null; + } + } + public Func filter { + get => _filter; + set { + _filter = value; + _cached_filtered = null; + _refresh_hierarchical_props(); + } + } + public IEnumerable rows { + get { + return _root_nodes.SelectMany(impl); + IEnumerable impl(INode n) { + yield return n.value; + if (n.value.is_expanded) { + foreach (var _n in n.inner.SelectMany(impl)) + yield return _n; + } + } + } + } + public int total_row_count { get; private set; } + + IEnumerable> _root_nodes => + _filter == null ? _tree.RootNodes : _cached_filtered ?? (_cached_filtered = _tree.RootNodes.filtered(_filter).sorted_hard(_comparer)); + + // collapse + public void collapse_row(TKey key) => _toggle_is_expanded(key, false); + public void collapse_all() => _toggle_is_expanded(false); + // expand + public void expand_row(TKey key) => _toggle_is_expanded(key, true); + public void expand_all() => _toggle_is_expanded(true); + // lookups + public bool try_get_row(TKey key, out TRow row) { + if (_tree.TryGetNode(key, out var node)) { + row = node.value; + return true; + } + row = default; + return false; + } + + public TRow get_parent(TKey key) => + _tree.TryGetNode(key, out var n) ? n.value : default; + + public IEnumerable get_descendent_rows(TKey key) { + if (_tree.TryGetNode(key, out var n)) { + yield return n.value; + foreach (var v in n.inner_values()) + yield return v; + } + } + + // update + public void update(IEnumerable added, IEnumerable changed, IEnumerable removed) { + foreach (var k in removed) { + if (_tree.Remove(k)) + total_row_count--; + } + foreach (var v in changed) { + _tree.TryReplace(_key(v), r => { r.on_value_changed(v); return r; }); + } + foreach (var v in added) { + if (_tree.Insert(_row_factory(v))) + total_row_count++; + } + _cached_filtered = null; + _refresh_hierarchical_props(); + } + + void _refresh_hierarchical_props() { + foreach (var n in _root_nodes) + impl(n, 0); + void impl(INode n, int depth_level) { + if (n.value.depth_level != depth_level) { + n.value.on_depth_level_changed(depth_level); + } + using (var en = n.inner.GetEnumerator()) { + if (en.MoveNext()) { + if (!n.value.is_parent) + n.value.on_is_parent_changed(true); + depth_level++; + do impl(en.Current, depth_level); + while (en.MoveNext()); + } else if (n.value.is_parent) + n.value.on_is_parent_changed(false); + } + } + } + + void _toggle_is_expanded(TKey key, bool is_expanded) => + _tree.TryReplace(key, r => { + if (r.is_expanded != is_expanded) + r.on_is_expanded_changed(is_expanded); + return r; + }); + + void _toggle_is_expanded(bool is_expanded) { + foreach (var row in _tree) + if (row.is_expanded != is_expanded) + row.on_is_expanded_changed(is_expanded); + } + + T _value_selector(TRow row) => row.value; + } +} diff --git a/src/client/spark_core/Collections/Operable/OperableCollection.cs b/src/client/spark_core/Collections/Operable/OperableCollection.cs new file mode 100644 index 000000000..badb05afd --- /dev/null +++ b/src/client/spark_core/Collections/Operable/OperableCollection.cs @@ -0,0 +1,73 @@ +using bts.api.core; +using bts.utils; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; + +namespace bts.collections { + class OperableCollection : ObservableCollection where TKey : IEquatable { + readonly Func _factory; + readonly Func _key; + readonly IEqualityComparer _eq_comparer; + IReadOnlyDictionary _map = DictionaryHelper.empty(); + + SortedList _sorted_items; + Func _filter; + IComparer _comparer; + + public OperableCollection(Func factory, Func key, IComparer comparer) { + _factory = factory; + _key = key; + _eq_comparer = EqualityComparer.Create(key); + _comparer = comparer; + _sorted_items = new SortedList(comparer ?? throw new ArgumentNullException(nameof(comparer))); + } + + public IComparer comparer { get => _comparer; set => _set_comparer(value); } + public Func filter { get => _filter; set => _set_filter(value); } + + public void reset(IComparer comparer, Func filter) { + _filter = filter; + _comparer = comparer; + _reset(new SortedList(filter == null ? _map.Values : _map.Values.Where(filter), comparer)); + } + + public void update(TableUpdate table) { + _map = table.state; + IEnumerable added, removed; + if (filter == null) { + added = table.added.Concat(table.changed); + removed = table.removed.Concat(table.changes.Select(ch => ch.Old)); + } else { + added = table.added.Where(filter).Concat(table.changed.Where(filter)); + removed = table.removed.Where(filter).Concat(table.changes.Select(ch => ch.Old).Where(filter)); + } + foreach (var v in removed) { + _sorted_items.Remove(v, out int? old_pos); + // don't bother checking 'old_pos.HasValue' - removes should always be successful (if not, an exception should be thrown anyways bc the situation is untenable). + RemoveAt(old_pos.Value); + } + foreach (var v in added) { + _sorted_items.Add(v, out int new_pos); + Insert(new_pos, _factory(v, _key(v))); + } + } + + void _set_comparer(IComparer new_comp) { + _comparer = new_comp ?? throw new ArgumentNullException(nameof(new_comp)); + _reset(new SortedList(_sorted_items, new_comp)); + } + + void _set_filter(Func filter) { + _filter = filter; + _reset(new SortedList(filter == null ? _map.Values : _map.Values.Where(filter), comparer)); + } + + void _reset(SortedList new_sorted_items) { + var changes = Diff.diff(_sorted_items, new_sorted_items, _eq_comparer).ToList(); + _sorted_items = new_sorted_items; + Diff.apply_diff(this, _sorted_items, changes, m => _factory(m, _key(m))); + } + } +} \ No newline at end of file diff --git a/src/client/spark/core/Collections/SetMap.cs b/src/client/spark_core/Collections/SetMap.cs similarity index 67% rename from src/client/spark/core/Collections/SetMap.cs rename to src/client/spark_core/Collections/SetMap.cs index ae2cbd18a..03302c4f2 100644 --- a/src/client/spark/core/Collections/SetMap.cs +++ b/src/client/spark_core/Collections/SetMap.cs @@ -3,10 +3,10 @@ using System.Collections; using System.Collections.Generic; using System.Linq; -namespace mbts.collections { - interface IGroupingSet : IGrouping, ISet { } +namespace bts.collections { + public interface IGroupingSet : IGrouping, ISet { } - class SetMap : IEnumerable>, ICollection { + public class SetMap : IEnumerable>, ICollection, IReadOnlyDictionary> { readonly IEqualityComparer _key_comparer; readonly IEqualityComparer _element_comparer; readonly Dictionary _dictionary; @@ -30,6 +30,10 @@ namespace mbts.collections { public object SyncRoot => null; public bool IsSynchronized => false; public IEnumerable Keys => _dictionary.Keys; + + public IEnumerable> Values => _dictionary.Values; + IEnumerable IReadOnlyDictionary>.this[TKey key] => _dictionary[key]; + public ISet this[TKey key] => _dictionary[key]; public void CopyTo(Array array, int index) => @@ -53,6 +57,36 @@ namespace mbts.collections { igs.AddRange(values); } + public bool add(TKey key, out ISet values) { + if (!_dictionary.TryGetValue(key, out InternalGroupSet igs)) { + _dictionary.Add(key, igs = new InternalGroupSet(key, _element_comparer)); + values = igs; + return true; + } + values = igs; + return false; + } + + /// + /// If '' is already contained in the specified 's set (according to the element-comparer being used by this instance), + /// it will be replaced with ',' and false will be returned. Otherwise, '' will be added and true will be returned. + /// + /// The key bucket to which the value should be added. + /// The value to added. + /// False if equivalent value was already present in the bucket, otherwise true. + public bool set(TKey key, TElement value) { + if (!_dictionary.TryGetValue(key, out InternalGroupSet values)) { + _dictionary[key] = values = new InternalGroupSet(key, _element_comparer); + } else { + if (values.Remove(value)) { + values.Add(value); + return false; + } + } + values.Add(value); + return true; + } + public bool remove(TKey key, TElement value) { if (_dictionary.TryGetValue(key, out InternalGroupSet values)) { bool removed = values.Remove(value); @@ -103,6 +137,19 @@ namespace mbts.collections { kv => new InternalGroupSet(kv.Key, kv.Value, _element_comparer) ), _key_comparer, _element_comparer); + public bool ContainsKey(TKey key) => _dictionary.ContainsKey(key); + public bool TryGetValue(TKey key, out IEnumerable value) { + if (_dictionary.TryGetValue(key, out InternalGroupSet igs)) { + value = igs; + return true; + } + value = null; + return false; + } + IEnumerator>> IEnumerable>>.GetEnumerator() { + foreach (var kv in _dictionary) + yield return new KeyValuePair>(kv.Key, kv.Value); + } class InternalGroupSet : HashSet, IGroupingSet { public InternalGroupSet(TKey key, IEqualityComparer comparer) @@ -115,7 +162,7 @@ namespace mbts.collections { } } - static class SetMap { + public static class SetMap { public static SetMap create(IEnumerable source, Func key_selector, Func value_selector) => create(source, key_selector, value_selector, EqualityComparer.Default, EqualityComparer.Default); @@ -140,4 +187,4 @@ namespace mbts.collections { return false; } } -} \ No newline at end of file +} diff --git a/src/client/spark_core/Collections/SetStack.cs b/src/client/spark_core/Collections/SetStack.cs new file mode 100644 index 000000000..dcf892895 --- /dev/null +++ b/src/client/spark_core/Collections/SetStack.cs @@ -0,0 +1,240 @@ +using System; +using System.Collections; +using System.Collections.Generic; + +namespace bts.collections { + class SetStack : ISet { + readonly SortedList _stack = new SortedList(Comparer.Default); + readonly Dictionary _index; + /// Note: is never reset (that is why a 'long' is used instead of an 'int'). + /// In the unlikely event that 2 ^ 64 values have been pushed/added, an exception should be thrown rather than silently breaking the stack order. + /// (i.e., should only be incremented in a checked scope) + long _version = long.MinValue; + + public SetStack() + : this(EqualityComparer.Default) { } + + public SetStack(IEqualityComparer comparer) { + _index = new Dictionary(comparer); + } + + public int Count => _stack.Count; + public bool IsReadOnly => false; + + public bool Push(T item) { + if (Remove(item)) { + Add(item); + return false; + } + Add(item); + return true; + } + + public T Pop() { + if (_stack.Count == 0) + throw new InvalidOperationException("No elements to pop."); + var rv = _stack[_stack.Count - 1].value; + _stack.RemoveAt(_stack.Count - 1); + _index.Remove(rv); + return rv; + } + + public T Peek() => + _stack.Count == 0 ? throw new InvalidOperationException("No elements to peek.") : _stack[_stack.Count - 1].value; + + public bool Add(T item) { + if (!_index.ContainsKey(item)) { + _index.Add(item, _version); + _stack.Add(new VersionedValue(item, _version)); + checked { + _version++; + } + return true; + } else return false; + } + + public void Clear() { + _index.Clear(); + _stack.Clear(); + } + + public bool Contains(T item) => + _index.ContainsKey(item); + + public void CopyTo(T[] array, int arrayIndex) { + for (int i = 0; i < _stack.Count; i++) + array[arrayIndex + i] = _stack[i].value; + } + + public void ExceptWith(IEnumerable other) { + foreach (var val in other) { + if (_index.TryPopValue(val, out long ver)) + _stack.Remove(new VersionedValue(val, ver)); + } + } + + public IEnumerator GetEnumerator() { + for (int i = 0; i < _stack.Count; i++) + yield return _stack[i].value; + } + + public void IntersectWith(IEnumerable other) { + var keep = _mark_common(other); + for (int i = 0; i < _stack.Count; i++) { + if (!keep.is_marked(i)) { + _index.Remove(_stack[i].value); + _stack.RemoveAt(i); + } + } + } + + public bool IsProperSubsetOf(IEnumerable other) { + if (other.SoftCount() is int other_count && other_count <= Count) + return false; + _mark_common(other, out int num_marked, out int num_unmarked); + return num_marked == Count && num_unmarked > 0; + } + + public bool IsProperSupersetOf(IEnumerable other) { + if (other.SoftCount() is int other_count && other_count < Count) + return true; + _mark_common(other, out int num_marked, out int num_unmarked); + return num_marked < Count && num_unmarked > 0; + } + + public bool IsSubsetOf(IEnumerable other) { + _mark_common(other, out int num_marked); + return num_marked == Count; + } + + public bool IsSupersetOf(IEnumerable other) { + _mark_common(other, out int num_marked, out int num_unmarked); + return num_unmarked == 0; + } + + public bool Overlaps(IEnumerable other) { + foreach (var v in other) { + if (_index.ContainsKey(v)) + return true; + } + return false; + } + + public bool Remove(T item) { + if (_index.TryPopValue(item, out long ver)) { + _stack.Remove(new VersionedValue(item, ver)); + return true; + } else return false; + } + + public bool SetEquals(IEnumerable other) { + _mark_common(other, out int num_marked, out int num_unmarked); + return num_marked == Count && num_unmarked == 0; + } + + public void SymmetricExceptWith(IEnumerable other) { + foreach (var v in other as ISet ?? new HashSet(other)) { + if (!Remove(v)) + Add(v); + } + } + + public void UnionWith(IEnumerable other) { + foreach (var v in other) + Add(v); + } + + void ICollection.Add(T item) => Add(item); + IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); + + BitMarker _mark_common(IEnumerable other) { + var common = new BitMarker(_stack.Count); + foreach (var value in other) { + if (_find(value, out int i)) + common.mark(i); + } + return common; + } + + bool _find(T value, out int i) { + if (_index.TryGetValue(value, out long version)) { + if (!_stack.TryGetIndex(new VersionedValue(value, version), out i)) + throw new InvalidOperationException($"{nameof(_stack)} is out of sync with {nameof(_index)}."); + return true; + } + i = -1; + return false; + } + + BitMarker _mark_common(IEnumerable other, out int num_marked) { + num_marked = 0; + var common = new BitMarker(_stack.Count); + foreach (var value in other) { + if (_find(value, out int i)) { + common.mark(i); + num_marked++; + } + } + return common; + } + + BitMarker _mark_common(IEnumerable other, out int num_marked, out int num_unmarked) { + num_marked = 0; + num_unmarked = 0; + var common = new BitMarker(_stack.Count); + foreach (var v in other) { + if (_find(v, out int i) && !common.is_marked(i)) { + common.mark(i); + num_marked++; + } else num_unmarked++; + } + return common; + } + + struct VersionedValue : IComparable { + public readonly T value; + public readonly long version; + + public VersionedValue(T value, long version) { + this.value = value; + this.version = version; + } + + public int CompareTo(VersionedValue other) => version.CompareTo(other.version); + } + + struct BitMarker { + const int _bits_per_byte = 8; + readonly byte[] _bytes; + + public BitMarker(int size) => + _bytes = new byte[size / _bits_per_byte]; + + public void mark(int i) => + _bytes[i / _bits_per_byte] |= (byte)(1 << (i % _bits_per_byte)); + + public bool is_marked(int i) => + (_bytes[i / _bits_per_byte] & (byte)(1 << (i % _bits_per_byte))) != 0; + } + } + + static class SetStackExtensions { + public static bool TryPeek(this SetStack set_stack, out T result) { + if (set_stack.Count > 0) { + result = set_stack.Peek(); + return true; + } + result = default; + return false; + } + + public static bool TryPop(this SetStack set_stack, out T result) { + if (set_stack.Count > 0) { + result = set_stack.Pop(); + return true; + } + result = default; + return false; + } + } +} \ No newline at end of file diff --git a/src/client/spark_core/Collections/SortedList.cs b/src/client/spark_core/Collections/SortedList.cs index 86fee2322..85b0d0298 100644 --- a/src/client/spark_core/Collections/SortedList.cs +++ b/src/client/spark_core/Collections/SortedList.cs @@ -76,6 +76,14 @@ namespace bts.collections { } } + public void RemoveAt(int index) { + if (index > _size) + throw new IndexOutOfRangeException(); + _size--; + Array.Copy(_values, index + 1, _values, index, _size - index); + _values[_size] = default(T); + } + public void Clear() { Array.Clear(_values, 0, _values.Length); _size = 0; diff --git a/src/client/spark/core/Collections/SortedSetMap.cs b/src/client/spark_core/Collections/SortedSetMap.cs similarity index 96% rename from src/client/spark/core/Collections/SortedSetMap.cs rename to src/client/spark_core/Collections/SortedSetMap.cs index 64793a2ce..0ed403f5a 100644 --- a/src/client/spark/core/Collections/SortedSetMap.cs +++ b/src/client/spark_core/Collections/SortedSetMap.cs @@ -2,7 +2,7 @@ using System.Collections; using System.Collections.Generic; -namespace mbts.collections { +namespace bts.collections { /// /// Similar to a SortedList, but supports both key and index read-access, the latter is achieved by the at_index() method. /// It also allows for multiple values per key, by internally creating a HashSet<TValue> for each key. diff --git a/src/client/spark_core/Collections/SortedTree.cs b/src/client/spark_core/Collections/SortedTree.cs index 00f7e1ef1..b09a7cd65 100644 --- a/src/client/spark_core/Collections/SortedTree.cs +++ b/src/client/spark_core/Collections/SortedTree.cs @@ -1,11 +1,11 @@ -using mbts.utils; +using bts.utils; using System; using System.Collections; using System.Collections.Generic; using System.Linq; namespace bts.collections { - public interface INode { + public interface INode { T value { get; } IEnumerable> inner { get; } } @@ -18,6 +18,44 @@ namespace bts.collections { yield return v; } } + + public static IEnumerable> filtered(this IEnumerable> root_nodes, Func filter) { + return impl(root_nodes); + IEnumerable> impl(IEnumerable> nodes) { + foreach (var n in nodes) { + if (filter(n.value)) { + yield return new Node(n.value, impl(n.inner)); + } else { + foreach (var _n in impl(n.inner)) + yield return _n; + } + } + } + } + + public static List> sorted_hard(this IEnumerable> root_nodes, IComparer comparer) { + var node_comp = comparer.wrap>(n => n.value); + var result = new List>(impl(root_nodes)); + result.Sort(node_comp); + return result; + IEnumerable> impl(IEnumerable> nodes) { + foreach (var n in nodes) { + var inner = new List>(impl(n.inner)); + inner.Sort(node_comp); + yield return new Node(n.value, inner); + } + } + } + + struct Node : INode { + public Node(T value, IEnumerable> inner) { + this.value = value; + this.inner = inner; + } + + public T value { get; } + public IEnumerable> inner { get; } + } } public class SortedTree : IEnumerable where TKey : IEquatable { @@ -50,6 +88,12 @@ namespace bts.collections { public IEnumerable> RootNodes => _tree; + public bool Insert(T item, out IEnumerable children) { + var insert_or_overwrite = Insert(item); + children = EnumerateInnerNodes(item).Select(n => n.value); + return insert_or_overwrite; + } + // Insert (return: true) or overwrite (return false) a new value // NOTE: you should use AddAll if you are adding multiple values public bool Insert(T item) { @@ -80,6 +124,17 @@ namespace bts.collections { } } + public bool TryReplace(TKey k, Func replace, out IEnumerable children) { + if (!_index.TryGetValue(k, out Node node)) { + children = Enumerable.Empty(); + return false; + } else { + _replace(node, replace); + children = node.children.Select(n => n.value); + return true; + } + } + public bool TryReplace(TKey k, Func replace) { if (!_index.TryGetValue(k, out Node node)) { return false; @@ -89,13 +144,11 @@ namespace bts.collections { } } - public void Remove(T item) => Remove(id(item)); + public bool Remove(T item) => Remove(id(item)); - // this is NOT idempotent, and will throw an exception if the Key is not present. - // (if we decide to change it to be idempotent, we should return a bool to indicate whether or not the remove succeeded) - public void Remove(TKey k) { - // must be in the index, bc this is a remove - var node = _index[k]; + public bool Remove(TKey k) { + if (!_index.TryGetValue(k, out Node node)) + return false; _index.Remove(k); var pk = parent(node.value); if (pk.Equals(_root_id)) { @@ -111,6 +164,7 @@ namespace bts.collections { foreach (var n in node.children) _tree.Add(n); } + return true; } /// @@ -299,12 +353,28 @@ namespace bts.collections { return null; } + public bool TryGetNode(TKey key, out INode node) { + if (_index.TryGetValue(key, out Node n)) { + node = n; + return true; + } + node = null; + return false; + } + public INode GetRootNode(TKey key) => _index.TryGetValue(key, out Node node) ? GetRootNode(node) : null; Node GetRootNode(Node node) => _index.TryGetValue(parent(node.value), out Node pnode) ? GetRootNode(pnode) : node; + public INode GetParent(T item) { + if (_index.TryGetValue(parent(item), out Node pnode)) { + return pnode; + } + return null; + } + public IEnumerable EnumerateGroup(T item) { var pnode = parentmost(item); return pnode == null ? Enumerable.Empty() : EnumerateNode(pnode); diff --git a/src/client/spark_core/utils/BitHelper.cs b/src/client/spark_core/utils/BitHelper.cs new file mode 100644 index 000000000..f669a3baa --- /dev/null +++ b/src/client/spark_core/utils/BitHelper.cs @@ -0,0 +1,25 @@ +namespace bts.utils { + public static class BitHelper { + public static int loaded_int32 => _Int32Bits.all; + + public static bool remove_flags(ref int target, int flags) { + if ((target & flags) == flags) { + target ^= flags; + return true; + } else return false; + } + + static class _Int32Bits { + public static readonly int all; + + static _Int32Bits() { + all = 1 << 31; + all |= (all >> 1); + all |= (all >> 2); + all |= (all >> 4); + all |= (all >> 8); + all |= (all >> 16); + } + } + } +} \ No newline at end of file diff --git a/src/client/spark/core/Utility/CollectionHelper.cs b/src/client/spark_core/utils/CollectionHelper.cs similarity index 79% rename from src/client/spark/core/Utility/CollectionHelper.cs rename to src/client/spark_core/utils/CollectionHelper.cs index 65d7252bf..76cf4f0c6 100644 --- a/src/client/spark/core/Utility/CollectionHelper.cs +++ b/src/client/spark_core/utils/CollectionHelper.cs @@ -4,7 +4,7 @@ using System.Collections.ObjectModel; using System.Collections.Specialized; using System.Linq; -namespace mbts.utils { +namespace bts.utils { static class CollectionHelper { public static int binary_search(IList items, T value, IComparer comparer) => binary_search(items, value, 0, items.Count, comparer); @@ -90,20 +90,25 @@ namespace mbts.utils { } // Note: this is not optimized, be wary of use with large collections - public static void sync_with_never_duplicate(ObservableCollection dest, IEnumerable src) => + public static void sync_with_never_duplicate(IList dest, IEnumerable src) => sync_with_never_duplicate(dest, src, EqualityComparer.Default); // Note: this is not optimized, be wary of use with large collections - public static void sync_with_never_duplicate(ObservableCollection dest, IEnumerable src, IEqualityComparer comp) { - int i = 0; - foreach (var val in src.empty_if_null()) { - int curr_index = dest.IndexOf(val); + public static void sync_with_never_duplicate(IList dest, IEnumerable src, IEqualityComparer comp) { + var src_list = src as IList ?? new List(src); + var src_set = src as ISet ?? new HashSet(src_list); + for (int i = 0; i < dest.Count; i++) { + if (!src_set.Contains(dest[i])) + dest.RemoveAt(i); + } + for (int i = 0; i < src_list.Count; i++) { + int curr_index = dest.IndexOf(src_list[i]); if (curr_index == i) { continue; - } else if (curr_index > 0 && curr_index < dest.Count) { + } else if (curr_index >= 0 && curr_index < dest.Count) { dest.RemoveAt(curr_index); } - dest.Insert(i++, val); + dest.Insert(i, src_list[i]); } } @@ -112,11 +117,16 @@ namespace mbts.utils { // Note: this is not optimized, be wary of use with large collections public static void sync_with_never_duplicate(ObservableCollection dest, IEnumerable src, Func create, Func key_selector, Func src_key_selector, IEqualityComparer key_comparer) { - int i = 0; - var src_map = src.ToDictionary(src_key_selector); + var src_list = src as IList ?? new List(src); + var src_map = src_list.ToDictionary(src_key_selector); + for (int i = 0; i < dest.Count; i++) { + var k = key_selector(dest[i]); + if (!src_map.ContainsKey(k)) + dest.RemoveAt(i); + } var dest_map = dest.ToDictionary(key_selector); - foreach (var val in src.empty_if_null()) { - TKey key = src_key_selector(val); + for (int i = 0; i < src_list.Count; i++) { + TKey key = src_key_selector(src_list[i]); if (dest_map.TryGetValue(key, out T dval)) { int curr_index = dest.IndexOf(dval); if (curr_index != i) { @@ -124,9 +134,8 @@ namespace mbts.utils { dest.Insert(i, dval); } } else { - dest.Insert(i, create(val)); + dest.Insert(i, create(src_list[i])); } - ++i; } } @@ -136,13 +145,5 @@ namespace mbts.utils { rv[i] = selector(source[i]); return rv; } - - public static IDisposable dispose_on_removed(ObservableCollection collection) => - collection.Subscribe((s, e) => { - if (e.OldItems != null) { - foreach (T item in e.OldItems) - (item as IDisposable)?.Dispose(); - } - }); } -} \ No newline at end of file +} diff --git a/src/client/spark_core/utils/DeferrableActionWrapper.cs b/src/client/spark_core/utils/DeferrableActionWrapper.cs new file mode 100644 index 000000000..162d8bf7a --- /dev/null +++ b/src/client/spark_core/utils/DeferrableActionWrapper.cs @@ -0,0 +1,70 @@ +using mbts; +using System; + +namespace bts.utils { + /// + /// Offers facilities to defer/delay/supress the execution of certain actions. + /// Common usage is to execute code that might lead to redundant invocations of one of more specified actions in a 'using' scope with . + /// + class DeferrableActionWrapper { + readonly (int flags, Action action)[] _actions; + int _deferment_count, _dirty, _redundancies; + + public DeferrableActionWrapper(Action action) + : this((1, action)) { } + + public DeferrableActionWrapper(params (int flags, Action action)[] actions) => + _actions = actions; + + public bool is_execution_deferred => _deferment_count > 0; + bool _is_execution_pending => _dirty != 0; + + public void cancel_pending_execution() { + _dirty = 0; + _deferment_count = 0; + } + + public void execute() => + execute(BitHelper.loaded_int32); + + public void execute(int flags) { + _dirty |= flags; + if (!is_execution_deferred) + _execute(); + } + + /// Be wary of circular redundancies (i.e., don't create a situation where every action is marked redundant). + public void execute(int flags, int redundancies) { + _redundancies |= redundancies; + execute(flags); + } + + public IDisposable supress_execution() { + _deferment_count++; + return Disposable.Create(() => _deferment_count--); + } + + public IDisposable defer_execution() { + _deferment_count++; + return Disposable.Create(() => { + _deferment_count--; + if (_is_execution_pending && !is_execution_deferred) { + _execute(); + } + }); + } + + void _execute() { + /// Need to set to 0 before executing any actions, + /// as they may cause it to be re-assigned, via re-entrancy (). + int local_flags = _dirty; + BitHelper.remove_flags(ref local_flags, _redundancies); + _dirty = 0; + _redundancies = 0; + for (int i = 0; i < _actions.Length;i++) { + if (BitHelper.remove_flags(ref local_flags, _actions[i].flags)) + _actions[i].action(); + } + } + } +} \ No newline at end of file diff --git a/src/client/spark_core/utils/Exceptions/ExceptionBuilder.cs b/src/client/spark_core/utils/Exceptions/ExceptionBuilder.cs index 68601ed17..bf87ee8af 100644 --- a/src/client/spark_core/utils/Exceptions/ExceptionBuilder.cs +++ b/src/client/spark_core/utils/Exceptions/ExceptionBuilder.cs @@ -31,5 +31,20 @@ namespace mbts.utils { public static ArgumentOutOfRangeException gte_length(string name) => new ArgumentOutOfRangeException(name, "Index is greater than or equal to the number of elements."); } + + public static class Format { + public static string LessThan(int value) => $"{Messages.LessThan} {value}."; + public static string LessThanOrEqualTo(int value) => $"{Messages.LessThanOrEqualTo} {value}."; + public static string GreaterThan(int value) => $"{Messages.GreaterThan} {value}."; + public static string GreaterThanOrEqualTo(int value) => $"{Messages.GreaterThanOrEqualTo} {value}."; + } + + public static class Messages { + public const string + LessThan = "Less than", + LessThanOrEqualTo = "Less than or equal to", + GreaterThan = "Greater than", + GreaterThanOrEqualTo = "Greater than or equal to"; + } } } \ No newline at end of file diff --git a/src/client/spark_core/utils/GlobalExtensions.cs b/src/client/spark_core/utils/GlobalExtensions.cs index ee291796b..7433968b4 100644 --- a/src/client/spark_core/utils/GlobalExtensions.cs +++ b/src/client/spark_core/utils/GlobalExtensions.cs @@ -25,6 +25,9 @@ namespace mbts { return str; } + public static string if_null_or_empty(this string str, string default_value) => + string.IsNullOrEmpty(str) ? default_value : str; + public static T choose(this Random r, IEnumerable range) { var index = r.Next(0, range.Count()); return range.Skip(index).First(); diff --git a/src/client/spark_core/utils/StringBuilderEx.cs b/src/client/spark_core/utils/StringBuilderEx.cs new file mode 100644 index 000000000..838ad3eda --- /dev/null +++ b/src/client/spark_core/utils/StringBuilderEx.cs @@ -0,0 +1,66 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Text; + +namespace bts.utils { + // The only reason this implements IEnumerable is for syntactical purposes, so it can be initialized like this: + // new StringBuilderEx { "A", "B", "C" }; + // Note: that cool initialization feature also depends on the fact that there is a method called 'Add' which accepts a string + class StringBuilderEx : IEnumerable { + readonly StringBuilder _sb; + + public StringBuilderEx() + : this(new StringBuilder()) { } + + public StringBuilderEx(string value) + : this(new StringBuilder(value)) { } + + public StringBuilderEx(params string[] values) + : this(_init_builder(values)) { } + + StringBuilderEx(StringBuilder sb) => + _sb = sb; + + public static string join(Func conditional_prefix, IEnumerable args) { + using (var en = args.GetEnumerator()) { + if (en.MoveNext()) { + var sb = new StringBuilder(conditional_prefix()); + do sb.Append(en.Current); + while (en.MoveNext()); + return sb.ToString(); + } + return string.Empty; + } + } + + public void Add(string arg) => + _sb.Append(arg); + + public void Add(params string[] args) { + foreach (var a in args) + _sb.Append(a); + } + + public void Insert(int index, string arg) => + _sb.Insert(index, arg); + + public void Insert(int index, params string[] args) { + for (int i = args.Length - 1; i >= 0; i--) + _sb.Insert(index, args[i]); + } + + public override string ToString() => _sb.ToString(); + + IEnumerator IEnumerable.GetEnumerator() { + yield break; + } + + static StringBuilder _init_builder(string[] values) { + var sb = new StringBuilder(); + foreach (var v in values) + sb.Append(v); + return sb; + } + } +} diff --git a/src/client/spark_core/utils/UpdateExtensions.cs b/src/client/spark_core/utils/UpdateExtensions.cs new file mode 100644 index 000000000..675a2a5cc --- /dev/null +++ b/src/client/spark_core/utils/UpdateExtensions.cs @@ -0,0 +1,197 @@ +using bts.api.core; +using bts.collections; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reactive.Linq; + +namespace bts.utils { + public static class UpdateExtensions { + public static IObservable> RootDependent( + this IObservable> source, + Func key, + Func parent_key, + Func with_root) + where TKey : IEquatable => + RootDependent(source, key, parent_key, with_root, v => v, EqualityComparer.Default, default).SelectKeyValue(kv => kv.Value, key); + + // TODO: unit tests + public static IObservable, TKey>> RootDependent( + this IObservable> source, + Func key, + Func parent_key, + Func get_result, + Func get_result_no_parent, + IEqualityComparer result_comparer, + TKey no_parent_key) + where TKey : IEquatable => + Observable.Create, TKey>>(observer => { + var value_comparer = EqualityComparer.Create, TResult>(kv => kv.Value, result_comparer); + var state = DictionaryHelper.empty(); + var output = TableUpdate, TKey>.mk_empty(kv => kv.Key); + var parent_to_children = new SetMap(); + return source.Subscribe(update); + // + void update(TableUpdate input) { + state = input.state; + var builder = output.to_builder(); + // execute all parent_to_children changes first, so descendent-propagation will be efficient (otherwise propagation might be needlessly performed on values that are yet to be removed, or performed with the wrong root, if the real root is yet to be added). + foreach (var v in input.removed.Concat(input.changes.Select(ch => ch.Old))) { + var k = input.key_extractor(v); + parent_to_children.remove(parent_key(v), v); + } + foreach (var v in input.added.Concat(input.changed)) { + var pk = parent_key(v); + if (!pk.Equals(no_parent_key)) + parent_to_children.add(pk, v); + } + foreach (var v in input.removed) { + var k = input.key_extractor(v); + builder.remove(k); + if (parent_to_children.try_lookup(k, out ISet children)) { + foreach (var child in children) { + var ck = key(child); + builder.add_or_update(new KeyValuePair(ck, get_result_no_parent(child))); + foreach (var d in descendents(ck)) + builder.add_or_update(new KeyValuePair(key(d), get_result(d, child))); + } + } + } + foreach (var v in input.changed) { + var k = input.key_extractor(v); + var root = get_root(v); + TResult result; + if (key(root).Equals(k)) { + result = get_result_no_parent(v); + foreach (var d in descendents(k)) + builder.add_or_update(new KeyValuePair(key(d), get_result(d, v))); + } else { + result = get_result(v, root); + } + builder.add_or_update(new KeyValuePair(k, result)); + } + foreach (var v in input.added) { + var k = input.key_extractor(v); + var pk = parent_key(v); + TResult result; + if (pk.Equals(no_parent_key)) { + result = get_result_no_parent(v); + foreach (var d in descendents(k)) + builder.add_or_update(new KeyValuePair(key(d), get_result(d, v))); + } else { + parent_to_children.add(pk, v); + var root = get_root(v); + if (key(root).Equals(k)) { + result = get_result_no_parent(v); + foreach (var d in descendents(k)) + builder.add_or_update(new KeyValuePair(key(d), get_result(d, v))); + } else { + result = get_result(v, root); + } + } + builder.add_or_update(new KeyValuePair(k, result)); + } + var new_output = builder.to_table_checked(value_comparer); + if (new_output.has_changes()) + observer.OnNext(output = new_output); + } + T get_root(T value) { + var pk = parent_key(value); + while (!pk.Equals(no_parent_key) && state.TryGetValue(pk, out var parent)) { + value = parent; + pk = parent_key(value); + } + return value; + } + IEnumerable descendents(TKey k) { + if (parent_to_children.try_lookup(k, out ISet children)) { + foreach (var child in children) { + yield return child; + foreach (var d in descendents(key(child))) + yield return d; + } + } + } + }); + + public static IObservable> MergeTable(this IObservable> source, IObservable> other) where TKey : IEquatable => + source.AggregateLatest(other, _Merge.source_change_del, _Merge.other_change_del, () => TableUpdate.empty, TableUpdate.empty, TableUpdate.empty); + + public static IObservable, TKey>> ParentDependent( + this IObservable> source, + Func key, + Func parent_key, + Func get_result, + Func get_result_no_parent) + where TResult : IEquatable + where TKey : IEquatable => + ParentDependent(source, key, parent_key, get_result, get_result_no_parent, EqualityComparer.Default, default); + + public static IObservable, TKey>> ParentDependent( + this IObservable> source, + Func key, + Func parent_key, + Func get_result, + Func get_result_no_parent, + IEqualityComparer result_comparer, + TKey no_parent_key) + where TKey : IEquatable => + Observable.Create, TKey>>(observer => { + var value_comparer = EqualityComparer.Create, TResult>(kv => kv.Value, result_comparer); + var state = DictionaryHelper.empty(); + var output = TableUpdate, TKey>.mk_empty(kv => kv.Key); + var parent_to_children = new SetMap(); + return source.Subscribe(update); + // + void update(TableUpdate input) { + state = input.state; + var builder = output.to_builder(); + foreach (var v in input.removed) { + var k = input.key_extractor(v); + builder.remove(k); + parent_to_children.remove(parent_key(v), v); + if (parent_to_children.try_lookup(k, out ISet children)) { + foreach (var child in children) + builder.add_or_update(new KeyValuePair(key(child), get_result_no_parent(child))); + } + } + foreach (var v in input.changed) { + var k = key(v); + builder.add_or_update(new KeyValuePair(k, lookup_result(v))); + parent_to_children.set(parent_key(v), v); + if (parent_to_children.try_lookup(k, out ISet children)) { + foreach (var child in children) + builder.add_or_update(new KeyValuePair(key(child), get_result(child, v))); + } + } + foreach (var v in input.added) { + var k = key(v); + builder.add_or_update(new KeyValuePair(k, lookup_result(v))); + parent_to_children.add(parent_key(v), v); + if (parent_to_children.try_lookup(k, out ISet children)) { + foreach (var child in children) + builder.add_or_update(new KeyValuePair(key(child), get_result(child, v))); + } + } + var result = builder.to_table_checked(value_comparer); + if (result.has_changes()) + observer.OnNext(output = result); + } + TResult lookup_result(T child) { + var pk = parent_key(child); + return !pk.Equals(no_parent_key) && state.TryGetValue(pk, out T parent) ? get_result(child, parent) : get_result_no_parent(child); + } + }); + + static class _Merge where TKey : IEquatable { + public static readonly Func, Change>, TableUpdate, TableUpdate> source_change_del = _source_changed_impl; + public static readonly Func, TableUpdate, Change>, TableUpdate> other_change_del = _other_changed_impl; + + static TableUpdate _source_changed_impl(TableUpdate target, Change> source_change, TableUpdate other_table) => + TableUpdate.update(target, source_change.New.added, source_change.New.changes, source_change.New.removed, source_change.New.key_extractor); + + static TableUpdate _other_changed_impl(TableUpdate target, TableUpdate source_table, Change> other_change) => + TableUpdate.update(target, other_change.New.added, other_change.New.changes, other_change.New.removed, other_change.New.key_extractor); + } + } +} diff --git a/src/client/spark_test/Collections/KeyedCollectionTest.cs b/src/client/spark_test/Collections/KeyedCollectionTest.cs new file mode 100644 index 000000000..8697cce88 --- /dev/null +++ b/src/client/spark_test/Collections/KeyedCollectionTest.cs @@ -0,0 +1,107 @@ +using bts.test; +using mbts; +using System; +using System.Linq; + +namespace bts.tests { + [TestGroup] + class KeyedCollectionTests { + [Test] + public void test_all() { + var collection = new collections.KeyedCollection(_key); + int id = 0; + var known_names = new[] { new NameID("Steve", id++), new NameID("Jobin", id++), new NameID("Michelle", id++), new NameID("Kristof", id++) }; + var unknown_names = new[] { new NameID("Ashley", id++), new NameID("Dee", id++) }; + var map = known_names.ToDictionary(_key); + // populate with known names + foreach (var n in known_names) + collection.Add(n); + // should find known names + foreach (var n in known_names) + assert_find(n, true); + // shouldn't find/remove unknown names + foreach (var n in unknown_names) + assert_find(n, false); + // should remove known names + foreach (var remove_test in new Action[] { assert_remove_by_index, assert_remove_key, assert_remove_value }) { + var copy = _copy(collection); + foreach (var n in known_names) + remove_test(n); + collection = copy; + } + // should throw exception when duplicate name is added + foreach (var n in known_names) + Assert.throws(() => collection.Add(n)); + + void assert_find(NameID n, bool expected) { + Assert.That(expected == collection.ContainsKey(n.id)); + Assert.That(expected == collection.Contains(n)); + int index = collection.IndexOf(n); + Assert.That(expected == index >= 0); + Assert.That(expected == collection.TryGetValue(n.id, out NameID result)); + if (expected) { + Assert.That(result.name == n.name); + Assert.That(result.Equals(map[n.id])); + Assert.That(index < collection.Count); + Assert.That(collection[index].Equals(n)); + } else { + Assert.IsFalse(collection.Remove(n)); + Assert.IsFalse(collection.AsDictionary().Remove(n.id)); + } + } + void assert_remove_by_index(NameID n) { + using (begin_assert_remove(n)) + collection.RemoveAt(collection.IndexOf(n)); + } + void assert_remove_value(NameID n) { + using (begin_assert_remove(n)) + collection.Remove(n); + } + void assert_remove_key(NameID n) { + using (begin_assert_remove(n)) + collection.AsDictionary().Remove(n.id); + } + IDisposable begin_assert_remove(params NameID[] ns) { + int count_before = collection.Count; + foreach (var n in ns) + assert_find(n, true); + return Disposable.Create(() => { + Assert.That(collection.Count == count_before - ns.Length); + foreach (var n in ns) + assert_find(n, false); + }); + } + } + + static int _key(NameID n) => n.id; + + static collections.KeyedCollection _copy(collections.KeyedCollection source, bool assert_sequence_equals = true) { + var copy = new collections.KeyedCollection(_key); + foreach (var n in source) + copy.Add(n); + if (assert_sequence_equals) { + Assert.That(copy.Count == source.Count); + for (int i = 0; i < source.Count; i++) + Assert.That(source[i].Equals(copy[i])); + } + return copy; + } + + class NameID : IEquatable { + public readonly string name; + public readonly int id; + public NameID(string name, int id) { + this.name = name; + this.id = id; + } + + public bool Equals(NameID other) => + other != null && + id == other.id && + name == other.name; + + public override bool Equals(object obj) => Equals(obj as NameID); + public override int GetHashCode() => id; + } + } +} \ No newline at end of file diff --git a/src/client/spark_test/Collections/SetStackTests.cs b/src/client/spark_test/Collections/SetStackTests.cs new file mode 100644 index 000000000..146ad8a48 --- /dev/null +++ b/src/client/spark_test/Collections/SetStackTests.cs @@ -0,0 +1,87 @@ +using bts.collections; +using bts.test; +using System; +using System.Collections.Generic; + +namespace bts.tests { + [TestGroup] + class SetStackTests { + [Test] + public void test_all() { + var set_stack = new SetStack(); + int id = 0; + var known_names = new[] { new NameID("Steve", id++), new NameID("Jobin", id++), new NameID("Michelle", id++), new NameID("Kristof", id++) }; + var unknown_names = new[] { new NameID("Ashley", id++), new NameID("Dee", id++) }; + // verify names are distinct before we begin (all tests assume this) + Assert.IsTrue(new HashSet(known_names).SetEquals(known_names)); + /// Test Add + foreach (var n in known_names) + assert_add(n); + Assert.AreEqual(set_stack.Count, known_names.Length); + /// Test Peek/Pop + for (int i = known_names.Length - 1; i >= 0; i--) { + var n = known_names[i]; + Assert.AreEqual(set_stack.Peek(), n); + Assert.AreEqual(set_stack.Pop(), n); + Assert.AreEqual(set_stack.Count, i); + } + /// Test Remove + foreach (var n in known_names) + assert_add(n); + for (int i = 0; i < known_names.Length; i++) + assert_remove(known_names[i]); + Assert.AreEqual(set_stack.Count, 0); + + // tests add, contains, peek, and pop + void assert_add(NameID n) { + int count_before = set_stack.Count; + // add + Assert.IsFalse(set_stack.Contains(n)); + Assert.IsTrue(set_stack.Add(n)); + Assert.AreEqual(set_stack.Count, count_before + 1); + Assert.IsTrue(set_stack.Contains(n)); + // peek/pop + Assert.AreEqual(set_stack.Peek(), set_stack.Pop()); + Assert.AreEqual(set_stack.Count, count_before); + Assert.IsFalse(set_stack.Contains(n)); + // re-add + Assert.IsTrue(set_stack.Add(n)); + Assert.AreEqual(set_stack.Count, count_before + 1); + Assert.IsTrue(set_stack.Contains(n)); + // re-add again + Assert.IsFalse(set_stack.Add(n)); + Assert.AreEqual(set_stack.Count, count_before + 1); + Assert.IsTrue(set_stack.Contains(n)); + } + // tests remove, and contains + void assert_remove(NameID n) { + int count_before = set_stack.Count; + // remove + Assert.IsTrue(set_stack.Contains(n)); + Assert.IsTrue(set_stack.Remove(n)); + Assert.AreEqual(set_stack.Count, count_before - 1); + // remove again + Assert.IsFalse(set_stack.Remove(n)); + Assert.AreEqual(set_stack.Count, count_before - 1); + } + } + + class NameID : IEquatable { + public readonly string name; + public readonly int id; + + public NameID(string name, int id) { + this.name = name; + this.id = id; + } + + public bool Equals(NameID other) => + other != null && + id == other.id && + name == other.name; + + public override bool Equals(object obj) => Equals(obj as NameID); + public override int GetHashCode() => id; + } + } +} \ No newline at end of file diff --git a/src/client/spark_test/SortedTree/SortedTreeTests.cs b/src/client/spark_test/SortedTree/SortedTreeTests.cs index d578f50aa..643a99184 100644 --- a/src/client/spark_test/SortedTree/SortedTreeTests.cs +++ b/src/client/spark_test/SortedTree/SortedTreeTests.cs @@ -82,6 +82,89 @@ namespace bts.tests { int id(Order order) => order.id; int pid(Order order) => order.parent_id; + [Test] + public void test_try_replace_with_returned_children() { + Order[] test_orders = new[] { + new Order('A', 1), + new Order('D', 4) + }; + var comparer = Comparer.Create((l, r) => l.name.CompareTo(r.name)); + var input = test_orders.ToList(); + var tree = new SortedTree(comparer, id, pid, input); + + // create child orders of A + var order_b = new Order('B', 2, 1); + var order_c = new Order('C', 3, 1); + + IEnumerable the_children = new List (); + tree.Insert(order_b, out the_children); + + // we have just inserted b, but b has no children yet + Assert.IsFalse(the_children.Any()); + + // now lets go ahead and insert another child of a + tree.Insert(order_c, out the_children); + + // we should still be at 0 here since A itself has not changed + Assert.IsFalse(the_children.Any()); + + // now let's change A to Z + var replace_success = tree.TryReplace(1, (o) => { o.name = 'Z'; return o; }, out the_children); + + // replace_success should be true and + // we should now get both B and C + // no short circuting since we want to test all conditions + Assert.IsTrue(replace_success & !the_children.Skip(2).Any() & the_children.Contains(order_b) & the_children.Contains(order_c)); + + // we will now try to replace a non-existant node + replace_success = tree.TryReplace(19, (o) => { o.name = 'Q'; return o; }, out the_children); + + // replace_success should be false and + // we should not get any children + // no short circuting since we want to test both conditions + Assert.IsTrue(!replace_success & !the_children.Any()); + } + + [Test] + public void test_parent() { + var comparer = Comparer.Create((l, r) => l.name.CompareTo(r.name)); + var input = orders.ToList(); + var tree = new SortedTree(comparer, id, pid, input); + + // grab node a to start + var input_a = input[0]; + var node_a = tree.Where(x => x.name == 'A').FirstOrDefault(); + Assert.AreEqual(input_a, node_a); + + // node a's parent should be null + var node_a_parent = tree.GetParent(node_a); + Assert.IsTrue(node_a_parent == null); + + // grab node b + var input_b = input[1]; + var node_b = tree.Where(x => x.name == 'B').FirstOrDefault(); + Assert.AreEqual(input_b, node_b); + + // verify node b's parent is node a + var node_b_parent = tree.GetParent(node_b); + Assert.AreEqual(node_b_parent.value, node_a); + + // grab a node deeper down and check that it only goes 1 level up + // grab node a to start + var input_e = input[4]; + var node_e = tree.Where(x => x.name == 'E').FirstOrDefault(); + Assert.AreEqual(input_e, node_e); + + var input_f = input[5]; + var node_f = tree.Where(x => x.name == 'F').FirstOrDefault(); + Assert.AreEqual(input_f, node_f); + + // verify node f's parent is node e + var node_f_parent = tree.GetParent(node_f); + Assert.AreEqual(node_f_parent.value, node_e); + + } + [Test] public void test_enumerate_group() { var comparer = Comparer.Create((l, r) => l.name.CompareTo(r.name)); diff --git a/src/client/spark_test/System/AlgoDefinitionTests.cs b/src/client/spark_test/System/AlgoDefinitionTests.cs new file mode 100644 index 000000000..3268a5a72 --- /dev/null +++ b/src/client/spark_test/System/AlgoDefinitionTests.cs @@ -0,0 +1,132 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reactive.Linq; +using System.Text; +using System.Threading.Tasks; +using bts.api; +using bts.api.admin; +using bts.api.core; +using bts.api.test; +using bts.test; +using bts.api.orderman; +using mbts; +using mbts.tests; +using bts.co2; +using bts.api.orderman.algo; + +namespace bts.tests { + [TestGroup(TestType = TestType.System)] + public class AlgoDefinitionTests : IDisposable { + List _resources; + ServiceContext _context; + //OrderService _order_service; + AdminService _admin_service; + AlgoDefinitionService _algo_definition_service; + IEnumerable _non_deleted_defs; + Random _rng = new Random(); + + public AlgoDefinitionTests() { + _context = new ServiceContext(); + //_order_service = _context.locate(); + _admin_service = _context.locate(); + _algo_definition_service = _context.locate(); + + _resources = new List { + _context, + _admin_service, + _algo_definition_service, + _algo_definition_service.subscribei_algo_definitions().Subscribe(defs => _non_deleted_defs = defs.all.Where( x => x.Metadata.IsActive)) + }; + + var auth = _context.login("bts", ""); + auth.Wait(3000); + } + + [Test(Timeout = 25)] + public async Task test_crud_algo_definitions() { + var created_algo_records = new List(); + var watch = new System.Diagnostics.Stopwatch(); + watch.Start(); + var user_data = await AdminUtilities.get_user_data(_admin_service, "bts"); + int num_created = 0; + if (user_data.HasValue) { + // create 100 algo defs + while (num_created < 100) { + var result = await _algo_definition_service.save_algo_definition_async( + new AlgoDefinitionUpdateRequest { + UserId = user_data.Value.Id, + Key = 0, + Algo = generate_random_algo_definition() + } + ); + Assert.IsTrue(result.value.Success, "There was a problem creating an algo defintion"); + created_algo_records.Add(result.value.Record); + num_created++; + } + + // update the 100 we just created algo defs + foreach(var r in created_algo_records) { + var def = r.Algo; + def.Name += " modified"; + await _algo_definition_service.save_algo_definition_async( + new AlgoDefinitionUpdateRequest { + UserId = user_data.Value.Id, + Key = r.Key, + Algo = def + } + ); + } + + // delete all non-deleted algo defs + Assert.IsTrue(_non_deleted_defs.Count() > 0, "There are no algo definitions to delete."); + foreach (var i in _non_deleted_defs.Select(x => x.Key).ToList()) { + var result = await _algo_definition_service.remove_algo_definition_async(new AlgoDefinitionRemoveRequest { Key = i }); + Assert.IsTrue(result.value.Success, "There was a problem removing an algo definition"); + } + Assert.IsTrue(_non_deleted_defs.Count() == 0, "There was a problem removing all algo definitions"); + + watch.Stop(); + Console.WriteLine($"Execution Time: {watch.ElapsedMilliseconds} ms"); + } + } + + // not quite random yet + private AlgoDefinition generate_random_algo_definition() { + return new AlgoDefinition { + Definition = new CustomOrderDefinition { + Iceberg = new IcebergOrderDefinition { + ShowQuantity = _rng.NextDouble() * 100, + Child = new CustomOrderDefinition { + Limit = new LimitOrderDefinition { } + } + }, + }, + Name = $"Test Algo Def: {generate_name(_rng, _rng.Next(4, 15))}" + }; + } + + // https://stackoverflow.com/questions/14687658/random-name-generator-in-c-sharp + public static string generate_name(Random r, int len) { + string[] consonants = { "b", "c", "d", "f", "g", "h", "j", "k", "l", "m", "l", "n", "p", "q", "r", "s", "sh", "zh", "t", "v", "w", "x" }; + string[] vowels = { "a", "e", "i", "o", "u", "ae", "y" }; + string name = ""; + name += consonants[r.Next(consonants.Length)].ToUpper(); + name += vowels[r.Next(vowels.Length)]; + int b = 2; //b tells how many times a new letter has been added. It's 2 right now because the first two letters are already in the name. + while (b < len) { + name += consonants[r.Next(consonants.Length)]; + b++; + name += vowels[r.Next(vowels.Length)]; + b++; + } + return name; + } + + public void Dispose() { + Disposable.dispose(_resources); + } + + } + +} diff --git a/src/client/spark_test/System/IcebergAlgoTests.cs b/src/client/spark_test/System/IcebergAlgoTests.cs new file mode 100644 index 000000000..fc4e073aa --- /dev/null +++ b/src/client/spark_test/System/IcebergAlgoTests.cs @@ -0,0 +1,124 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reactive.Linq; +using System.Text; +using System.Threading.Tasks; +using bts.api; +using bts.api.admin; +using bts.api.core; +using bts.test; +using bts.api.orderman; +using mbts; +using bts.co2; +using bts.tests.utils; + +namespace bts.tests { + + [TestGroup(TestType = TestType.System)] + class IcebergAlgoTests : TestBase { + public IcebergAlgoTests() { } + + [Test(Timeout = 25)] + public async Task test_ib_create_and_takeout_market() { + // find a security with no market + var s = await MarketDataUtilities.get_security(_md_relay, "CL", SecurityType.Future, update => update.Direct.Asks.Count == 0 && update.Direct.Bids.Count == 0); + Assert.IsTrue(s.HasValue, "Could not find a security with no maket"); + + // create a market in the instrument + List> orders_response_list = new List>(); + var bid_order_def = OrderDefinitionUtilities.create_limit_order_def(s.Value.Id, Side.Buy, _test_account, _test_user); + var ask_order_def = OrderDefinitionUtilities.create_limit_order_def(s.Value.Id, Side.Sell, _test_account, _test_user); + orders_response_list.Add(await OrderUtilities.send_order(_order_service, bid_order_def, 55.00, 50)); + orders_response_list.Add(await OrderUtilities.send_order(_order_service, ask_order_def, 55.05, 50)); + List test_orders = new List(); + foreach (var i in orders_response_list) { + var iret = (await OrderUtilities.wait_for_filtered_orders( + _order_service, + rows => rows.Where(o => o.Key == i.value.OrderKey && o.HasState && o.State.Status == OrderStatus.Working).Count() == 1, + rows => rows.Where(o => o.Key == i.value.OrderKey))).result ?? Enumerable.Empty(); + Assert.IsTrue(iret.Count() == 1, "This order should have been 'working'"); + test_orders.AddRange(iret); + } + + // create an IB that will cross this market + var ib_order_def = OrderDefinitionUtilities.create_iceberg_order_def(s.Value.Id, Side.Buy, _test_account, _test_user, 3); + var ib_order_result = await OrderUtilities.send_order(_order_service, ib_order_def, 55.05, 30); + var ib_filtered_order = (await OrderUtilities.wait_for_filtered_orders( + _order_service, + rows => rows.Where(x => x.Key == ib_order_result.value.OrderKey && x.HasState && x.State.Status == OrderStatus.Completed).Count() == 1, + rows => rows.Where(x => x.Key == ib_order_result.value.OrderKey))).result ?? Enumerable.Empty(); + var ib_child_orders = (await OrderUtilities.wait_for_filtered_orders( + _order_service, + rows => rows.Where(x => x.ParentKey == ib_order_result.value.OrderKey && x.HasState && x.State.Status == OrderStatus.Completed).Count() == 10, + rows => rows.Where(x => x.ParentKey == ib_order_result.value.OrderKey))).result ?? Enumerable.Empty(); + + Assert.IsTrue(ib_filtered_order.Count() == 1, "This IB order should have been 'Completed'"); + Assert.IsTrue(ib_child_orders.Count() == 10, "There should have been 10 completed child orders"); + + var filled_childen = (await OrderUtilities.wait_for_filtered_fills( + _order_service, + rows => rows.Where(x => ib_child_orders.Select(o => o.Key).Contains(x.OrderKey)).Count() == 10, + rows => rows.Where(x => ib_child_orders.Select(o => o.Key).Contains(x.OrderKey)))).result ?? Enumerable.Empty(); + + Assert.IsTrue(filled_childen.Count() == 10, "There should have been 10 fills"); + Assert.IsTrue(filled_childen.All(x => + TestUtils.test_price_equality(x.LastPrice, 55.05, s.Value.ContractSpec.ticksize(x.LastPrice)) && x.LastShares == 3), "All child fills should have been filled at price 55.50 with quantity 3"); + + // cleanup + Assert.IsTrue(await OrderUtilities.cancel_orders(_order_service, test_orders), "Unable to cancel test orders"); + } + + [Test(Timeout = 25)] + public async Task test_ib_avg_fill() { + // find a security with no market + var s = await MarketDataUtilities.get_security(_md_relay, "CL", SecurityType.Future, update => update.Direct.Asks.Count == 0 && update.Direct.Bids.Count == 0); + Assert.IsTrue(s.HasValue, "Could not find a security with no maket"); + + // create a market in the instrument + List> orders_response_list = new List>(); + var bid_order_def = OrderDefinitionUtilities.create_limit_order_def(s.Value.Id, Side.Buy, _test_account, _test_user); + var ask_order_def = OrderDefinitionUtilities.create_limit_order_def(s.Value.Id, Side.Sell, _test_account, _test_user); + orders_response_list.Add(await OrderUtilities.send_order(_order_service, ask_order_def, 56.02, 1)); + orders_response_list.Add(await OrderUtilities.send_order(_order_service, ask_order_def, 56.01, 1)); + orders_response_list.Add(await OrderUtilities.send_order(_order_service, ask_order_def, 56.00, 1)); + orders_response_list.Add(await OrderUtilities.send_order(_order_service, ask_order_def, 55.50, 5)); + orders_response_list.Add(await OrderUtilities.send_order(_order_service, ask_order_def, 55.01, 20)); + orders_response_list.Add(await OrderUtilities.send_order(_order_service, bid_order_def, 55.00, 1)); + orders_response_list.Add(await OrderUtilities.send_order(_order_service, bid_order_def, 54.99, 1)); + orders_response_list.Add(await OrderUtilities.send_order(_order_service, bid_order_def, 54.98, 1)); + orders_response_list.Add(await OrderUtilities.send_order(_order_service, bid_order_def, 54.97, 1)); + orders_response_list.Add(await OrderUtilities.send_order(_order_service, bid_order_def, 54.96, 1)); + orders_response_list.Add(await OrderUtilities.send_order(_order_service, bid_order_def, 54.95, 1)); + List test_orders = new List(); + foreach (var i in orders_response_list) { + var iret = (await OrderUtilities.wait_for_filtered_orders( + _order_service, + rows => rows.Where(o => o.Key == i.value.OrderKey && o.HasState && o.State.Status == OrderStatus.Working).Count() == 1, + rows => rows.Where(o => o.Key == i.value.OrderKey))).result ?? Enumerable.Empty(); + Assert.IsTrue(iret.Count() == 1, "This order should have been 'working'"); + test_orders.AddRange(iret); + } + + // create an IB that will cross this market + var ib_order_def = OrderDefinitionUtilities.create_iceberg_order_def(s.Value.Id, Side.Buy, _test_account, _test_user, 1); + var ib_order_result = await OrderUtilities.send_order(_order_service, ib_order_def, 56.02, 26); + var ib_filtered_order = (await OrderUtilities.wait_for_filtered_orders( + _order_service, + rows => rows.Where(x => x.Key == ib_order_result.value.OrderKey && x.HasState && x.State.Status == OrderStatus.Completed).Count() == 1, + rows => rows.Where(x => x.Key == ib_order_result.value.OrderKey))).result ?? Enumerable.Empty(); + var ib_child_orders = (await OrderUtilities.wait_for_filtered_orders( + _order_service, + rows => rows.Where(x => x.ParentKey == ib_order_result.value.OrderKey && x.HasState && x.State.Status == OrderStatus.Completed).Count() == 10, + rows => rows.Where(x => x.ParentKey == ib_order_result.value.OrderKey))).result ?? Enumerable.Empty(); + + Assert.IsTrue(ib_filtered_order.Count() == 1, "This IB order should have been 'Completed'"); + Assert.IsTrue(ib_filtered_order.All(x => + TestUtils.test_price_equality(x.State.AvgPrice, 55.1423, s.Value.ContractSpec.ticksize(x.State.AvgPrice))), "IB avg price should be 55.1423"); + + // cleanup + Assert.IsTrue(await OrderUtilities.cancel_orders(_order_service, test_orders), "Unable to cancel test orders"); + } + + } +} diff --git a/src/client/spark_test/System/JoinAlgoTests.cs b/src/client/spark_test/System/JoinAlgoTests.cs new file mode 100644 index 000000000..a98c4f1bb --- /dev/null +++ b/src/client/spark_test/System/JoinAlgoTests.cs @@ -0,0 +1,194 @@ +using bts.api; +using bts.api.core; +using bts.api.orderman; +using bts.test; +using bts.tests.utils; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reactive.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace bts.tests { + + /// + /// For buy orders: + /// triggers when: curr_bid.price > initial_bid && current_bid.qty >= join_threshold. + /// i.e. When the join is first entered, it looks at the market to capture the initial bid and + /// then it waits until the current bid is above that level AND that the qty at that level is greater + /// that some threshold. + /// + + [TestGroup(TestType = TestType.System)] + public class JoinAlgoTests : TestBase { + public JoinAlgoTests() { } + + [Test(Timeout = 25)] + public async Task test_join_price() { + double initial_price = 54.99; + double ask_price = 55.01; + + + // find a security with no market + var s = await MarketDataUtilities.get_security(_md_relay, "CL", SecurityType.Future, update => update.Direct.Asks.Count == 0 && update.Direct.Bids.Count == 0); + Assert.IsTrue(s.HasValue, "Could not find a security with no maket"); + + // create a market in the instrument + List> orders_response_list = new List>(); + var bid_order_def = OrderDefinitionUtilities.create_limit_order_def(s.Value.Id, Side.Buy, _test_account, _test_user); + var ask_order_def = OrderDefinitionUtilities.create_limit_order_def(s.Value.Id, Side.Sell, _test_account, _test_user); + orders_response_list.Add(await OrderUtilities.send_order(_order_service, bid_order_def, 55.00, 10)); + orders_response_list.Add(await OrderUtilities.send_order(_order_service, ask_order_def, ask_price, 1)); + List test_orders = new List(); + foreach (var i in orders_response_list) { + var iret = (await OrderUtilities.wait_for_filtered_orders( + _order_service, + rows => rows.Where(o => o.Key == i.value.OrderKey && o.HasState && o.State.Status == OrderStatus.Working).Count() == 1, + rows => rows.Where(o => o.Key == i.value.OrderKey))).result ?? Enumerable.Empty(); + Assert.IsTrue(iret.Count() == 1, "This order should have been 'working'"); + test_orders.AddRange(iret); + } + + // create a join order + var join_order_def = OrderDefinitionUtilities.create_join_order_definition(s.Value.Id, Side.Buy, _test_account, _test_user, new spark.QuantityMeasure() { Absolute = 1 }); + var join_order_response = await OrderUtilities.send_order(_order_service, join_order_def, initial_price, 1); + var join_order = (await OrderUtilities.wait_for_filtered_orders( + _order_service, + rows => rows.Where(o => o.Key == join_order_response.value.OrderKey && o.HasState && o.State.Status == OrderStatus.Working).Count() == 1, + rows => rows.Where(o => o.Key == join_order_response.value.OrderKey))).result ?? Enumerable.Empty(); + Assert.IsTrue(join_order.Count() == 1, "The join order should have 'working'"); + test_orders.Add(join_order.First()); + + // verify the join order's child is working at the specefied price + // note: the price doesn't actually matter in the join order + var join_child_order = (await OrderUtilities.wait_for_filtered_orders( + _order_service, + rows => rows.Where(o => o.ParentKey == join_order.First().Key && + o.HasState && (o.State.Status == OrderStatus.Working && + TestUtils.test_price_equality(o.State.Price, initial_price, s.Value.ContractSpec.ticksize(o.State.Price)))).Count() == 1, + rows => rows.Where(o => o.ParentKey == join_order.First().Key))).result ?? Enumerable.Empty(); + Assert.IsTrue(join_child_order.Count() == 1, $"The join child order should have been 'working' at {initial_price}"); + + // now we move the best bid to become the best offer + var original_bid_order = test_orders.Where(o => o.Def.Side == Side.Buy).First(); + var bid_order_response = await OrderUtilities.modify_order(_order_service, original_bid_order, ask_price); + var modified_bid_order = (await OrderUtilities.wait_for_filtered_orders( + _order_service, + rows => rows.Where(o => o.Key == bid_order_response.value.OrderKey && o.HasState && + TestUtils.test_price_equality(o.State.Price, ask_price, s.Value.ContractSpec.ticksize(o.State.Price))).Count() == 1, + rows => rows.Where(o => o.Key == bid_order_response.value.OrderKey))).result ?? Enumerable.Empty(); + Assert.IsTrue(modified_bid_order.Count() == 1, "The working bid should have become the best offer"); + + // and we finally verify that the child order has joined the market at the appropriate price + join_child_order = (await OrderUtilities.wait_for_filtered_orders( + _order_service, + rows => rows.Where(o => o.ParentKey == join_order.First().Key && + o.HasState && (o.State.Status == OrderStatus.Working && + TestUtils.test_price_equality(o.State.Price, ask_price, s.Value.ContractSpec.ticksize(o.State.Price)))).Count() == 1, + rows => rows.Where(o => o.ParentKey == join_order.First().Key))).result ?? Enumerable.Empty(); + Assert.IsTrue(join_child_order.Count() == 1, $"The join child order should now have been 'working' at {ask_price}"); + test_orders.Add(join_child_order.First()); + + // cleanup + Assert.IsTrue(await OrderUtilities.cancel_orders(_order_service, test_orders), "Unable to cancel test orders"); + + } + + [Test(Timeout = 25)] + public async Task test_join_qty_threshold() { + double initial_price = 54.99; + double ask_price = 55.01; + uint ask_size = 1; + uint qty_threshold = 15; + + + // find a security with no market + var s = await MarketDataUtilities.get_security(_md_relay, "CL", SecurityType.Future, update => update.Direct.Asks.Count == 0 && update.Direct.Bids.Count == 0); + Assert.IsTrue(s.HasValue, "Could not find a security with no maket"); + + // create a market in the instrument + List> orders_response_list = new List>(); + var bid_order_def = OrderDefinitionUtilities.create_limit_order_def(s.Value.Id, Side.Buy, _test_account, _test_user); + var ask_order_def = OrderDefinitionUtilities.create_limit_order_def(s.Value.Id, Side.Sell, _test_account, _test_user); + orders_response_list.Add(await OrderUtilities.send_order(_order_service, bid_order_def, 55.00, 10)); + orders_response_list.Add(await OrderUtilities.send_order(_order_service, ask_order_def, ask_price, ask_size)); + List test_orders = new List(); + foreach (var i in orders_response_list) { + var iret = (await OrderUtilities.wait_for_filtered_orders( + _order_service, + rows => rows.Where(o => o.Key == i.value.OrderKey && o.HasState && o.State.Status == OrderStatus.Working).Count() == 1, + rows => rows.Where(o => o.Key == i.value.OrderKey))).result ?? Enumerable.Empty(); + Assert.IsTrue(iret.Count() == 1, "This order should have been 'working'"); + test_orders.AddRange(iret); + } + + // create a join order + var join_order_def = OrderDefinitionUtilities.create_join_order_definition(s.Value.Id, Side.Buy, _test_account, _test_user, new spark.QuantityMeasure() { Absolute = qty_threshold }); + var join_order_response = await OrderUtilities.send_order(_order_service, join_order_def, initial_price, 1); + var join_order = (await OrderUtilities.wait_for_filtered_orders( + _order_service, + rows => rows.Where(o => o.Key == join_order_response.value.OrderKey && o.HasState && o.State.Status == OrderStatus.Working).Count() == 1, + rows => rows.Where(o => o.Key == join_order_response.value.OrderKey))).result ?? Enumerable.Empty(); + Assert.IsTrue(join_order.Count() == 1, "The join order should have 'working'"); + test_orders.Add(join_order.First()); + + // verify the join order's child is working at the specefied price + // note: the price doesn't actually matter in the join order + var join_child_order = (await OrderUtilities.wait_for_filtered_orders( + _order_service, + rows => rows.Where(o => o.ParentKey == join_order.First().Key && + o.HasState && (o.State.Status == OrderStatus.Working && + TestUtils.test_price_equality(o.State.Price, initial_price, s.Value.ContractSpec.ticksize(o.State.Price)))).Count() == 1, + rows => rows.Where(o => o.ParentKey == join_order.First().Key))).result ?? Enumerable.Empty(); + Assert.IsTrue(join_child_order.Count() == 1, $"The join child order should have been 'working' at {initial_price}"); + + // now we move the best bid to become the best offer + var top_bid_order = test_orders.Where(o => o.Def.Side == Side.Buy).First(); + var bid_order_response = await OrderUtilities.modify_order(_order_service, top_bid_order, ask_price); + var modified_bid_order = (await OrderUtilities.wait_for_filtered_orders( + _order_service, + rows => rows.Where(o => o.Key == bid_order_response.value.OrderKey && o.HasState && + TestUtils.test_price_equality(o.State.Price, ask_price, s.Value.ContractSpec.ticksize(o.State.Price))).Count() == 1, + rows => rows.Where(o => o.Key == bid_order_response.value.OrderKey))).result ?? Enumerable.Empty(); + Assert.IsTrue(modified_bid_order.Count() == 1, "The working bid should have become the best offer"); + + // verify the join order's child is *still* working at the initial price + // b/c the quantity threshold has not yet been met + join_child_order = (await OrderUtilities.wait_for_filtered_orders( + _order_service, + rows => rows.Where(o => o.ParentKey == join_order.First().Key && + o.HasState && (o.State.Status == OrderStatus.Working && + TestUtils.test_price_equality(o.State.Price, initial_price, s.Value.ContractSpec.ticksize(o.State.Price)))).Count() == 1, + rows => rows.Where(o => o.ParentKey == join_order.First().Key))).result ?? Enumerable.Empty(); + Assert.IsTrue(join_child_order.Count() == 1, $"The join child order should still have been 'working' at {initial_price}"); + + // now we modify our top bid's volume to meet the join's threshold + // note that we must add the intial ask_size to the qty_threshold b/c we have partially filled our bid order + // when we moved the bid up. + var target_qty = qty_threshold + ask_size; + bid_order_response = await OrderUtilities.modify_order(_order_service, modified_bid_order.First(), target_qty); + modified_bid_order = (await OrderUtilities.wait_for_filtered_orders( + _order_service, + rows => rows.Where(o => o.Key == bid_order_response.value.OrderKey && o.HasState && o.State.Quantity == target_qty).Count() == 1, + rows => rows.Where(o => o.Key == bid_order_response.value.OrderKey))).result ?? Enumerable.Empty(); + Assert.IsTrue(modified_bid_order.Count() == 1, $"The working bid should have its quantity modified to {target_qty}"); + + // now that the qty threshold has been met, verify that the child order has joined the market at the appropriate price + join_child_order = (await OrderUtilities.wait_for_filtered_orders( + _order_service, + rows => rows.Where(o => o.ParentKey == join_order.First().Key && + o.HasState && (o.State.Status == OrderStatus.Working && + TestUtils.test_price_equality(o.State.Price, ask_price, s.Value.ContractSpec.ticksize(o.State.Price)))).Count() == 1, + rows => rows.Where(o => o.ParentKey == join_order.First().Key))).result ?? Enumerable.Empty(); + Assert.IsTrue(join_child_order.Count() == 1, $"The join child order should now have been 'working' at {ask_price}"); + test_orders.Add(join_child_order.First()); + + // cleanup + Assert.IsTrue(await OrderUtilities.cancel_orders(_order_service, test_orders), "Unable to cancel test orders"); + } + + + } + +} diff --git a/src/client/spark_test/System/LeanAlgoTests.cs b/src/client/spark_test/System/LeanAlgoTests.cs new file mode 100644 index 000000000..2f39c7331 --- /dev/null +++ b/src/client/spark_test/System/LeanAlgoTests.cs @@ -0,0 +1,144 @@ +using bts.api; +using bts.api.core; +using bts.api.orderman; +using bts.test; +using bts.tests.utils; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reactive.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace bts.tests { + + [TestGroup(TestType = TestType.System)] + public class LeanAlgoTests : TestBase { + + public LeanAlgoTests() { } + + [Test(Timeout = 25)] + public async Task test_lean_price() { + double initial_price = 54.98; + double ask_price_1 = 55.00; + double ask_price_2 = 55.01; + uint ask_size = 10; + uint lean_order_size = 30; + uint cross_threshold = ask_size - 1; + + // find a security with no market + var s = await MarketDataUtilities.get_security(_md_relay, "CL", SecurityType.Future, update => update.Direct.Asks.Count == 0 && update.Direct.Bids.Count == 0); + Assert.IsTrue(s.HasValue, "Could not find a security with no maket"); + + // create a market in the instrument + List> orders_response_list = new List>(); + var bid_order_def = OrderDefinitionUtilities.create_limit_order_def(s.Value.Id, Side.Buy, _test_account, _test_user); + var ask_order_def = OrderDefinitionUtilities.create_limit_order_def(s.Value.Id, Side.Sell, _test_account, _test_user); + orders_response_list.Add(await OrderUtilities.send_order(_order_service, bid_order_def, 54.99, 1)); + orders_response_list.Add(await OrderUtilities.send_order(_order_service, ask_order_def, ask_price_1, ask_size)); + orders_response_list.Add(await OrderUtilities.send_order(_order_service, ask_order_def, ask_price_2, ask_size)); + orders_response_list.Add(await OrderUtilities.send_order(_order_service, ask_order_def, ask_price_2 + 0.01, ask_size)); + orders_response_list.Add(await OrderUtilities.send_order(_order_service, ask_order_def, ask_price_2 + 0.02, ask_size)); + List test_orders = new List(); + foreach (var i in orders_response_list) { + var iret = (await OrderUtilities.wait_for_filtered_orders( + _order_service, + rows => rows.Where(o => o.Key == i.value.OrderKey && o.HasState && o.State.Status == OrderStatus.Working).Count() == 1, + rows => rows.Where(o => o.Key == i.value.OrderKey))).result ?? Enumerable.Empty(); + Assert.IsTrue(iret.Count() == 1, "This order should have been 'working'"); + test_orders.AddRange(iret); + } + + // create a lean order, 2 tick chase (default) + var lean_order_def = OrderDefinitionUtilities.create_lean_order_definition(s.Value.Id, Side.Buy, _test_account, _test_user, new spark.QuantityMeasure() { Absolute = cross_threshold }); + var lean_order_response = await OrderUtilities.send_order(_order_service, lean_order_def, initial_price, lean_order_size); + var lean_order = (await OrderUtilities.wait_for_filtered_orders( + _order_service, + rows => rows.Where(o => o.Key == lean_order_response.value.OrderKey && o.HasState && o.State.Status == OrderStatus.Working).Count() == 1, + rows => rows.Where(o => o.Key == lean_order_response.value.OrderKey))).result ?? Enumerable.Empty(); + Assert.IsTrue(lean_order.Count() == 1, "The lean order should have 'working'"); + test_orders.Add(lean_order.First()); + + // verify the lean order's child is working at the specified price + // note: the price doesn't actually matter in the lean order + var lean_child_order = (await OrderUtilities.wait_for_filtered_orders( + _order_service, + rows => rows.Where(o => o.ParentKey == lean_order.First().Key && + o.HasState && (o.State.Status == OrderStatus.Working && + TestUtils.test_price_equality(o.State.Price, initial_price, s.Value.ContractSpec.ticksize(o.State.Price)))).Count() == 1, + rows => rows.Where(o => o.ParentKey == lean_order.First().Key))).result ?? Enumerable.Empty(); + Assert.IsTrue(lean_child_order.Count() == 1, $"The lean child order should have been 'working' at {initial_price}"); + + // now we modify the opposite inside market qty to breach the lean threshold + var target_ask_order = test_orders.Where(o => o.Def.Side == Side.Sell && + TestUtils.test_price_equality(o.State.Price, ask_price_1, s.Value.ContractSpec.ticksize(o.State.Price))).First(); + var ask_order_response = await OrderUtilities.modify_order(_order_service, target_ask_order, cross_threshold); + var modified_ask_order = (await OrderUtilities.wait_for_filtered_orders( + _order_service, + rows => rows.Where(o => o.Key == ask_order_response.value.OrderKey && o.HasState && + o.State.Quantity == cross_threshold).Count() == 1, + rows => rows.Where(o => o.Key == ask_order_response.value.OrderKey))).result ?? Enumerable.Empty(); + Assert.IsTrue(modified_ask_order.Count() == 1, "The opposite inside market should have been adjusted to the Lean's cross threshold"); + + // verify that the child order has leaned into the market at the appropriate price and been parially filled appropriately + // this is the initial trigger payup + lean_child_order = (await OrderUtilities.wait_for_filtered_orders( + _order_service, + rows => rows.Where(o => o.ParentKey == lean_order.First().Key && + o.HasState && ( + o.State.Status == OrderStatus.Working && + TestUtils.test_price_equality(o.State.Price, ask_price_1, s.Value.ContractSpec.ticksize(o.State.Price)) && + o.State.FilledQuantity == 9) + ).Count() == 1, + rows => rows.Where(o => o.ParentKey == lean_order.First().Key))).result ?? Enumerable.Empty(); + Assert.IsTrue(lean_child_order.Count() == 1, $"Initial trigger: The lean child order should now have been 'working' at {ask_price_1}"); + test_orders.Add(lean_child_order.First()); + + // now we modify the opposite inside market qty again to start checking that the case is working + target_ask_order = test_orders.Where(o => o.Def.Side == Side.Sell && + TestUtils.test_price_equality(o.State.Price, ask_price_2, s.Value.ContractSpec.ticksize(o.State.Price))).First(); + ask_order_response = await OrderUtilities.modify_order(_order_service, target_ask_order, cross_threshold); + modified_ask_order = (await OrderUtilities.wait_for_filtered_orders( + _order_service, + rows => rows.Where(o => o.Key == ask_order_response.value.OrderKey && o.HasState && + o.State.Quantity == cross_threshold).Count() == 1, + rows => rows.Where(o => o.Key == ask_order_response.value.OrderKey))).result ?? Enumerable.Empty(); + Assert.IsTrue(modified_ask_order.Count() == 1, "The opposite inside market should have been adjusted to the Lean's cross threshold"); + + // verify that the child order has chased and that it's filled quantity has increased + lean_child_order = (await OrderUtilities.wait_for_filtered_orders( + _order_service, + rows => rows.Where(o => o.ParentKey == lean_order.First().Key && + o.HasState && ( + o.State.Status == OrderStatus.Working && + TestUtils.test_price_equality(o.State.Price, ask_price_2, s.Value.ContractSpec.ticksize(o.State.Price)) && + o.State.FilledQuantity == 9) + ).Count() == 1, + rows => rows.Where(o => o.ParentKey == lean_order.First().Key))).result ?? Enumerable.Empty(); + Assert.IsTrue(lean_child_order.Count() == 1, $"First Chase: The lean child order should now have been 'working' at {ask_price_1}"); + test_orders.Add(lean_child_order.First()); + + // TODO: + // verify the parent order also reflects the increase filled quantity from the child order + + // TODO: + // instigate another chase + + // TODO: + // verify parent order again reflects + + // TODO: + // instigate another chanse + + // TODO: + // verify we are *not* chasing any longer, verify appropriate order statuses + + + + // cleanup + Assert.IsTrue(await OrderUtilities.cancel_orders(_order_service, test_orders), "Unable to cancel test orders"); + + } + + } +} diff --git a/src/client/spark_test/System/LimitsTests.cs b/src/client/spark_test/System/LimitsTests.cs index c5f6807cc..0a3357561 100644 --- a/src/client/spark_test/System/LimitsTests.cs +++ b/src/client/spark_test/System/LimitsTests.cs @@ -13,6 +13,7 @@ using bts.api.orderman; using mbts; using mbts.tests; using bts.co2; +using bts.tests.utils; namespace bts.tests { @@ -43,6 +44,7 @@ namespace bts.tests Disposable.dispose(ref _order_service); Disposable.dispose(ref _admin_service); Disposable.dispose(ref _context); + Disposable.dispose(ref _order_subscription); } async Task> all_futures(string symbol) { @@ -78,28 +80,31 @@ namespace bts.tests return securities; } - [Test(Timeout = 30)] + [Test(Timeout = 300)] public async Task test_position_limits() { + bool system_ready = await TestUtils.test_for_system_ready(_context, TimeSpan.FromMinutes(5)); + Assert.IsTrue(system_ready, "System is not ready"); + string test_symbol = "CL"; var test_user = ( name: "bts", id: 0u ); var test_account = ( name: "ACC A", id: 0u ); - BTSAccountImmutable? account_data = await AdminUtilities.get_account_data(_admin_service, test_account.name); + var account_task = AdminUtilities.get_account_data(_admin_service, test_account.name); + BTSAccountImmutable? account_data = await TestUtils.await_with_timeout(account_task, TimeSpan.FromMinutes(0.5)); + Assert.IsTrue(account_data.HasValue); test_account.id = account_data.Value.Id; - var user_data = await AdminUtilities.get_user_data(_admin_service, test_user.name); Assert.IsTrue(user_data.HasValue); test_user.id = user_data.Value.Id; - var clip_set_success = await AdminUtilities.set_clip_limit(_admin_service, 10000, account_data, test_symbol); Assert.IsTrue(clip_set_success, "Failed to set clip limit "); var all_securities = await all_futures(test_symbol); List security_list = all_securities.ToList(); - Assert.IsTrue(all_securities.Count() >= 2); + Assert.IsTrue(all_securities.Count() >= 2, "At least two securities are needed"); SecurityImmutable first_sec = security_list[0]; SecurityImmutable second_sec = security_list[1]; @@ -109,10 +114,11 @@ namespace bts.tests var second_order_def = create_order_def(second_sec.Id, Side.Buy, test_account, test_user); - Result no_limit_order_result = await send_order(first_order_def, 5, 1); + Result no_limit_order_result = await OrderUtilities.send_order(_order_service, first_order_def, 5, 1); IEnumerable no_limit_filtered_orders = await get_filtered_orders(x => x.Key == no_limit_order_result.value.OrderKey); + Assert.IsNotNull(no_limit_filtered_orders, "No orders retrieved"); Assert.IsTrue(no_limit_filtered_orders.First().State.Status == OrderStatus.RejectedBySpark, "'Absent Limit' Order is not 'Rejected by Spark'"); bool position_set_success = await AdminUtilities.set_position_limit(_admin_service, test_account.name, test_symbol, 60, 120); @@ -121,11 +127,11 @@ namespace bts.tests List> orders_response_list = new List>(); for(int i = 0; i <3; i++){ - orders_response_list.Add(await send_order(first_order_def, 5, 10)); + orders_response_list.Add(await OrderUtilities.send_order(_order_service, first_order_def, 5, 10)); } for(int i = 0; i <3; i++){ - orders_response_list.Add(await send_order(second_order_def, 5, 10)); + orders_response_list.Add(await OrderUtilities.send_order(_order_service, second_order_def, 5, 10)); } foreach(var i in orders_response_list){ @@ -133,24 +139,24 @@ namespace bts.tests Assert.IsTrue(iret.First().State.Status == OrderStatus.Working, "This order should have been 'working'"); } - var fail_order_result = await send_order(first_order_def, 5, 1); + var fail_order_result = await OrderUtilities.send_order(_order_service, first_order_def, 5, 1); var fail_order_filtered_orders = await get_filtered_orders(x => x.Key == fail_order_result.value.OrderKey); Assert.IsTrue(fail_order_filtered_orders.First().State.Status == OrderStatus.RejectedBySpark, "This order should have been 'Rejected by Spark'"); bool position_increase_success = await AdminUtilities.set_position_limit(_admin_service, test_account.name, test_symbol, 70, 120); Assert.IsTrue(position_increase_success); - var increased_order_result = await send_order(first_order_def, 5, 10); + var increased_order_result = await OrderUtilities.send_order(_order_service, first_order_def, 5, 10); var increased_order_filtered_orders = await get_filtered_orders(x => x.Key == increased_order_result.value.OrderKey); Assert.IsTrue(increased_order_filtered_orders.First().State.Status == OrderStatus.Working, "This order should have been 'Working'"); - var second_fail_order_result = await send_order(first_order_def, 5, 10); + var second_fail_order_result = await OrderUtilities.send_order(_order_service, first_order_def, 5, 10); var second_fail_filtered_orders = await get_filtered_orders(x => x.Key == second_fail_order_result.value.OrderKey); Assert.IsTrue(second_fail_filtered_orders.First().State.Status == OrderStatus.RejectedBySpark, "This order should have been 'Rejected by Spark'"); /* Test Short Position Limit */ - Assert.IsTrue(await cancel_orders(), "Unable to cancel orders"); + Assert.IsTrue(await OrderUtilities.cancel_orders(_order_service, _orders.all), "Unable to cancel orders"); await AdminUtilities.remove_position_limit(_admin_service, test_account.name, test_symbol); @@ -162,7 +168,7 @@ namespace bts.tests uint short_no_limit_order_key; - Result short_no_limit_order_result = await send_order(first_short_order_def, 50000, 7); + Result short_no_limit_order_result = await OrderUtilities.send_order(_order_service, first_short_order_def, 50000, 7); short_no_limit_order_key = short_no_limit_order_result.value.OrderKey; IEnumerable short_no_limit_filtered_orders = await get_filtered_orders(x => x.Key == short_no_limit_order_key); @@ -175,11 +181,11 @@ namespace bts.tests List> short_orders_response_list = new List>(); for(int i = 0; i <3; i++){ - short_orders_response_list.Add(await send_order(first_short_order_def, 50000, 10)); + short_orders_response_list.Add(await OrderUtilities.send_order(_order_service, first_short_order_def, 50000, 10)); } for(int i = 0; i <3; i++){ - short_orders_response_list.Add(await send_order(second_short_order_def, 50000, 10)); + short_orders_response_list.Add(await OrderUtilities.send_order(_order_service, second_short_order_def, 50000, 10)); } foreach(var i in short_orders_response_list){ @@ -187,22 +193,22 @@ namespace bts.tests Assert.IsTrue(iret.First().State.Status == OrderStatus.Working, "This order should have been 'working'"); } - var short_fail_order_result = await send_order(first_short_order_def, 50000, 1); + var short_fail_order_result = await OrderUtilities.send_order(_order_service, first_short_order_def, 50000, 1); var short_fail_order_filtered_orders = await get_filtered_orders(x => x.Key == short_fail_order_result.value.OrderKey); Assert.IsTrue(short_fail_order_filtered_orders.First().State.Status == OrderStatus.RejectedBySpark, "This order should have been 'Rejected by Spark'"); bool short_position_increase_success = await AdminUtilities.set_position_limit(_admin_service, test_account.name, test_symbol, 120, 70); Assert.IsTrue(short_position_increase_success); - var short_increased_order_result = await send_order(first_short_order_def, 50000, 10); + var short_increased_order_result = await OrderUtilities.send_order(_order_service, first_short_order_def, 50000, 10); var short_increased_order_filtered_orders = await get_filtered_orders(x => x.Key == short_increased_order_result.value.OrderKey); Assert.IsTrue(short_increased_order_filtered_orders.First().State.Status == OrderStatus.Working, "This order should have been 'Working'"); - var short_second_fail_order_result = await send_order(first_short_order_def, 50000, 10); + var short_second_fail_order_result = await OrderUtilities.send_order(_order_service, first_short_order_def, 50000, 10); var short_second_fail_filtered_orders = await get_filtered_orders(x => x.Key == short_second_fail_order_result.value.OrderKey); Assert.IsTrue(short_second_fail_filtered_orders.First().State.Status == OrderStatus.RejectedBySpark, "This order should have been 'Rejected by Spark'"); - Assert.IsTrue(await cancel_orders(), "Unable to cancel orders"); + Assert.IsTrue(await OrderUtilities.cancel_orders(_order_service, _orders.all), "Unable to cancel orders"); } @@ -286,6 +292,7 @@ namespace bts.tests } Assert.IsTrue(success, "Failed to restore Limit"); + Assert.IsTrue(await OrderUtilities.cancel_orders(_order_service, _orders.all), "Unable to cancel orders"); } @@ -305,40 +312,12 @@ namespace bts.tests } await Task.Delay(100); } - while(it < 100 &&(_orders == null || current_count < count)); + while(it < 100 && (_orders == null || current_count < count)); return null; } - - public async Task> send_order(OrderDefinition order_def, double price, uint size){ - return await _order_service.create_order_async(new Create() { - NewOrder = order_def, - Price = price, - Quantity = size - }); - } - - public async Task cancel_orders(uint key = 0){ - if (key > 0) { - Result resp = await _order_service.cancel_order_async(new Cancel() { OrderKey = key }); - return resp.success; - } - else { - bool suc = true; - var working_orders = await get_filtered_orders(x => x.State.Status == OrderStatus.Working); - if(working_orders != null){ - foreach (var o in working_orders){ - Result resp = await _order_service.cancel_order_async(new Cancel() { OrderKey = o.Key }); - suc &= resp.success; - } - return suc; - } - return true;// there are no working orders... so true enough - } - } - public OrderDefinition create_order_def(uint security_id, Side side, (String name, uint id) account, (String name, uint id) user){ return new OrderDefinition { SecurityKey = security_id, @@ -358,218 +337,4 @@ namespace bts.tests } - public class AdminUtilities { - - public static async Task get_account_data (AdminService admin_service, string account_name) - { - Update update = await admin_service.subscribei_admin_data().FirstAsync(); - - foreach (var acc in update.all.First().Accounts) { - if(acc.Name == account_name) { - return acc; - } - } - return null; - } - - public static async Task get_user_data (AdminService admin_service, string user_name) - { - Update update = await admin_service.subscribei_admin_data().FirstAsync(); - - foreach (var usr in update.all.First().Users) { - if(usr.Name == user_name) { - return usr; - } - } - return null; - } - - public static AccountSecurityClipLimitUnitImmutable? get_clip_limit_row(BTSAccountImmutable? account_data, string symbol, SecurityType security_type = SecurityType.Future, Venue venue = Venue.Sim) { - IEnumerable clip_limit_rows = account_data.Value.SecurityClipLimits.Limit.Where( - r => r.Security.SecuritySymbol == symbol - && r.Security.Exchange == venue - && r.Security.SecurityType == security_type); - return clip_limit_rows.Any() ? clip_limit_rows.First() : (AccountSecurityClipLimitUnitImmutable?) null; - } - - public static uint? get_clip_limit(BTSAccountImmutable? account_data, string symbol, SecurityType security_type = SecurityType.Future, Venue venue = Venue.Sim) { - var row = get_clip_limit_row(account_data,symbol,security_type,venue); - return row.HasValue ? row.Value.ClipSize : (uint?) null; - } - - public static async Task get_clip_limit(AdminService admin_service, string account_name, string symbol, SecurityType security_type = SecurityType.Future, Venue venue = Venue.Sim) { - var account_data = await get_account_data(admin_service, account_name); - return get_clip_limit(account_data, symbol, security_type, venue); - } - - public static async Task set_clip_limit(AdminService admin_service, uint clip_value, string account_name, string symbol, SecurityType security_type = SecurityType.Future, Venue venue = Venue.Sim) { - var account_data = await get_account_data(admin_service, account_name); - return await set_clip_limit(admin_service, clip_value,account_data, symbol,security_type, venue); - } - - public static async Task set_clip_limit(AdminService admin_service, uint clip_value, BTSAccountImmutable? account_data, string symbol, SecurityType security_type = SecurityType.Future, Venue venue = Venue.Sim) { - - AccountSecurityClipLimitUnitImmutable? origin_clip_limit_row = get_clip_limit_row(account_data,symbol,security_type,venue); - AccountSecurityClipLimitUnitImmutable new_clip_limit_row; - - List clip_limits_list = account_data.Value.SecurityClipLimits.Limit.ToList(); - - if(origin_clip_limit_row.HasValue) { - clip_limits_list.Remove(origin_clip_limit_row.Value); - } - - new_clip_limit_row = (AccountSecurityClipLimitUnitImmutable) new AccountSecurityClipLimitUnit { - Security = new SecurityScope(){ SecuritySymbol = symbol, Exchange = venue, SecurityType = security_type }, - ClipSize = clip_value - }; - - clip_limits_list.Add(new_clip_limit_row); - - AccountSecurityClipLimits temp_scl = new AccountSecurityClipLimits(); - temp_scl.Limit.AddRange(clip_limits_list.Select(x => x.CloneToMutable())); - - var new_account_data = account_data.Value.with(security_clip_limits: temp_scl); - - var update_ret = await admin_service.update_account_async(new AccountUpdateAPIArgument { - CompleteData = new_account_data.CloneToMutable() - }); - - return update_ret.success; - } - - public static async Task clear_all_limits(AdminService admin_service, string account_name) { - var account_data = await get_account_data(admin_service, account_name); - return await clear_all_limits(admin_service, account_data); - } - - public static async Task clear_all_limits(AdminService admin_service, BTSAccountImmutable? account_data) { - var new_account_data = account_data.Value.with(security_clip_limits: new AccountSecurityClipLimits(), product_position_limits: new List()); - - var update_ret = await admin_service.update_account_async(new AccountUpdateAPIArgument { - CompleteData = new_account_data.CloneToMutable() - }); - - return update_ret.success; - } - - - public static async Task remove_clip_limit(AdminService admin_service, string account_name, string symbol, SecurityType security_type = SecurityType.Future, Venue venue = Venue.Sim) { - var account_data = await get_account_data(admin_service, account_name); - return await remove_clip_limit(admin_service, account_data, symbol, security_type, venue); - } - - public static async Task remove_clip_limit(AdminService admin_service, BTSAccountImmutable? account_data, string symbol, SecurityType security_type = SecurityType.Future, Venue venue = Venue.Sim) { - - AccountSecurityClipLimitUnitImmutable? origin_clip_limit_row = get_clip_limit_row(account_data,symbol,security_type,venue); - List clip_limits_list = account_data.Value.SecurityClipLimits.Limit.ToList(); - - if(origin_clip_limit_row.HasValue) { - clip_limits_list.Remove(origin_clip_limit_row.Value); - AccountSecurityClipLimits temp_scl = new AccountSecurityClipLimits(); - temp_scl.Limit.AddRange(clip_limits_list.Select(x => x.CloneToMutable())); - var new_account_data = account_data.Value.with(security_clip_limits: temp_scl); - - var update_ret = await admin_service.update_account_async(new AccountUpdateAPIArgument { - CompleteData = new_account_data.CloneToMutable() - }); - - return update_ret.success; - } - else - { - return false; - } - } - - - public static async Task get_position_limit_row(AdminService admin_service, string account_name, string symbol, SecurityType security_type = SecurityType.Future, Venue venue = Venue.Sim) { - var account_data = await get_account_data(admin_service, account_name); - return get_position_limit_row(account_data, symbol, security_type, venue); - } - - public static AccountProductPositionLimitUnitImmutable? get_position_limit_row(BTSAccountImmutable? account_data, string symbol, SecurityType security_type = SecurityType.Future, Venue venue = Venue.Sim) { - IEnumerable limit_rows = account_data.Value.ProductPositionLimits.Where( - r => r.Product.SecuritySymbol == symbol - && r.Product.Exchange == venue - && r.Product.SecurityType == security_type); - return limit_rows.Any() ? limit_rows.First() : (AccountProductPositionLimitUnitImmutable?) null; - - } - - public static async Task remove_position_limit(AdminService admin_service, string account_name, string symbol, SecurityType security_type = SecurityType.Future, Venue venue = Venue.Sim) { - var account_data = await get_account_data(admin_service, account_name); - return await remove_position_limit(admin_service, account_data, symbol, security_type, venue); - } - - public static async Task remove_position_limit(AdminService admin_service, BTSAccountImmutable? account_data, string symbol, SecurityType security_type = SecurityType.Future, Venue venue = Venue.Sim) { - - AccountProductPositionLimitUnitImmutable? origin_limit_row = get_position_limit_row(account_data,symbol,security_type,venue); - List limits_list = account_data.Value.ProductPositionLimits.ToList(); - - if(origin_limit_row.HasValue) { - limits_list.Remove(origin_limit_row.Value); - List temp_plu = new List(); - temp_plu.AddRange(limits_list.Select(x => x.CloneToMutable())); - var new_account_data = account_data.Value.with(product_position_limits: temp_plu); - - var update_ret = await admin_service.update_account_async(new AccountUpdateAPIArgument { - CompleteData = new_account_data.CloneToMutable() - }); - - return update_ret.success; - } - else - { - return false; - } - } - - public static async Task set_position_limit(AdminService admin_service, string account_name, string symbol, uint long_limit, uint short_limit, SecurityType security_type = SecurityType.Future, Venue venue = Venue.Sim) { - var account_data = await get_account_data(admin_service, account_name); - return await set_position_limit(admin_service, account_data, symbol, long_limit, short_limit, security_type, venue); - } - - public static async Task set_position_limit(AdminService admin_service, BTSAccountImmutable? account_data, string symbol, uint long_limit, uint short_limit, SecurityType security_type = SecurityType.Future, Venue venue = Venue.Sim) { - - AccountProductPositionLimitUnitImmutable? limit_row = get_position_limit_row(account_data,symbol,security_type,venue); - List limits_list = account_data.Value.ProductPositionLimits.ToList(); - - if(limit_row.HasValue) { - // update the row - limits_list.Remove(limit_row.Value); - limit_row = limit_row.Value.with(long_position_limit: long_limit, short_position_limit: short_limit); - } - else { - // create a new row - AccountProductPositionLimitUnit acplu = new AccountProductPositionLimitUnit(); - acplu.LongPositionLimit = long_limit; - acplu.ShortPositionLimit = short_limit; - acplu.Product = new ProductScope { - SecuritySymbol = symbol, - SecurityType = security_type, - Exchange = venue - }; - - limit_row = acplu; - } - - limits_list.Add(limit_row.Value); - - List temp_plu = new List(); - temp_plu.AddRange(limits_list.Select(x => x.CloneToMutable())); - - var new_account_data = account_data.Value.with(product_position_limits: temp_plu); - - var update_ret = await admin_service.update_account_async(new AccountUpdateAPIArgument { - CompleteData = new_account_data.CloneToMutable() - }); - - return update_ret.success; - } - - - } - - - } diff --git a/src/client/spark_test/System/SpreaderTests.cs b/src/client/spark_test/System/SpreaderTests.cs new file mode 100644 index 000000000..10a8a42d5 --- /dev/null +++ b/src/client/spark_test/System/SpreaderTests.cs @@ -0,0 +1,152 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reactive.Linq; +using System.Text; +using System.Threading.Tasks; +using bts.api; +using bts.api.admin; +using bts.api.core; +using bts.api.test; +using bts.test; +using bts.api.orderman; +using mbts; +using mbts.tests; +using bts.co2; +using bts.tests.utils; +using bts.api.synthetic; +using bts.spark; + +namespace bts.tests +{ + [TestGroup(TestType = TestType.System)] + public class SpreaderTests : IDisposable { + ServiceContext _context; + OrderService _order_service; + AdminService _admin_service; + MarketDataRelay _md_relay; + SyntheticSecurityService _synthetic_service; + IDisposable _order_subscription; + Update _orders; + public SpreaderTests (){ + _context = new ServiceContext(); + + _order_service = _context.locate(); + _admin_service = _context.locate(); + _md_relay = _context.locate(); + _synthetic_service = _context.locate(); + + var auth = _context.login("bts",""); + auth.Wait(3000); + + _order_subscription = _order_service.subscribei_orders().Subscribe(ords => + { + _orders = ords; + }); + } + + public void Dispose() { + Disposable.dispose(ref _order_service); + Disposable.dispose(ref _admin_service); + Disposable.dispose(ref _context); + Disposable.dispose(ref _order_subscription); + } + + [Test(Timeout = 30)] + public async Task spreader_simple_sanity() { + bool system_ready = await TestUtils.test_for_system_ready(_context, TimeSpan.FromMinutes(5)); + Assert.IsTrue(system_ready, "System is not ready"); + + string test_symbol = "SI";// don't use ES, the prices will be rounded to the same number and the result will be off + var test_user = (name: "bts", id: 1u); + var test_account = (name: "ACC A", id: 1u); + + (SecurityImmutable s1, SecurityImmutable s2) test_securities = await SpreaderUtilities.get_securities_for_common_setup_one(_md_relay, test_symbol); + + var setup_product = await SpreaderUtilities.common_setup_one(_order_service, _synthetic_service, test_securities, test_account, test_user); + + var order1_def = OrderDefinitionUtilities.create_spreader_order_def( + setup_product.synthetic.security, + Side.Buy, + setup_product.synthetic.strategy, + test_account, + test_user + ); + + var spreader_order1_response = await OrderUtilities.send_order(_order_service, order1_def, -0.30, 1); + Assert.IsTrue(spreader_order1_response.success, "Failed to send first spreader order"); + + var (spreader_order_is_working, working_spreader_order1) = await verify_order_status(spreader_order1_response.value.OrderKey, OrderStatus.Working); + Assert.IsTrue(spreader_order_is_working, "Spreader order is not Working"); + + var (quoting_order_is_working, working_quoting_order) = await verify_child_order_status(spreader_order1_response.value.OrderKey, OrderStatus.Working); + Assert.IsTrue(quoting_order_is_working, "Order is not Working"); + Assert.IsTrue(working_quoting_order.Value.State.Price == 18.6, "Quoting order has the wrong price"); + + Assert.IsTrue(await OrderUtilities.cancel_orders(_order_service, new List {working_spreader_order1.Value}), "Failed to cancel order"); + + var (quoting_order_is_canceled, canceled_quoting_order) = await verify_child_order_status(spreader_order1_response.value.OrderKey, OrderStatus.Canceled); + Assert.IsTrue(quoting_order_is_canceled, "Quoting order may not have been canceled"); + + // Spreader Order 2 + var spreader_order2_response = await OrderUtilities.send_order(_order_service, order1_def, -0.30, 1); + Assert.IsTrue(spreader_order2_response.success, "Failed to send spreader order 2"); + + var (spreader_order2_is_working, working_spreader_order2) = await verify_order_status(spreader_order2_response.value.OrderKey, OrderStatus.Working); + + Assert.IsTrue(spreader_order2_is_working, "Spreader order 2 is not 'Working'"); + + var spreader_order2_change_response = await OrderUtilities.modify_order(_order_service, working_spreader_order2.Value, -0.6); + Assert.IsTrue(spreader_order2_change_response.success, "failed to modify spreader order"); + + Assert.IsTrue(await verify_order_price(spreader_order2_response.value.OrderKey, -0.6), "Failed to change price of spreader order"); + + // verify quoting order price + Assert.IsTrue(await verify_child_order_price(spreader_order2_response.value.OrderKey, 18.9), "Quoting order incorrect or not found"); + + //fill spreader order + var spreader_order2_fill_change_response = await OrderUtilities.modify_order(_order_service, working_spreader_order2.Value, -0.2); + Assert.IsTrue(spreader_order2_fill_change_response.success, "failed to modify spreader order"); + + Assert.IsTrue(await verify_order_price(spreader_order2_response.value.OrderKey, -0.2), "Failed to change price of spreader order"); + + // verify quoting order price + Assert.IsTrue(await verify_child_order_price(spreader_order2_response.value.OrderKey, 18.5), "Quoting order incorrect or not found"); + + // verify Hedging order price + Assert.IsTrue(await verify_child_order_price(spreader_order2_response.value.OrderKey, 18.3), "Hedging order incorrect or not found"); + + } + + private async Task<(Boolean, OrderRecordImmutable?)> verify_child_order_status(uint parent_order_key, OrderStatus expected_status) { + var order = await get_order(ordi => ordi.ParentKey == parent_order_key && ordi.State.Status == expected_status); + return (order.HasValue && order.Value.State.Status == expected_status, order); + } + private async Task<(Boolean, OrderRecordImmutable?)> verify_order_status(uint order_key, OrderStatus expected_status) { + var order = await get_order(ordi => ordi.Key == order_key); + return (order.HasValue && order.Value.State.Status == expected_status, order); + } + + private async Task verify_order_price(uint order_key, double expected_price, double precision = 10) { + var order = await get_order(ordi => ordi.Key == order_key && Math.Truncate(ordi.State.Price * precision) == precision * expected_price); + return order.HasValue && (Math.Truncate(order.Value.State.Price * precision) == precision * expected_price); + } + + private async Task verify_child_order_price(uint parent_order_key, double expected_price, double precision = 10.0) + { + var order = await get_order(ordi => ordi.ParentKey == parent_order_key && Math.Truncate(ordi.State.Price * precision) == precision * expected_price); + return order.HasValue && (Math.Truncate(order.Value.State.Price * precision) == precision * expected_price); + } + + private async Task get_order(Func predicate) + { + var orders = await OrderUtilities.wait_for_filtered_orders(_order_service, + o => o.Where(predicate).Count() > 0, + ord => ord.Where(predicate), + TimeSpan.FromSeconds(30)); + return orders.result.TryFirst(); + } + + + } +} \ No newline at end of file diff --git a/src/client/spark_test/System/TestBase.cs b/src/client/spark_test/System/TestBase.cs new file mode 100644 index 000000000..dad725590 --- /dev/null +++ b/src/client/spark_test/System/TestBase.cs @@ -0,0 +1,59 @@ +using bts.api.admin; +using bts.api.core; +using bts.api.orderman; +using bts.co2; +using bts.test; +using mbts; +using System; +using System.Collections.Generic; +using System.Text; + +namespace bts.tests { + public abstract class TestBase : IDisposable { + + protected (string name, uint id) _test_account = ("ACC A", 0u); + protected (string name, uint id) _test_user = ("bts", 0u); + protected ServiceContext _context; + protected AdminService _admin_service; + protected OrderService _order_service; + protected MarketDataRelay _md_relay; + protected List _resources; + + public TestBase() { + _context = new ServiceContext(); + _admin_service = _context.locate(); + _order_service = _context.locate(); + _md_relay = _context.locate(); + + _resources = new List { + _context, + _admin_service, + _order_service, + _md_relay + }; + + var auth = _context.login("bts", ""); + auth.Wait(3000); + + // get the ACC A account + var account_data = AdminUtilities.get_account_data(_admin_service, _test_account.name); + account_data.Wait(3000); + Assert.IsTrue(account_data.Result.HasValue); + _test_account.id = account_data.Result.Value.Id; + + // get the bts user + var user_data = AdminUtilities.get_user_data(_admin_service, _test_user.name); + user_data.Wait(3000); + Assert.IsTrue(user_data.Result.HasValue); + _test_user.id = user_data.Result.Value.Id; + + } + + public void Dispose() { + // seg faults on linux during this dispose, not sure why yet + if (System.Environment.OSVersion.Platform == PlatformID.Win32NT) { + Disposable.dispose(_resources); + } + } + } +} diff --git a/src/client/spark_test/Utils/AdminUtilities.cs b/src/client/spark_test/Utils/AdminUtilities.cs new file mode 100644 index 000000000..d46160b16 --- /dev/null +++ b/src/client/spark_test/Utils/AdminUtilities.cs @@ -0,0 +1,230 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reactive.Linq; +using System.Text; +using System.Threading.Tasks; +using bts.api; +using bts.api.admin; +using bts.api.core; +using bts.api.test; +using bts.test; +using bts.api.orderman; +using mbts; +using mbts.tests; +using bts.co2; + +namespace bts.tests +{ + public class AdminUtilities { + + public static async Task get_account_data (AdminService admin_service, string account_name) + { + Update update = await admin_service.subscribei_admin_data().FirstAsync(); + + foreach (var acc in update.all.First().Accounts) { + if(acc.Name == account_name) { + return acc; + } + } + return null; + } + + public static async Task get_user_data (AdminService admin_service, string user_name) + { + Update update = await admin_service.subscribei_admin_data().FirstAsync(); + + foreach (var usr in update.all.First().Users) { + if(usr.Name == user_name) { + return usr; + } + } + return null; + } + + public static AccountSecurityClipLimitUnitImmutable? get_clip_limit_row(BTSAccountImmutable? account_data, string symbol, SecurityType security_type = SecurityType.Future, Venue venue = Venue.Sim) { + IEnumerable clip_limit_rows = account_data.Value.SecurityClipLimits.Limit.Where( + r => r.Security.SecuritySymbol == symbol + && r.Security.Exchange == venue + && r.Security.SecurityType == security_type); + return clip_limit_rows.Any() ? clip_limit_rows.First() : (AccountSecurityClipLimitUnitImmutable?) null; + } + + public static uint? get_clip_limit(BTSAccountImmutable? account_data, string symbol, SecurityType security_type = SecurityType.Future, Venue venue = Venue.Sim) { + var row = get_clip_limit_row(account_data,symbol,security_type,venue); + return row.HasValue ? row.Value.ClipSize : (uint?) null; + } + + public static async Task get_clip_limit(AdminService admin_service, string account_name, string symbol, SecurityType security_type = SecurityType.Future, Venue venue = Venue.Sim) { + var account_data = await get_account_data(admin_service, account_name); + return get_clip_limit(account_data, symbol, security_type, venue); + } + + public static async Task set_clip_limit(AdminService admin_service, uint clip_value, string account_name, string symbol, SecurityType security_type = SecurityType.Future, Venue venue = Venue.Sim) { + var account_data = await get_account_data(admin_service, account_name); + return await set_clip_limit(admin_service, clip_value,account_data, symbol,security_type, venue); + } + + public static async Task set_clip_limit(AdminService admin_service, uint clip_value, BTSAccountImmutable? account_data, string symbol, SecurityType security_type = SecurityType.Future, Venue venue = Venue.Sim) { + + AccountSecurityClipLimitUnitImmutable? origin_clip_limit_row = get_clip_limit_row(account_data,symbol,security_type,venue); + AccountSecurityClipLimitUnitImmutable new_clip_limit_row; + + List clip_limits_list = account_data.Value.SecurityClipLimits.Limit.ToList(); + + if(origin_clip_limit_row.HasValue) { + clip_limits_list.Remove(origin_clip_limit_row.Value); + } + + new_clip_limit_row = (AccountSecurityClipLimitUnitImmutable) new AccountSecurityClipLimitUnit { + Security = new SecurityScope(){ SecuritySymbol = symbol, Exchange = venue, SecurityType = security_type }, + ClipSize = clip_value + }; + + clip_limits_list.Add(new_clip_limit_row); + + AccountSecurityClipLimits temp_scl = new AccountSecurityClipLimits(); + temp_scl.Limit.AddRange(clip_limits_list.Select(x => x.CloneToMutable())); + + var new_account_data = account_data.Value.with(security_clip_limits: temp_scl); + + var update_ret = await admin_service.update_account_async(new AccountUpdateAPIArgument { + CompleteData = new_account_data.CloneToMutable() + }); + + return update_ret.success; + } + + public static async Task clear_all_limits(AdminService admin_service, string account_name) { + var account_data = await get_account_data(admin_service, account_name); + return await clear_all_limits(admin_service, account_data); + } + + public static async Task clear_all_limits(AdminService admin_service, BTSAccountImmutable? account_data) { + var new_account_data = account_data.Value.with(security_clip_limits: new AccountSecurityClipLimits(), product_position_limits: new List()); + + var update_ret = await admin_service.update_account_async(new AccountUpdateAPIArgument { + CompleteData = new_account_data.CloneToMutable() + }); + + return update_ret.success; + } + + + public static async Task remove_clip_limit(AdminService admin_service, string account_name, string symbol, SecurityType security_type = SecurityType.Future, Venue venue = Venue.Sim) { + var account_data = await get_account_data(admin_service, account_name); + return await remove_clip_limit(admin_service, account_data, symbol, security_type, venue); + } + + public static async Task remove_clip_limit(AdminService admin_service, BTSAccountImmutable? account_data, string symbol, SecurityType security_type = SecurityType.Future, Venue venue = Venue.Sim) { + + AccountSecurityClipLimitUnitImmutable? origin_clip_limit_row = get_clip_limit_row(account_data,symbol,security_type,venue); + List clip_limits_list = account_data.Value.SecurityClipLimits.Limit.ToList(); + + if(origin_clip_limit_row.HasValue) { + clip_limits_list.Remove(origin_clip_limit_row.Value); + AccountSecurityClipLimits temp_scl = new AccountSecurityClipLimits(); + temp_scl.Limit.AddRange(clip_limits_list.Select(x => x.CloneToMutable())); + var new_account_data = account_data.Value.with(security_clip_limits: temp_scl); + + var update_ret = await admin_service.update_account_async(new AccountUpdateAPIArgument { + CompleteData = new_account_data.CloneToMutable() + }); + + return update_ret.success; + } + else + { + return false; + } + } + + + public static async Task get_position_limit_row(AdminService admin_service, string account_name, string symbol, SecurityType security_type = SecurityType.Future, Venue venue = Venue.Sim) { + var account_data = await get_account_data(admin_service, account_name); + return get_position_limit_row(account_data, symbol, security_type, venue); + } + + public static AccountProductPositionLimitUnitImmutable? get_position_limit_row(BTSAccountImmutable? account_data, string symbol, SecurityType security_type = SecurityType.Future, Venue venue = Venue.Sim) { + IEnumerable limit_rows = account_data.Value.ProductPositionLimits.Where( + r => r.Product.SecuritySymbol == symbol + && r.Product.Exchange == venue + && r.Product.SecurityType == security_type); + return limit_rows.Any() ? limit_rows.First() : (AccountProductPositionLimitUnitImmutable?) null; + + } + + public static async Task remove_position_limit(AdminService admin_service, string account_name, string symbol, SecurityType security_type = SecurityType.Future, Venue venue = Venue.Sim) { + var account_data = await get_account_data(admin_service, account_name); + return await remove_position_limit(admin_service, account_data, symbol, security_type, venue); + } + + public static async Task remove_position_limit(AdminService admin_service, BTSAccountImmutable? account_data, string symbol, SecurityType security_type = SecurityType.Future, Venue venue = Venue.Sim) { + + AccountProductPositionLimitUnitImmutable? origin_limit_row = get_position_limit_row(account_data,symbol,security_type,venue); + List limits_list = account_data.Value.ProductPositionLimits.ToList(); + + if(origin_limit_row.HasValue) { + limits_list.Remove(origin_limit_row.Value); + List temp_plu = new List(); + temp_plu.AddRange(limits_list.Select(x => x.CloneToMutable())); + var new_account_data = account_data.Value.with(product_position_limits: temp_plu); + + var update_ret = await admin_service.update_account_async(new AccountUpdateAPIArgument { + CompleteData = new_account_data.CloneToMutable() + }); + + return update_ret.success; + } + else + { + return false; + } + } + + public static async Task set_position_limit(AdminService admin_service, string account_name, string symbol, uint long_limit, uint short_limit, SecurityType security_type = SecurityType.Future, Venue venue = Venue.Sim) { + var account_data = await get_account_data(admin_service, account_name); + return await set_position_limit(admin_service, account_data, symbol, long_limit, short_limit, security_type, venue); + } + + public static async Task set_position_limit(AdminService admin_service, BTSAccountImmutable? account_data, string symbol, uint long_limit, uint short_limit, SecurityType security_type = SecurityType.Future, Venue venue = Venue.Sim) { + + AccountProductPositionLimitUnitImmutable? limit_row = get_position_limit_row(account_data,symbol,security_type,venue); + List limits_list = account_data.Value.ProductPositionLimits.ToList(); + + if(limit_row.HasValue) { + // update the row + limits_list.Remove(limit_row.Value); + limit_row = limit_row.Value.with(long_position_limit: long_limit, short_position_limit: short_limit); + } + else { + // create a new row + AccountProductPositionLimitUnit acplu = new AccountProductPositionLimitUnit(); + acplu.LongPositionLimit = long_limit; + acplu.ShortPositionLimit = short_limit; + acplu.Product = new ProductScope { + SecuritySymbol = symbol, + SecurityType = security_type, + Exchange = venue + }; + + limit_row = acplu; + } + + limits_list.Add(limit_row.Value); + + List temp_plu = new List(); + temp_plu.AddRange(limits_list.Select(x => x.CloneToMutable())); + + var new_account_data = account_data.Value.with(product_position_limits: temp_plu); + + var update_ret = await admin_service.update_account_async(new AccountUpdateAPIArgument { + CompleteData = new_account_data.CloneToMutable() + }); + + return update_ret.success; + } + + + } +} diff --git a/src/client/spark_test/Utils/MarketDataUtilities.cs b/src/client/spark_test/Utils/MarketDataUtilities.cs new file mode 100644 index 000000000..5ab58171a --- /dev/null +++ b/src/client/spark_test/Utils/MarketDataUtilities.cs @@ -0,0 +1,74 @@ +using bts.api; +using bts.co2; +using System; +using System.Collections.Generic; +using System.Text; +using System.Threading.Tasks; + +namespace bts.tests { + class MarketDataUtilities { + + const string _MD_HOST = "system_test"; + + public static async Task get_security(MarketDataRelay relay, string symbol, SecurityType security_type, Func match, MDRequest.Types.Flags flags = MDRequest.Types.Flags.Bbo, Venue v = Venue.Sim) { + var request = new MDRequest() { + Host = _MD_HOST, + Channels = { + new SecurityChannel() { + Time = 0, + Flags = (uint)flags, + Type = security_type, + Exchange = v, + Symbol = symbol, + TradeCursor = 0, + RfqCursor = 0 + } + } + }; + var result = await relay.requestmd_async(request); + + if (result.success) { + foreach (var ch in result.value.Channels) { + foreach (var update in ch.Updates) { + if (match(update)) { + return new SecurityImmutable(update.Security); + } + } + } + } + return null; + } + + public static async Task> get_expirations(MarketDataRelay relay, string symbol, SecurityType security_type, MDRequest.Types.Flags flags = MDRequest.Types.Flags.Bbo, Venue v = Venue.Sim) { + var request = new MDRequest() { + Host = _MD_HOST, + Channels = { + new SecurityChannel() { + Time = 0, + Flags = (uint)flags, + Type = security_type, + Exchange = v, + Symbol = symbol, + TradeCursor = 0, + RfqCursor = 0 + } + } + }; + + var result = await relay.requestmd_async(request); + + var futures = new List(); + + if (result.success) { + foreach (var ch in result.value.Channels) { + foreach (var update in ch.Updates) { + futures.Add(update.Security.Future); + } + } + } + + return (IEnumerable) futures; + } + + } +} diff --git a/src/client/spark_test/Utils/OrderUtilities.cs b/src/client/spark_test/Utils/OrderUtilities.cs new file mode 100644 index 000000000..031484a5c --- /dev/null +++ b/src/client/spark_test/Utils/OrderUtilities.cs @@ -0,0 +1,200 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reactive.Linq; +using System.Text; +using System.Threading.Tasks; +using bts.api; +using bts.api.admin; +using bts.api.core; +using bts.api.test; +using bts.test; +using bts.api.orderman; +using mbts; +using mbts.tests; +using bts.co2; +using bts.tests.utils; +using bts.spark; + +namespace bts.tests +{ + public class OrderUtilities { + public static async Task> send_order(OrderService order_service, OrderDefinition order_def, double price, uint size){ + return await order_service.create_order_async(new Create() { + NewOrder = order_def, + Price = price, + Quantity = size + }); + } + public static async Task> modify_order(OrderService order_service, OrderRecordImmutable o, uint size) { + return await modify_order(order_service, o.Key, o.State.Price, size); + } + public static async Task> modify_order(OrderService order_service, OrderRecordImmutable o, double price) { + return await modify_order(order_service, o.Key, price, o.State.Quantity); + } + public static async Task> modify_order(OrderService order_service, OrderRecordImmutable o, double price, uint size) { + return await modify_order(order_service, o.Key, price, size); + } + private static async Task> modify_order(OrderService order_service, uint order_key, double price, uint size) { + return await order_service.update_order_async(new Update() { + OrderKey = order_key, + Price = price, + Quantity = size + }); + } + + public static async Task cancel_orders(OrderService order_service, IEnumerable orders, uint key = 0){ + if (key > 0) { + Result resp = await order_service.cancel_order_async(new Cancel() { OrderKey = key }); + return resp.success; + } + else { + bool suc = true; + var working_orders = orders.Where(x => x.State.Status == OrderStatus.Working); + if(working_orders != null){ + foreach (var o in working_orders){ + Result resp = await order_service.cancel_order_async(new Cancel() { OrderKey = o.Key }); + suc &= resp.success; + } + return suc; + } + return true;// there are no working orders... so true enough + } + } + + public async static Task>> + wait_for_filtered_orders(OrderService order_service, Func, bool> match, Func, IEnumerable> selector, TimeSpan? timeout = null) { + if (timeout == null) { + timeout = TimeSpan.FromSeconds(3); + } + var tcs = new TaskCompletionSource>(); + var sub = order_service.subscribei_orders().Subscribe(update => { + if (match(update.all)) { + tcs.TrySetResult(selector(update.all)); + } + }); + var tr = await tcs.Task.timeout(timeout.Value); + sub.Dispose(); + return tr; + } + + public async static Task>> + wait_for_filtered_fills(OrderService order_service, Func, bool> match, Func, IEnumerable> selector, TimeSpan? timeout = null) { + if (timeout == null) { + timeout = TimeSpan.FromSeconds(3); + } + var tcs = new TaskCompletionSource>(); + var sub = order_service.subscribei_fills().Subscribe(update => { + if (match(update.all)) { + tcs.TrySetResult(selector(update.all)); + } + }); + var tr = await tcs.Task.timeout(timeout.Value); + sub.Dispose(); + return tr; + } + + public async static Task> create_book(OrderService order_service, (OrderDefinition order_def, double price, uint size)[] order_defs) { + + List> results = new List>(); + + foreach(var ord in order_defs) { + Assert.IsTrue(ord.order_def != null, "Order definition can not be null"); + results.Add(await send_order(order_service, ord.order_def, ord.price, ord.size)); + } + + Func, IEnumerable> selector = existing_orders => { + return existing_orders.Where(z => results.Exists(y => z.Key == y.value.OrderKey)); + }; + + Func, bool> match = existing_orders => { + return selector(existing_orders).Count() > 0; + }; + + await Task.Delay(5000);// I'm not sure how to get around this + + utils.TestUtils.TimeoutResult> filtered_orders = await wait_for_filtered_orders(order_service, match, selector, TimeSpan.FromSeconds(30)); + + Assert.IsNotNull(filtered_orders.result, "Book is incomplete"); + Assert.IsTrue(filtered_orders.result.Count() == order_defs.Length, "Book is incomplete"); + + return filtered_orders.result; + } + + } + + /// + /// We should replace with something like the OrderDataHeler from the Spark project. + /// + public static class OrderDefinitionUtilities { + + private static OrderDefinition create_base_order(uint security_id, Side side, (String name, uint id) account, (String name, uint id) user) { + return new OrderDefinition { + SecurityKey = security_id, + Side = side, + TimeInForce = TimeInForce.Day, + CtiCode = CTICode.CtiCode1, + CustomerOrFirm = CustomerOrFirm.Firm, + ManualOrderIndicator = ManualOrderIndicator.Yes, + Account = account.name, + AccountId = account.id, + User = user.name, + UserId = user.id + }; + } + public static OrderDefinition create_limit_order_def(uint security_id, Side side, (String name, uint id) account, (String name, uint id) user) { + var def = create_base_order(security_id, side, account, user); + def.CustomDef = new CustomOrderDefinition { Limit = new LimitOrderDefinition { } }; + return def; + } + + public static OrderDefinition create_spreader_order_def(Security security, Side side, ExecutionStrategy strategy, (String name, uint id) account, (String name, uint id) user) { + var def = create_base_order(security.Id, side, account, user); + def.CustomDef = new CustomOrderDefinition { Spreader = new SpreaderOrderDefinition {Security = security, ExecutionStrategy = strategy} }; + return def; + } + + public static OrderDefinition create_iceberg_order_def(uint security_id, Side side, (String name, uint id) account, (String name, uint id) user, double show_quantity) { + var def = create_base_order(security_id, side, account, user); + def.CustomDef = new CustomOrderDefinition { + Iceberg = new IcebergOrderDefinition { + ShowQuantity = show_quantity, + Child = new CustomOrderDefinition { + Limit = new LimitOrderDefinition { } + } + } + }; + return def; + } + + public static OrderDefinition create_join_order_definition(uint security_id, Side side, (String name, uint id) account, (String name, uint id) user, spark.QuantityMeasure join_threshold) { + var def = create_base_order(security_id, side, account, user); + def.CustomDef = new CustomOrderDefinition { + Join = new JoinOrderDefinition { + JoinThreshold = join_threshold, + Child = new CustomOrderDefinition { + Limit = new LimitOrderDefinition { } + } + } + }; + return def; + } + + public static OrderDefinition create_lean_order_definition(uint security_id, Side side, (String name, uint id) account, (String name, uint id) user, spark.QuantityMeasure lean_threshold, uint max_chase_ticks = 2, LeanOrderDefinition.Types.OnToward ontoward_behavor = LeanOrderDefinition.Types.OnToward.NoChange) { + var def = create_base_order(security_id, side, account, user); + def.CustomDef = new CustomOrderDefinition { + Lean = new LeanOrderDefinition { + CrossThreshold = lean_threshold, + MaxChaseTicks = max_chase_ticks, + TradeTowardBehavior = ontoward_behavor, + Child = new CustomOrderDefinition { + Limit = new LimitOrderDefinition { } + } + } + }; + return def; + } + + } + +} \ No newline at end of file diff --git a/src/client/spark_test/Utils/SpreaderUtilities.cs b/src/client/spark_test/Utils/SpreaderUtilities.cs new file mode 100644 index 000000000..db2f830f6 --- /dev/null +++ b/src/client/spark_test/Utils/SpreaderUtilities.cs @@ -0,0 +1,180 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reactive.Linq; +using System.Text; +using System.Threading.Tasks; +using bts.api; +using bts.api.admin; +using bts.api.core; +using bts.api.test; +using bts.test; +using bts.api.orderman; +using mbts; +using mbts.tests; +using bts.co2; +using bts.tests.utils; +using bts.api.synthetic; +using bts.spark; + +namespace bts.tests +{ + public class SpreaderUtilities { + + public static async Task<(SecurityImmutable s1, SecurityImmutable s2)> get_securities_for_common_setup_one(MarketDataRelay relay, string symbol) { + var exps = (await MarketDataUtilities.get_expirations(relay, symbol, SecurityType.Future)).ToList(); + + Assert.IsNotNull(exps); + Assert.IsTrue(exps.Count() > 2, "Need at least two expirations"); + + var exp1 = exps[0]; + var exp2 = exps[1]; + + Func sec1_match = ch => + ch.Security.Future.ExpirationYear == exp1.ExpirationYear && + ch.Security.Future.ExpirationMonth == exp1.ExpirationMonth && + ch.Security.Future.ExpirationDay == exp1.ExpirationDay; + + Func sec2_match = ch => + ch.Security.Future.ExpirationYear == exp2.ExpirationYear && + ch.Security.Future.ExpirationMonth == exp2.ExpirationMonth && + ch.Security.Future.ExpirationDay == exp2.ExpirationDay; + + var sec_task1 = MarketDataUtilities.get_security(relay, symbol, SecurityType.Future, sec1_match); + var sec_task2 = MarketDataUtilities.get_security(relay, symbol, SecurityType.Future, sec2_match); + + var sec1 = await sec_task1; + var sec2 = await sec_task2; + + Assert.IsFalse(sec1 == null, "security is null"); + Assert.IsFalse(sec2 == null, "security is null"); + + return (s1: sec1.Value, s2: sec2.Value); + } + public static async Task<(IEnumerable book, (Security security, ExecutionStrategy strategy) synthetic)> common_setup_one(OrderService order_service, SyntheticSecurityService synthetic_service, (SecurityImmutable? s1, SecurityImmutable? s2) securities, (String name, uint id) account, (String name, uint id) user) { + var order_defs = new (OrderDefinition order_def, double price, uint size)[10]; + + for (int i = 0; i < 4; i ++) { + double p = (0.01 * i) + 18.230; + order_defs[i] = ( + order_def: OrderDefinitionUtilities.create_limit_order_def(securities.s1.Value.Id, Side.Buy, account, user), + price: p, + size: 1 + ); + } + + for (int i = 4; i < 8; i ++) { + double p = (0.01 * (i - 4)) + 18.300; + order_defs[i] = ( + order_def: OrderDefinitionUtilities.create_limit_order_def(securities.s1.Value.Id, Side.Sell, account, user), + price: p, + size: 1 + ); + } + + order_defs[8] = ( + order_def: OrderDefinitionUtilities.create_limit_order_def(securities.s2.Value.Id, Side.Buy, account, user), + price: 18.500, + size: 5 + ); + + order_defs[9] = ( + order_def: OrderDefinitionUtilities.create_limit_order_def(securities.s2.Value.Id, Side.Sell, account, user), + price: 18.53, + size: 5 + ); + + var book = await OrderUtilities.create_book(order_service, order_defs); + + List<(ContractLeg contract, LegSpreaderParams parameters)> legs = new List<(ContractLeg, LegSpreaderParams)>(); + + legs.Add(create_leg(securities.s1.Value.CloneToMutable(),1,1,false,1)); + legs.Add(create_leg(securities.s2.Value.CloneToMutable(),-1,-1,true,1)); + + (Security security, ExecutionStrategy strategy) synthetic = await create_synthetic(synthetic_service, legs); + + return(book, synthetic); + + } + + public static async Task<(Security, ExecutionStrategy)> create_synthetic(SyntheticSecurityService service, IEnumerable<(ContractLeg contract, LegSpreaderParams parameters)> legs) { + var new_synth = new Security(){}; + new_synth.Synthetic = new SyntheticContract(); + new_synth.Synthetic.Legs.Add(legs.Select(l => l.contract)); + new_synth.Symbol = deduce_symbol(new_synth); + new_synth.ContractSpec = new ContractSpecification(); + new_synth.ContractSpec.LowTick = 0.01; + new_synth.ContractSpec.HighTick = 0.01; + new_synth.ContractSpec.PriceBreak = double.MaxValue; + new_synth.ContractSpec.MainFraction = 1u; + new_synth.ContractSpec.PriceDisplayFormat = 3u; + new_synth.Exchange = Venue.Bts; + new_synth.Synthetic.Name = "TEST_SYNTH" + DateTime.Now.ToString(); + + var result = await service.create_synthetic_async(new_synth); + Assert.IsTrue(result.success, "Unable to create synthetic"); + Assert.IsTrue(result.value.Error == CreateResult.Types.Error.Ok, "Create synthetic was not OK"); + + uint? id = result.value.Key; + Assert.IsTrue(id.HasValue && id.Value != 0, "Failed to get synthetic security key"); + + new_synth.Id = result.value.Key; + + ExecutionStrategy strategy = new ExecutionStrategy(); + foreach(var leg in legs){ + strategy.LegParamsMap.Add(leg.contract.Security.Id, leg.parameters); + } + bool success = await save_strategy(service, new_synth.Id, new ExecutionStrategyImmutable(strategy)); + Assert.IsTrue(success, "Failed to save synthetic strategy"); + + return (new_synth, strategy); + + } + + public static (ContractLeg contract, LegSpreaderParams parameters) create_leg( + Security security, + double quantity, + double price_multiplier, + bool is_quoting, + double lean_qty_factor, + LegSpreaderParams.Types.MarketDataType market_data_type = 0 + ) + { + var contract = new ContractLeg(); + contract.Security = security; + contract.PriceMultiplier = price_multiplier; + contract.Side = quantity > 0 ? Side.Buy : Side.Sell; + contract.Quantity = Math.Abs(quantity); + + var parameters = new LegSpreaderParams(); + parameters.IsActiveQuoting = is_quoting; + parameters.MarketDataType = market_data_type; // 0 == Merged, 1 == Direct + parameters.EnableHedging = !is_quoting; + parameters.PostHedgeParams = new PostHedgeParams(); + parameters.PreHedgeParams = new PreHedgeParams(); + + parameters.QuoteParams = new QuoteParams(); + parameters.QuoteParams.LeanQuantityRatio = lean_qty_factor; + parameters.QuoteParams.QuoteMuteZone = null; // == Throttle unchecked + + return (contract: contract, parameters: parameters); + } + + public static string deduce_symbol(SecurityImmutable? security) { + if (!string.IsNullOrWhiteSpace(security?.Symbol)) return security?.Symbol; + if (security?.Synthetic.Legs.Count() > 0) return security?.Synthetic.Legs.First().Security.Symbol; + return string.Empty; + } + + public static async Task create_synthetic(SyntheticSecurityService service, SecurityImmutable? synthetic) { + var result = await service.create_synthetic_async(synthetic.Value); + Assert.IsTrue(result.success, "failed to create synthetic"); + return result.value.Key; + } + + public static async Task save_strategy(SyntheticSecurityService service, uint synthetic_id, ExecutionStrategyImmutable strategy) { + var result = await service.update_security_metadata_async(new Metadata { SecurityKey = synthetic_id, Strategy = strategy.CloneToMutable() }); + return result.success; + } + } +} \ No newline at end of file diff --git a/src/client/spark_test/Utils/TestUtils.cs b/src/client/spark_test/Utils/TestUtils.cs index f469031f3..6967bee52 100644 --- a/src/client/spark_test/Utils/TestUtils.cs +++ b/src/client/spark_test/Utils/TestUtils.cs @@ -1,10 +1,16 @@ -using bts.collections; +using bts.api; +using bts.api.admin; +using bts.api.core; +using bts.api.orderman; +using bts.collections; using System; using System.Collections.Generic; using System.Linq; +using System.Reactive.Linq; +using System.Threading.Tasks; namespace bts.tests.utils { - static class TestUtils { + public static class TestUtils { public static List randomize_values(IReadOnlyList input) { var remaining_indices = Enumerable.Range(0, input.Count).ToList(); var rand = new Random(); @@ -38,5 +44,99 @@ namespace bts.tests.utils { } return reshuffled; } + + public static bool test_price_equality(double price_1, double price_2, double tick_size) { + return Math.Abs(price_2 - price_1) < 0.01 * tick_size; + } + + // this is a copy from TickUtils -- ask what's legal for the spark_test project... + public static double ticksize(this ContractSpecificationImmutable spec, double price) => + Math.Abs(price) > spec.PriceBreak ? spec.HighTick : spec.LowTick; + + // this was copied from GlobalExtensions + public struct TimeoutResult { + public TimeoutResult(T result, TimeSpan ts) { + wait_duration = ts; + this.result = result; + } + public readonly TimeSpan wait_duration; + public readonly T result; + } + + // this was copied from GlobalExtensions + public static async Task> timeout(this Task task, TimeSpan timeout) { + System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch(); + sw.Start(); + var timeout_task = Task.Delay(timeout); + var completed = await Task.WhenAny(task, timeout_task); + return (completed == timeout_task) ? + new TimeoutResult(default(T), timeout) : + new TimeoutResult(task.Result, sw.Elapsed); + } + + public static async Task await_with_timeout(Task task, TimeSpan timeout){ + var to = timeout(task, timeout); + var tr = await to; + return tr.result; + } + + + public static async Task test_for_system_ready(ServiceContext context, TimeSpan? timeout = null) { + if(timeout == null) { + timeout = TimeSpan.FromSeconds(30); + } + + System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch(); + sw.Start(); + + bool admin_ready = await test_for_admin_service_ready(context, timeout.Value.Subtract(sw.Elapsed)); + Console.WriteLine("Admin Service Ready: " + admin_ready); + bool md_ready = await test_for_md_service_ready(context, timeout.Value.Subtract(sw.Elapsed)); + Console.WriteLine("MD Service Ready: " + md_ready); + + return admin_ready && md_ready; + } + + public static async Task test_for_admin_service_ready(ServiceContext context, TimeSpan timeout) { + System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch(); + sw.Start(); + + var admin_service = context.locate(); + + Update admin_value = null; + var account_sub = admin_service.subscribei_admin_data().Subscribe(update => admin_value = update); + + while(admin_value == null && sw.Elapsed < timeout) { + Console.WriteLine("Waiting for admin service..."); + await Task.Delay(100); + } + + return admin_value != null; + } + + + public static async Task test_for_md_service_ready(ServiceContext context, TimeSpan timeout) { + var md_request = new co2.MDRequest() { + Host = "system_test", + Channels = { + new co2.SecurityChannel() { + Time = 0, + Flags = 0, + Type = SecurityType.Future, + Exchange = Venue.Sim, + Symbol = "*", + TradeCursor = 0, + RfqCursor = 0 + } + } + }; + + var md_relay = context.locate(); + Result? md_result = await await_with_timeout( + md_relay.requestmd_async(md_request), + timeout); + + return md_result != null; + } } } \ No newline at end of file diff --git a/src/client/spark_test/api/ApiUpdateTests.cs b/src/client/spark_test/api/ApiUpdateTests.cs index a0feaa204..e41f9dbce 100644 --- a/src/client/spark_test/api/ApiUpdateTests.cs +++ b/src/client/spark_test/api/ApiUpdateTests.cs @@ -544,7 +544,7 @@ namespace mbts.api.Test { var left_source = new Subject>(); var right_source = new Subject>(); // join/state - var join = left_source.LeftJoin(right_source, i => i.id, i => i.id, null).RefCount(); + var join = left_source.LeftJoin(right_source, i => i.id, i => i.id, null); var update_list = new List>(); join.Subscribe(t => { lock (update_list) { diff --git a/src/client/spark_test/spark_test.csproj b/src/client/spark_test/spark_test.csproj index 8a6c94761..308bc8928 100644 --- a/src/client/spark_test/spark_test.csproj +++ b/src/client/spark_test/spark_test.csproj @@ -11,4 +11,8 @@ + + + + diff --git a/src/client/spark_test/system_test_scripts/spreader_simple_sanity.sh b/src/client/spark_test/system_test_scripts/spreader_simple_sanity.sh new file mode 100644 index 000000000..4a0bc7bc1 --- /dev/null +++ b/src/client/spark_test/system_test_scripts/spreader_simple_sanity.sh @@ -0,0 +1,47 @@ +#!/bin/bash + +if [ -d ~/sparkdata/ ] +then + sparkdata_dir=~/sparkdata +else + sparkdata_dir=/sparkdata +fi + +config=$sparkdata_dir/conf/spark.conf +bak=$sparkdata_dir/conf/spark.conf.bak + +[ -d "$sparkdata_dir/data" ] && rm -r $sparkdata_dir/data/ +[ ! -d "$sparkdata_dir/conf" ] && mkdir $sparkdata_dir/conf/ +[ -f "$conf" ] && mv $conf $bak + +cat << EOF > $sparkdata_dir/conf/spark.conf + ExchangeSim { + value { + merge_with_md:false + } + } + Logging { + value { + console { default_level: "Error" } + syslog { default_level: "Error" } + file { default_level: "Error" } + } +} +EOF + + +nohup ./sparkd run & +pid=$! +echo "sparkd pid: " $pid + +echo "sleeping for 120 seconds..." +sleep 120 + +dotnet sparkcmd.dll test spreader_simple_sanity +exit_status=$? + +pkill -P $$ + +[ -f "$bak" ] && mv $bak $conf +[ $exit_status -eq 0 ] && echo "Test Finished" || echo "Test failed" +exit $exit_status \ No newline at end of file diff --git a/src/client/spark_test/system_test_scripts/test_clip_limits.sh b/src/client/spark_test/system_test_scripts/test_clip_limits.sh new file mode 100644 index 000000000..885b91710 --- /dev/null +++ b/src/client/spark_test/system_test_scripts/test_clip_limits.sh @@ -0,0 +1,46 @@ +#!/bin/bash + +if [ -d ~/sparkdata/ ] +then + sparkdata_dir=~/sparkdata +else + sparkdata_dir=/sparkdata +fi + +config=$sparkdata_dir/conf/spark.conf +bak=$sparkdata_dir/conf/spark.conf.bak + +[ -d "$sparkdata_dir/data" ] && rm -r $sparkdata_dir/data/ +[ ! -d "$sparkdata_dir/conf" ] && mkdir $sparkdata_dir/conf/ +[ -f "$conf" ] && mv $conf $bak + +cat << EOF > $sparkdata_dir/conf/spark.conf + ExchangeSim { + value { + merge_with_md:true + } + } + Logging { + value { + console { default_level: "Error" } + syslog { default_level: "Error" } + file { default_level: "Error" } + } +} +EOF + +nohup ./sparkd run & +pid=$! +echo "sparkd pid: " $pid + +echo "sleeping for 120 seconds..." +sleep 120 + +dotnet sparkcmd.dll test test_clip_limits +exit_status=$? + +pkill -P $$ +[ -f "$bak" ] && mv $bak $conf + +[ $exit_status -eq 0 ] && echo "Test Finished" || echo "Test failed" +exit $exit_status \ No newline at end of file diff --git a/src/client/spark_test/system_test_scripts/test_join_algo.sh b/src/client/spark_test/system_test_scripts/test_join_algo.sh new file mode 100644 index 000000000..616dcadba --- /dev/null +++ b/src/client/spark_test/system_test_scripts/test_join_algo.sh @@ -0,0 +1,160 @@ +#!/usr/bin/env bash + +# Stop script on NZEC +#set -e # the will allow sparkd to keep running if a test fails, preventing Jenkins from continuing +# Stop script if unbound variable found (use ${var:-} if intentional) +set -u + +if [ -d ~/sparkdata/ ] +then + sparkdata_dir=~/sparkdata +else + sparkdata_dir=/sparkdata +fi + +# Use in the the functions: eval $invocation +invocation='say_verbose "Calling: ${yellow:-}${FUNCNAME[0]} ${green:-}$*${normal:-}"' + +# standard output may be used as a return value in the functions +# we need a way to write text on the screen in the functions so that +# it won't interfere with the return value. +# Exposing stream 3 as a pipe to standard output of the script itself +exec 3>&1 + +# Setup some colors to use. These need to work in fairly limited shells, like the Ubuntu Docker container where there are only 8 colors. +# See if stdout is a terminal +if [ -t 1 ] && command -v tput > /dev/null; then + # see if it supports colors + ncolors=$(tput colors) + if [ -n "$ncolors" ] && [ $ncolors -ge 8 ]; then + bold="$(tput bold || echo)" + normal="$(tput sgr0 || echo)" + black="$(tput setaf 0 || echo)" + red="$(tput setaf 1 || echo)" + green="$(tput setaf 2 || echo)" + yellow="$(tput setaf 3 || echo)" + blue="$(tput setaf 4 || echo)" + magenta="$(tput setaf 5 || echo)" + cyan="$(tput setaf 6 || echo)" + white="$(tput setaf 7 || echo)" + fi +fi + +say_warning() { + printf "%b\n" "${yellow:-}$test_script_name: Warning: $1${normal:-}" +} + +say_err() { + printf "%b\n" "${red:-}$test_script_name: Error: $1${normal:-}" >&2 +} + +say() { + # using stream 3 (defined in the beginning) to not interfere with stdout of functions + # which may be used as return value + printf "%b\n" "${cyan:-}$test_script_name:${normal:-} $1" >&3 +} + +say_verbose() { + if [ "$verbose" = true ]; then + say "$1" + fi +} + +is_merge_with_md_on() { + eval $invocation + + if [ $(./sparkd configcheck ExchangeSim | grep merge_with_md: | cut -d " " -f 2) == "false" ]; then + return 0 + else + return 1 + fi +} + +set_merge_with_md_off() { + eval $invocation + + if [ -f $config_file_path ]; then + say_verbose "config file exists ... removing" + rm $config_file_path + fi + + echo "$merge_with_md_key" >> $config_file_path && test_config_file_created=true + + return 0 +} + +# args +# return_var - $1 +# class_name - $2 +get_tests_in_class() { + eval $invocation + + local return_var=$1 + local class_name=$2 + local arr=($(dotnet sparkcmd.dll test --type System --list | perl -ne '/^( *)/; $i = length $1; $j && $i >= $j and print, next; $j = 0; /'"$class_name"'/ and $j = $i + 1, print' | tail -n +2)) + eval $return_var='("${arr[@]}")' + + return 0 +} + +# Start sparkd +nohup ./sparkd run & +pid=$! +echo "sparkd pid: " $pid +echo "sleeping for 120 seconds..." +sleep 120 + + +# args +# class_name - $1 +run_bts_test() { + eval $invocation + + class_name=$1 + + local test_names_tuple=() + get_tests_in_class test_names_tuple $class_name + for test_name in ${test_names_tuple[@]}; do + say_verbose "running test with name: $test_name ..."; + dotnet sparkcmd.dll test $test_name + exit_status=$? + done + + return 0 +} + +test_script_name=$(basename "$0") +verbose=true +config_file_path="$sparkdata_dir/conf/test_join_algo_tests.conf" +test_config_file_created=false +merge_with_md_key=$(/bin/cat <<'END_HEREDOC' +ExchangeSim { + value { + merge_with_md: false + } +} +END_HEREDOC +) + +if is_merge_with_md_on; then + set_merge_with_md_off + if is_merge_with_md_on; then + say_err "Could not turn off merge_with_md" + say_err "Please investigate manually" + exit 1 + fi +else + say_verbose "merge with md is already off" +fi + +run_bts_test "JoinAlgoTests" + +if [ "$test_config_file_created" = true ]; then + rm $config_file_path +fi + +# Kill sparkd +pkill -P $$ + +[ $exit_status -eq 0 ] && echo "Test Finished" || echo "Test failed" +exit $exit_status diff --git a/src/client/spark_test/system_test_scripts/test_position_limits.sh b/src/client/spark_test/system_test_scripts/test_position_limits.sh new file mode 100644 index 000000000..8a1466a58 --- /dev/null +++ b/src/client/spark_test/system_test_scripts/test_position_limits.sh @@ -0,0 +1,47 @@ +#!/bin/bash + +if [ -d ~/sparkdata/ ] +then + sparkdata_dir=~/sparkdata +else + sparkdata_dir=/sparkdata +fi + +config=$sparkdata_dir/conf/spark.conf +bak=$sparkdata_dir/conf/spark.conf.bak + +[ -d "$sparkdata_dir/data" ] && rm -r $sparkdata_dir/data/ +[ ! -d "$sparkdata_dir/conf" ] && mkdir $sparkdata_dir/conf/ +[ -f "$conf" ] && mv $conf $bak + +cat << EOF > $sparkdata_dir/conf/spark.conf + ExchangeSim { + value { + merge_with_md:true + } + } + Logging { + value { + console { default_level: "Error" } + syslog { default_level: "Error" } + file { default_level: "Error" } + } +} +EOF + + +nohup ./sparkd run & +pid=$! +echo "sparkd pid: " $pid + +echo "sleeping for 120 seconds..." +sleep 120 +dotnet sparkcmd.dll test test_position_limits +exit_status=$? + +pkill -P $$ + +[ -f "$bak" ] && mv $bak $conf + +[ $exit_status -eq 0 ] && echo "Test Finished" || echo "Test failed" +exit $exit_status \ No newline at end of file diff --git a/src/data_files/files/cert_secure_logon.txt b/src/data_files/files/cert_secure_logon.txt index 3987786a0..cd0110d4f 100644 --- a/src/data_files/files/cert_secure_logon.txt +++ b/src/data_files/files/cert_secure_logon.txt @@ -1,6 +1,6 @@ Session ID Access ID Secret Key Creation Date Expiration Date Environment -MC1 0N10hKkE2B2KUt86ewd8 dJ5I52JNA-6aZZ8hnO0byVKcyqA8Of6kkstfIF89AAM 2018-04-05 2019-04-05 CERT -MC5 e4uBmhQ1ebaXAeWHa7HK PNOM86eofsiCwzzKUsB5yAmrNoyZypnYD72pT2A8zgc 2018-04-05 2019-04-05 CERT -MC7 S6KfCnay5UJ67P55ibHd 5lSs1TbX7N0p6Duu63_JDMghPUqBAWacvkM91MUv1uM 2018-04-05 2019-04-05 CERT -MC8 AbEEtBn63WIAuItPDz1c n3ndjYb03Hx6wBO3me35HoONyDgO5TZKWk0tDSaX9KA 2018-04-05 2019-04-05 CERT -V06 WOC3GVA6l8ffrcOKUT9P Az1TJc2XHJyZ4C0S1bG_p5eWPQlVYUYhfjmdPqSGJ8o 2018-11-26 2019-11-26 NEWRELEASE +MC1 KTima1GzuuXgmAd5LWnN bAFTi2XyMDBxX5S2-BC-k8Ti-5GmENer8Vtv4zmyCXM 2019-04-09 2020-04-09 CERT +MC5 tnoschzeeYyQEcUFLYBp uA4xXSggo3-hwRJdD35v0CTKpx6_HmpAock0CHgmZ4A 2019-04-09 2020-04-09 CERT +MC7 8ArA8FSwuoeTzMhkoQlW Zi1egeOWG3phGx4qZYjhOTtptcmA3t7ty_7if7qwO4c 2019-04-09 2020-04-09 CERT +MC8 grWHZk3dCz8wtRPYTQR9 OPIIFk1orwBLu4IBJVcNAVvRb8Db1-VRD0qyQClYHl8 2019-04-09 2020-04-09 CERT +V06 jw4KHsh6FqXIGK7ejJKp s_Cqv1o1rPhWTUWgY8mvHXJudzBYBUYS1rlMzwjMMT8 2019-04-09 2020-04-09 NEWRELEASE diff --git a/src/lib/CMakeDeps.cmake b/src/lib/CMakeDeps.cmake index c9d142ec6..ecd1c370b 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/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/logging.conf;config/defaults/orderman_cfg.conf;config/defaults/orders_fills_cleanup.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/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/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/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/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/md2_tests.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/OrderServicesData.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/orders/DynamicOrder.cpp;orderman/orders/IcebergOrder.cpp;orderman/orders/NativeOrder.cpp;orderman/orders/Order.cpp;orderman/orders/TimeBoxOrder.cpp;orderman/orders/TriggerOrder.cpp;orderman/orders/book_algos/BookAlgo.cpp;orderman/orders/book_algos/CoverOrder.cpp;orderman/orders/book_algos/JoinOrder.cpp;orderman/orders/book_algos/LeanOrder.cpp;orderman/orders/book_algos/OCOOrder.cpp;orderman/orders/book_algos/OffsetOrder.cpp;orderman/orders/book_algos/PricerOrder.cpp;orderman/orders/book_algos/TopOrder.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/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;orderman2/orders/NativeOrder.cpp;orderman2/orders/Order.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/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/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/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/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/logging.conf;config/defaults/orderman_cfg.conf;config/defaults/orders_fills_cleanup.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/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/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/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/IAlgoOrder.cpp;orderman/orders/algo/IAlgoServices.cpp;orderman/orders/algo/IBeforeLaunchAlgoServices.cpp;orderman/orders/algo/algo_orders/CoverAlgo.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/TopAlgo.cpp;orderman/orders/book_algos/BookAlgo.cpp;orderman/orders/book_algos/BookOrderBase.cpp;orderman/orders/book_algos/OCOOrder.cpp;orderman/orders/book_algos/OffsetOrder.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/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/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/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/thread_manager.cpp) \ No newline at end of file diff --git a/src/lib/api/public/ClientChannel.h b/src/lib/api/public/ClientChannel.h index 25cbd019f..fb5fd31c7 100644 --- a/src/lib/api/public/ClientChannel.h +++ b/src/lib/api/public/ClientChannel.h @@ -93,7 +93,7 @@ public: } else { bool first_update = true; - auto cb = [observer, first_update, method, qualifier](EventType event_type, const StreamUpdate* changes, int change_count) mutable { + auto cb = [observer, first_update, qualifier](EventType event_type, const StreamUpdate* changes, int change_count) mutable { if (event_type == EventType::TABLE_UPDATED) { std::vector> added_items, changed_items; std::vector added_keys, diff --git a/src/lib/api/service_helpers/AdminServiceUtils.cpp b/src/lib/api/service_helpers/AdminServiceUtils.cpp index ca30f9f61..0c86f2a7f 100644 --- a/src/lib/api/service_helpers/AdminServiceUtils.cpp +++ b/src/lib/api/service_helpers/AdminServiceUtils.cpp @@ -8,6 +8,7 @@ #include #include +#include namespace bts{ namespace admin{ @@ -814,9 +815,13 @@ AdminServiceUtils::find_user_account_matches (const bts::api::admin::AdminData& auto user_ptrs = users(admin_data, false); for(const bts::api::admin::BTSAccount* account_ptr : account_ptrs){ if (account_has_connection(*account_ptr, connection)){ - if (exchange_account == find_account_exchange_account(admin_data,*account_ptr,exchange,find_account_result) && find_account_result.is_success()){ + if (boost::algorithm::iequals(exchange_account, + find_account_exchange_account(admin_data,*account_ptr,exchange,find_account_result)) && + find_account_result.is_success()){ for(const bts::api::admin::BTSUser* user_ptr : user_ptrs){ - if (exchange_user == find_user_exchange_id(admin_data,*user_ptr,exchange,find_user_result) && find_user_result.is_success()) + if (boost::algorithm::iequals(exchange_user, + find_user_exchange_id(admin_data,*user_ptr,exchange,find_user_result)) && + find_user_result.is_success()) return std::pair(account_ptr,user_ptr); } } diff --git a/src/lib/api/services/OrderService.proto b/src/lib/api/services/OrderService.proto index d20877f52..b16c4d584 100644 --- a/src/lib/api/services/OrderService.proto +++ b/src/lib/api/services/OrderService.proto @@ -12,11 +12,21 @@ service OrderService { option (bts.api.service_description)="Implements order management"; // service calls - rpc create_order(Create) returns (Response) { option(skip_excel_generation) = true; }; - rpc cancel_order(Cancel) returns (Response) { option(skip_excel_generation) = true; }; - rpc update_order(Update) returns (Response) { option(skip_excel_generation) = true; }; - rpc crack_order(Crack) returns (Response) { option(skip_excel_generation) = true; }; - rpc get_registered_dynamic_order_types(bts.api.VoidMessage) returns (RegisteredDynamicOrderTypes); + rpc create_order(Create) returns (Response) + { option(skip_excel_generation) = true; }; + + rpc cancel_order(Cancel) returns (Response) + { option(skip_excel_generation) = true; }; + + rpc update_order(Update) returns (Response) + { option(skip_excel_generation) = true; }; + + rpc detach_order(Detach) returns (Response) + { option(skip_excel_generation) = true; }; + + rpc get_registered_dynamic_order_types(bts.api.VoidMessage) + returns (RegisteredDynamicOrderTypes); + // streams rpc orders (OrdersSub) returns (stream OrderRecord); @@ -24,10 +34,20 @@ service OrderService { } // request types -message Create {OrderDefinition new_order = 1;double price = 2; uint32 quantity = 3;} -message Update {uint32 order_key = 1; double price = 2; uint32 quantity = 3;} +message Create { + OrderDefinition new_order = 1; + double price = 2; + uint32 quantity = 3; +} + +message Update { + CustomOrderDefinition custom = 4; + double price = 2; + uint32 quantity = 3; + uint32 order_key = 1; +} message Cancel {uint32 order_key = 1;}; -message Crack {uint32 order_key = 1;}; +message Detach {uint32 order_key = 1;}; // response types message Response {uint32 order_key = 1; OrderError error_code = 2; string msg = 3;} @@ -37,6 +57,9 @@ message OrdersSub {} message FillsSub {} message OrderDefinition { + // deleted fields (don't reuse!): + // - uint32 algo_template_key = 15; (originally deleted 05/03/2019) + // standard order elements uint32 security_key = 1; api.Side side = 2; @@ -44,13 +67,12 @@ message OrderDefinition { uint32 user_id = 13; string account = 6; uint32 account_id = 14; - uint32 algo_template_key = 15; TimeInForce time_in_force = 7; ManualOrderIndicator manual_order_indicator = 8; CTICode cti_code = 9; CustomerOrFirm customer_or_firm = 10; OrderSubType sub_type = 12; - + uint32 attach_target_order_key = 16; CustomOrderDefinition custom_def = 11; } @@ -74,8 +96,10 @@ message CustomOrderDefinition TriggerOrderDefinition trigger = 22; CoverOrderDefinition cover = 23; OffsetOrderDefinition offset = 24; + QueueHolderDefinition queue_holder = 30; OCOOrderDefinition oco = 25; PricerOrderDefinition pricer = 26; + CompositeOrderDefinition composite = 27; DynamicOrderDefinition dynamic = 1000; } @@ -92,6 +116,7 @@ message StopLimitOrderDefinition { } message IcebergOrderDefinition { double show_quantity = 1; + uint32 pause_between_orders_ms = 3; CustomOrderDefinition child = 2; } message SpreaderOrderDefinition { @@ -127,19 +152,12 @@ message LeanOrderDefinition { CustomOrderDefinition child = 3; } message JoinOrderDefinition { - reserved 1; reserved "tick_offset_on_deploy"; spark.QuantityMeasure join_threshold = 2; - reserved 3; reserved "enable_hedge"; - reserved 4; reserved "hedge"; - reserved 5; reserved "hedge_ticks"; CustomOrderDefinition child = 6; } message TopOrderDefinition { uint32 watch_level_tick_offset = 1; spark.QuantityMeasure top_threshold = 2; - reserved 3; reserved "enable_hedge"; - reserved 4; reserved "hedge"; - reserved 5; reserved "hedge_ticks"; CustomOrderDefinition child = 6; } message TriggerOrderDefinition { @@ -150,13 +168,20 @@ message TriggerOrderDefinition { } message CoverOrderDefinition { CustomOrderDefinition hedge = 1; - int32 hedge_ticks = 2; + uint32 hedge_ticks = 2; CustomOrderDefinition child = 3; } message OffsetOrderDefinition { uint32 tick_offset_on_deploy = 1; CustomOrderDefinition child = 6; } +message QueueHolderDefinition{ + // this is for the number of trailing + // orders behind the top one (so value + // of 1 means 2 orders in all) + uint32 n_queue_orders = 1; + CustomOrderDefinition child=10; +} message OCOOrderDefinition { CustomOrderDefinition other = 1; int32 other_ticks = 2; @@ -168,6 +193,10 @@ message PricerOrderDefinition { double price_factor = 2; CustomOrderDefinition child = 3; } +message CompositeOrderDefinition { + uint32 algo_template_key = 1; + CustomOrderDefinition definition = 2; +} message DynamicOrderDefinition { string dynamic_order_type = 1; map order_params = 2; @@ -217,6 +246,7 @@ message OrderState { TriggerOrderState trigger = 21; CoverOrderState cover = 22; OffsetOrderState offset = 24; + QueueHolderState queue_holder = 30; OCOOrderState oco = 25; PricerOrderState pricer = 26; @@ -295,6 +325,7 @@ message OffsetOrderState {} message OCOOrderState {} message PricerOrderState {} message DynamicOrderState {} +message QueueHolderState {} enum OrderStatus { @@ -429,6 +460,13 @@ enum OrderError ORDER_ERROR_ORDER_NOT_ACK = 7; ORDER_ERROR_SERVER_NOT_READY = 8; ORDER_ERROR_OK = 9; + ORDER_ERROR_OP_NOT_SUPPORTED = 10; + ORDER_ERROR_INVALID_OP = 11; + ORDER_ERROR_LIMIT_BREACH = 12; + ORDER_ERROR_MESSAGING_LIMIT_BREACH = 13; + ORDER_ERROR_UNAUTHORIZED = 14; + ORDER_ERROR_INVALID_ORDER_DEFINITON = 15; + ORDER_ERROR_UNEXPECTED_CHILD_STATE = 16; } // Trigger Condition ///////////////////////////////// diff --git a/src/lib/config/defaults/jetfix.conf b/src/lib/config/defaults/jetfix.conf index 786f3f8fe..b4c0b4b51 100644 --- a/src/lib/config/defaults/jetfix.conf +++ b/src/lib/config/defaults/jetfix.conf @@ -11,11 +11,12 @@ JetFIXSimConnection { target_compid: "BTS" target_subid: "BTS" cme_market_segment_id: 0 - end_time: "07:48:00" - start_time: "07:52:00" + end_time: "02:00:00" + start_time: "02:05:00" raw_data: "1JE9X" use_cme_secure_logon: false seconds_to_pause : 1 + max_connection_attempts: 9999999 } } } diff --git a/src/lib/config/protos/UI.proto b/src/lib/config/protos/UI.proto index 579701ce5..f49f7b6c9 100644 --- a/src/lib/config/protos/UI.proto +++ b/src/lib/config/protos/UI.proto @@ -48,6 +48,17 @@ message ShellLimits { optional uint64 limit_group_memory_mb = 3; } +message MultiThreadedWindows { + optional bool market_view = 1 [default = true]; + optional bool time_and_sales = 2 [default = true]; + optional bool order_book = 3 [default = true]; + optional bool fills = 4 [default = true]; + optional bool pnl = 5 [default = true]; + optional bool algo_studio = 6 [default = true]; + optional bool ladder = 7 [default = true]; + optional bool synthetic_management = 8 [default = true]; +} + message LadderKnobs { // priorities (ordered): SystemIdle, ApplicationIdle, ContextIdle, Background, Input, Loaded, Render, DataBind, Normal, Send // It seems like all priorities higher than ApplicationIdle choke the main thread. @@ -57,7 +68,13 @@ message LadderKnobs { optional uint32 max_open_ladders = 4 [default = 75]; optional uint32 security_timeout_secs = 5 [default = 60]; optional bool open_algo_popup_on_select = 6 [default = false]; - optional uint32 max_mbo_orders = 7 [default = 200]; + optional bool use_algo_param_grid = 7 [default = true]; + optional uint32 max_mbo_orders = 8 [default = 200]; +} + +message OrderBookOptions { + optional bool animate_child_order_rows = 1 [default = false]; + optional double status_color_opacity_when_selected = 2 [default = 0.35]; } message ShellPingOptions { @@ -100,4 +117,25 @@ message AlgoStudioOptions { message AlgoStudioFlatDefinitionModelOptions { optional bool enabled = 1 [default = true]; +} + +// TODO: The following algo-type specific attach ui messages should be consolidated into a single location, along with other algo-type metadata. +message CoverAttachUIOptions { + optional bool show_price = 1 [default = false]; + optional bool show_quantity = 2 [default = false]; +} + +message JoinAttachUIOptions { + optional bool show_price = 1 [default = false]; + optional bool show_quantity = 2 [default = false]; +} + +message LeanAttachUIOptions { + optional bool show_price = 1 [default = false]; + optional bool show_quantity = 2 [default = false]; +} + +message TopAttachUIOptions { + optional bool show_price = 1 [default = false]; + optional bool show_quantity = 2 [default = false]; } \ No newline at end of file diff --git a/src/lib/config/protos/jetfix.proto b/src/lib/config/protos/jetfix.proto index 4744002e2..c3666f5ef 100644 --- a/src/lib/config/protos/jetfix.proto +++ b/src/lib/config/protos/jetfix.proto @@ -22,10 +22,10 @@ message JetFIX { // time in seconds before reconnect attempt optional int32 reconnect_interval = 20 [default = 60]; - // time of day the FIX session becomes activated (UTC) + // time of day the FIX session becomes activated (local time) optional string start_time = 50 [default = "00:30:00"]; - // time of day the FIX session become deactiviated (UTC) + // time of day the FIX session become deactiviated (local time) optional string end_time = 60 [ default = "23:30:00"]; // time in seconds between heartbeat messages (typically 30) @@ -35,10 +35,10 @@ message JetFIX { // the connection optional int32 max_missed_hbs = 75 [default = 2]; - // time of day the FIX session becomes activated (UTC) + // day of the week (local time) when the fix session starts (blank for every day) optional string start_day = 80; - // time of day the FIX session become deactiviated (UTC) + // day of the week (local time) when the fix session ends (blank for every day) optional string end_day = 90; optional string sender_compid = 100 [default = ""]; @@ -68,7 +68,7 @@ message JetFIX { optional uint32 msg_buffer_sz = 230 [default = 10000000]; optional uint32 msg_high_water_mark = 240 [default = 2048]; - optional uint32 seconds_to_replay = 250 [default = 30]; + optional uint32 seconds_to_replay = 250 [default = 600]; optional bool log_fix_stream = 260 [default=false]; optional bool use_persisted_quote_ids = 270 [default=true]; optional uint32 quote_id_reservation_size = 290 [default=100000]; diff --git a/src/lib/config/protos/toggles.proto b/src/lib/config/protos/toggles.proto index 7985bbac7..31e9f7129 100644 --- a/src/lib/config/protos/toggles.proto +++ b/src/lib/config/protos/toggles.proto @@ -8,10 +8,6 @@ syntax='proto2'; package bts.config.toggles; -message LaddersOnThreads { - optional bool enabled = 1 [default = true]; -} - message FilterOrdersWithDanglingSecurities { optional bool enabled = 1 [default = true]; } @@ -35,9 +31,20 @@ message SoundNotifications { message VolumeAtPrice{ optional bool enabled = 1 [default = true]; } + message MBOStats { optional bool enabled = 1 [default = false]; } message PlacementInQueue { optional bool enabled = 1 [default = true]; +} +message FixNestedScrolling { + optional bool enabled = 1 [default = true]; +} + +message EnsureOnScreenWithWorkAreaRect { + // Defaulting to false bc this is near the end of the cycle (04/27/2019), + // and the new ensure_onscreen code has only been tested with a single monitor arrangement. + // Should verify that the code works with every monitor arrangement before enabling by default. + optional bool enabled = 1 [default = false]; } \ No newline at end of file diff --git a/src/lib/domain_model/Security.h b/src/lib/domain_model/Security.h index 0647fa261..9227e5b07 100644 --- a/src/lib/domain_model/Security.h +++ b/src/lib/domain_model/Security.h @@ -1,41 +1,102 @@ #pragma once -#include #include +#include - -#include "lib/domain_model/common.h" #include "lib/domain_model/Security.pb.h" +#include "lib/domain_model/common.h" #include "lib/utils/bts_assert.h" namespace bts { -namespace api {class Security;} +namespace api { +class Security; +} namespace securities { -SecurityKey security_key(api::Security const&); -std::string to_str (api::Security const&); -std::pair from_str(std::string const&); -std::string descriptor(api::Security const&); +SecurityKey security_key(api::Security const &); +std::string to_str(api::Security const &); +std::pair from_str(std::string const &); +std::string descriptor(api::Security const &); -inline Price decode_exchange_price(api::Security const&sec, Price in) { +inline std::string const &side_name(api::Side side) { + return api::Side_Name(side); +} + +inline api::Side other_side(api::Side side) { + switch (side) { + case api::SIDE_BUY: + return api::SIDE_SELL; + case api::SIDE_SELL: + return api::SIDE_BUY; + default: + return side; + } +} + +inline double market_epislon() { return 1e-10; } + +inline bool is_better(api::Side side, Price p1, Price p2) { + switch (side) { + case api::SIDE_BUY: + return p1.value() - p2.value() > market_epislon(); + case api::SIDE_SELL: + return p2.value() - p1.value() > market_epislon(); + default: + return false; + } +} + +inline Price improve_price(api::Side side, Price p, Price offset) { + switch (side) { + case api::SIDE_BUY: + return Price(p.value() + offset.value()); + case api::SIDE_SELL: + return Price(p.value() - offset.value()); + default: + bts_assert(false); + break; + } + bts_assert(false); + return Price(0); +} + +inline Price worsen_price(api::Side side, Price p, Price offset) { + return improve_price(other_side(side), p, offset); +} + +inline bool is_same(Price p1, Price p2) { + return std::abs(p1.value() - p2.value()) < market_epislon(); +} + +inline bool is_equal_or_better(api::Side side, Price p1, Price p2) { + return is_same(p1, p2) || is_better(side, p1, p2); +} + +// returns the better price out of p1, p2, if p1==p2, +// return p1 +inline Price better_price (api::Side side, Price p1, Price p2){ + return is_equal_or_better(side, p1, p2) ? p1 : p2; +} + +inline Price decode_exchange_price(api::Security const &sec, Price in) { return Price(in.value() * sec.contract_spec().price_multiplier()); } -inline Price encode_exchange_price(api::Security const&sec, Price in) { +inline Price encode_exchange_price(api::Security const &sec, Price in) { auto mult = sec.contract_spec().price_multiplier(); if (mult != 1.0) - return Price(in.value()/mult); + return Price(in.value() / mult); else - return in; + return in; } -inline double raw_round_to_quote_price (double raw_price, double tick_size, api::Side side) -{ +inline double raw_round_to_quote_price(double raw_price, double tick_size, + api::Side side) { double factor = 1000000000; - auto i_price = llround (factor * raw_price); - auto i_tick_size = llround (tick_size * factor); - + auto i_price = llround(factor * raw_price); + auto i_tick_size = llround(tick_size * factor); + long new_i_price = 0; long mod = i_price % i_tick_size; @@ -43,13 +104,12 @@ inline double raw_round_to_quote_price (double raw_price, double tick_size, api: // price is already a valid tick new_i_price = i_price; else if (side == api::SIDE_BUY) { - // buy, round down + // buy, round down if (i_price > 0) new_i_price = i_price - mod; else new_i_price = i_price - mod - i_tick_size; - } - else if (side == api::SIDE_SELL) { + } else if (side == api::SIDE_SELL) { // sell, round up if (i_price > 0) new_i_price = i_price - mod + i_tick_size; @@ -60,46 +120,62 @@ inline double raw_round_to_quote_price (double raw_price, double tick_size, api: return new_i_price / factor; } -inline double checked_round_to_quote_price(const api::ContractSpecification& spec, double price, api::Side side) { - if (std::isnan(price)) return price; +inline double +checked_round_to_quote_price(const api::ContractSpecification &spec, + double price, api::Side side) { + if (std::isnan(price)) + return price; if (price < -spec.price_break() || price > spec.price_break()) { - if (spec.high_tick() == 0) return price; + if (spec.high_tick() == 0) + return price; return raw_round_to_quote_price(price, spec.high_tick(), side); - } - else { - if (spec.low_tick() == 0) return price; + } else { + if (spec.low_tick() == 0) + return price; return raw_round_to_quote_price(price, spec.low_tick(), side); } } -inline Price round_to_quote_price(api::Security const&sec, Price in, api::Side side) { +inline Price round_to_quote_price(api::Security const &sec, Price in, + api::Side side) { auto p = in.value(); bts_assert_d(!std::isnan(p)); - if (p < -sec.contract_spec().price_break() || p > sec.contract_spec().price_break()) - return Price(raw_round_to_quote_price(p,sec.contract_spec().high_tick(),side)); - else - return Price(raw_round_to_quote_price(p,sec.contract_spec().low_tick(),side)); + if (p < -sec.contract_spec().price_break() || + p > sec.contract_spec().price_break()) + return Price( + raw_round_to_quote_price(p, sec.contract_spec().high_tick(), side)); + else + return Price( + raw_round_to_quote_price(p, sec.contract_spec().low_tick(), side)); +} + +inline Price tick_size(api::Security const &sec) { + return Price(sec.contract_spec().low_tick()); } // Looking to round md::IntPrice? Look in IntPrice.h - // computes the difference between 2 prices in ticks. // the result is an a signed int so the order of args // matter, its second price - first price -inline int price_diff_to_ticks (double price_1, double price_2, double tick_size) -{ - return static_cast (std::round((price_2 - price_1)/tick_size)); +inline int price_diff_to_ticks(double price_1, double price_2, + double tick_size) { + return static_cast(std::round((price_2 - price_1) / tick_size)); } // because of prices not being completely rounded to the tick, -// simple double equality can not be used to compare prices. +// simple double equality can not be used to compare prices. // this function deems 2 prices to be equal if they are within // 1 % of the tick size -inline bool test_price_equality (double price_1, double price_2, double tick_size) -{ +inline bool test_price_equality(double price_1, double price_2, + double tick_size) { return std::fabs(price_2 - price_1) < 0.01 * tick_size; } -inline bool gr_than_eq(double p1, double p2, double tick_size){ - return test_price_equality(p1,p2,tick_size) || p1>=p2; +inline bool gr_than_eq(double p1, double p2, double tick_size) { + return test_price_equality(p1, p2, tick_size) || p1 >= p2; } -}} +inline bool gr_than(double p1, double p2, double tick_size) { + return gr_than_eq(p1, p2, tick_size) && + !test_price_equality(p1,p2,tick_size); +} +} // namespace securities +} // namespace bts diff --git a/src/lib/jetfix/codec/FIXFragment.h b/src/lib/jetfix/codec/FIXFragment.h index 475adc68e..1ee163111 100644 --- a/src/lib/jetfix/codec/FIXFragment.h +++ b/src/lib/jetfix/codec/FIXFragment.h @@ -88,7 +88,8 @@ public: FIXFragment&operator=(FIXFragment &&src) { this->~FIXFragment (); - _buffer = std::move (src._buffer); + _buffer = src._buffer; + _owns_buffer = src._owns_buffer; _checksum= src._checksum; _initial_offset = src._initial_offset; src._buffer = nullptr; diff --git a/src/lib/jetfix/gateway/CoreGateway.cpp b/src/lib/jetfix/gateway/CoreGateway.cpp index 4ef84d41b..8b014898c 100644 --- a/src/lib/jetfix/gateway/CoreGateway.cpp +++ b/src/lib/jetfix/gateway/CoreGateway.cpp @@ -442,7 +442,9 @@ void CoreGateway::sync_time(EventData const &ev) { me->connection_attempts++; if (!me->has_replayed) { - me->observer.replay(me->session_info->store->replay()); + auto msgs_to_replay = me->session_info->store->replay(); + LOG(Jetfix, Warn, "Replaying {} FIX msgs", msgs_to_replay.size()); + me->observer.replay(msgs_to_replay); me->has_replayed = true; } diff --git a/src/lib/jetfix/store/FIXFileStore.cpp b/src/lib/jetfix/store/FIXFileStore.cpp index 8b6825a73..25c4d05cd 100644 --- a/src/lib/jetfix/store/FIXFileStore.cpp +++ b/src/lib/jetfix/store/FIXFileStore.cpp @@ -115,7 +115,7 @@ std::string store_path(std::string base_path, std::map load_replay(config::JetFIX::Connection const &cfg, std::string const &path, - uint32_t max_sn) { + uint32_t ) { std::map result; if (boost::filesystem::exists(path)) { @@ -136,8 +136,7 @@ load_replay(config::JetFIX::Connection const &cfg, std::string const &path, cfg.seconds_to_replay())) { InMsgBuffer msg(line_buffer.substr(24)); auto sn = msg.get_seq_num(); - if (sn <= max_sn) - result[sn] = msg; + result[sn] = msg; } } } else @@ -193,15 +192,13 @@ FIXFileStore::FIXFileStore(config::JetFIX::Connection const &cfg, auto fix_log_p = fix_log_path(path); auto replay_messages = load_replay(cfg, fix_log_p, me->last_seq_num_processed); - uint32_t previous_sn = 0; + auto max_sn = 0u; for (auto &p : replay_messages) { auto sn = p.first; auto &m = p.second; - if (!(m.has_poss_dup_flag_flag() && m.get_poss_dup_flag())) { - if (previous_sn != 0) - bts_assert(sn == (previous_sn + 1)); - previous_sn = sn; + if (sn > max_sn) { me->replay_messages.emplace_back(m); + max_sn = sn; } } me->fix_store.open(fix_log_p, std::ofstream::app); diff --git a/src/lib/md/MDConsumer.cpp b/src/lib/md/MDConsumer.cpp index a303c34ad..3a6610dae 100644 --- a/src/lib/md/MDConsumer.cpp +++ b/src/lib/md/MDConsumer.cpp @@ -269,6 +269,16 @@ public: if (!_cold.is_initialized()) return true; return is_heart_beat_ok(cold_header()); } + + void dump_shm_to(const char* directory) const { + _cold.dump_to(directory); + if (_hot) { + _hot->dump_to(directory); + } + if (_hot_depth) { + _hot_depth->dump_to(directory); + } + } private: @@ -910,6 +920,15 @@ public: return result; } + void dump_shm_to(const char* p) const { + // To be safe we should lock _work_mutex -but- + // we need this function to diagnose problems happening in the on_security callback + // which holds the _work_mutex. Since anyone calling this function is going down + // anyway we as well live dangerously. + for (auto& inst : _instances) { + inst->dump_shm_to(p); + } + } }; @@ -957,6 +976,8 @@ MDConsumerChannel MDConsumer::get_channel(const std::string& symbol, SecurityTyp MDConsumerChannel MDConsumer::get_channel(const UserSymbol& u) const { return _pimpl->get_channel(u.symbol(), u.type(), u.exchange()); } +void MDConsumer::dump_shm_to(const char* p) const { _pimpl->dump_shm_to(p); } + MDConsumerChannel::MDConsumerChannel(const shared_ptr& inst) : _pimpl(inst) {} int64_t MDConsumerChannel::read_trades(google::protobuf::RepeatedPtrField& trades, int64_t cursor) { return _pimpl->read_trades(trades, cursor); } diff --git a/src/lib/md/MDConsumer.h b/src/lib/md/MDConsumer.h index 103e8bb19..d197499a3 100644 --- a/src/lib/md/MDConsumer.h +++ b/src/lib/md/MDConsumer.h @@ -67,6 +67,8 @@ public: } uintptr_t id() const { return reinterpret_cast(_pimpl.get()); } + void dump_shm_to(const char* directory) const; + private: //BTS_NO_COPY(MDConsumer); COPY OK std::shared_ptr _pimpl; diff --git a/src/lib/md/MDConsumerInterop.cpp b/src/lib/md/MDConsumerInterop.cpp index 17a36b072..88972112d 100644 --- a/src/lib/md/MDConsumerInterop.cpp +++ b/src/lib/md/MDConsumerInterop.cpp @@ -177,5 +177,11 @@ CAPI void post_on_scan_security_thread(just_action a) { md::scan_securities_thread().post(a); } +CAPI void dump_co2_memory_to_disk(MDConsumer* consumer, const char* path) { + if (consumer) { + consumer->dump_shm_to(path); + } +} + }} //namespace #endif diff --git a/src/lib/md/relay/RelayClient.cpp b/src/lib/md/relay/RelayClient.cpp index 9830a6cc7..54c3a9066 100644 --- a/src/lib/md/relay/RelayClient.cpp +++ b/src/lib/md/relay/RelayClient.cpp @@ -143,7 +143,9 @@ public: LOG(md,Diag, "Added {} trades", ch.trade_log_size()); } for (const auto& trade : ch.trade_log()) { - channel.add_trade(trade); + if (trade.key()) { + channel.add_trade(trade); + } } for (const auto& rfq : ch.rfq_log()) { channel.add_rfq(rfq); diff --git a/src/lib/mercury/actors/ContentSubscription.h b/src/lib/mercury/actors/ContentSubscription.h index 9b7d3257c..f7bfa648f 100644 --- a/src/lib/mercury/actors/ContentSubscription.h +++ b/src/lib/mercury/actors/ContentSubscription.h @@ -1,13 +1,12 @@ #pragma once #include "lib/mercury/actors/Actor.h" +#include "lib/tracing/PerfLog.h" +#include "lib/utils/bts_assert.h" +#include #include #include #include -#include -#include "lib/tracing/PerfLog.h" - -#include "lib/utils/bts_assert.h" namespace bts { namespace mercury { @@ -33,45 +32,82 @@ template class ContentSubscription { struct SubID { SubID() : k(), sid(0) {} SubID(Key k, uint32_t sid) : k(k), sid(sid) {} - + Key k; uint32_t sid; bool operator==(SubID const &rhs) const { return k == rhs.k && sid == rhs.sid; } + + bool operator!=(SubID const &rhs) const { return !operator==(rhs); } + bool empty() const { return sid == 0; } + void clear() { sid = 0; } }; - void init() { - _name = utils::type_name(); - } - - ContentSubscription(Actor &actor, trace::PerfLog& log) + ContentSubscription(Actor &actor, trace::PerfLog &log) : _actor(&actor), _sub(_actor->subscribe( [this](auto const &u) { this->on_update(u); })), _my_subs(), _dispatching(false), _current_sub_id(1), - _pre_sub([](auto) {}), _log(log) {init();} + _pre_sub([](auto const &) {}), _log(log), + _name(utils::type_name()), _pre_event([](auto const &) {}) {} - ContentSubscription(Actor &actor, std::function const &pscb, trace::PerfLog& log) + ContentSubscription(Actor &actor, std::function const &pscb, + trace::PerfLog &log) : _actor(&actor), _sub(_actor->subscribe( [this](auto const &u) { this->on_update(u); })), - _my_subs(), _dispatching(false), _current_sub_id(0), _pre_sub(pscb), _log(log) {init();} + _my_subs(), _dispatching(false), _current_sub_id(1), _pre_sub(pscb), + _log(log), _name(utils::type_name()), + _pre_event([](auto const &) {}) {} + + ContentSubscription(Actor &actor, std::function const &pscb, + std::function const &pre_ev, + trace::PerfLog &log) + : _actor(&actor), _sub(_actor->subscribe( + [this](auto const &u) { this->on_update(u); })), + _my_subs(), _dispatching(false), _current_sub_id(1), _pre_sub(pscb), + _log(log), _name(utils::type_name()), _pre_event(pre_ev) {} template - ContentSubscription(Actor &actor, Tag const &tag, trace::PerfLog& log) + ContentSubscription(Actor &actor, Tag const &tag, trace::PerfLog &log) : _actor(&actor), _sub(_actor->subscribe( tag, [this](auto const &u) { this->on_update(u); })), _my_subs(), _dispatching(false), _current_sub_id(1), - _pre_sub([](auto) {}), _log(log) {init();} + _pre_sub([](auto const &) {}), _log(log), + _name(utils::type_name()), _pre_event([](auto const &) {}) {} template ContentSubscription(Actor &actor, Tag const &tag, - std::function const &pscb, trace::PerfLog& log) + std::function const &pscb, + trace::PerfLog &log) + : _actor(&actor), + _sub(_actor->subscribe( + tag, [this](auto const &u) { this->on_update(u); })), + _my_subs(), _dispatching(false), _current_sub_id(1), _pre_sub(pscb), + _log(log), _name(utils::type_name()), + _pre_event([](auto const &) {}) {} + + template + ContentSubscription(Actor &actor, Tag const &tag, + std::function const &pre_ev, + trace::PerfLog &log) : _actor(&actor), _sub(_actor->subscribe( tag, [this](auto const &u) { this->on_update(u); })), _my_subs(), _dispatching(false), _current_sub_id(1), - _pre_sub(pscb), _log(log) {init();} + _pre_sub([](auto const &) {}), _log(log), + _name(utils::type_name()), _pre_event(pre_ev) {} + + template + ContentSubscription(Actor &actor, Tag const &tag, + std::function const &pscb, + std::function const &pre_ev, + trace::PerfLog &log) + : _actor(&actor), + _sub(_actor->subscribe( + tag, [this](auto const &u) { this->on_update(u); })), + _my_subs(), _dispatching(false), _current_sub_id(1), _pre_sub(pscb), + _log(log), _name(utils::type_name()), _pre_event(pre_ev) {} template SubID sub(Key k, CBT const &cb) { _pre_sub(k); @@ -106,7 +142,7 @@ template class ContentSubscription { CB cb; }; - using SubList = boost::container::small_vector; + using SubList = boost::container::small_vector; using Subscriptions = std::unordered_map; Actor *_actor; @@ -116,22 +152,27 @@ template class ContentSubscription { bool _dispatching; uint32_t _current_sub_id; std::function _pre_sub; - trace::PerfLog& _log; + trace::PerfLog &_log; std::string _name; + std::function _pre_event; + void on_update(Update const &u) { - auto scoped_do_work = trace::log_scope(_log, {}, "ContentSub::on_update", 0, _name.c_str()); + auto scoped_do_work = + trace::log_scope(_log, {}, "ContentSub::on_update", 0, _name.c_str()); KE ke; _dispatching = true; if (u.events) for (auto const &ev : *(u.events)) { + _pre_event(ev); auto k = ke(ev); - _aux_sub_list = _my_subs[k]; // we copy so we can allow for unsub/sub during dispatch + _aux_sub_list = _my_subs[k]; // we copy so we can allow for + // unsub/sub during dispatch for (auto const &sub : _aux_sub_list) sub.cb(ev); } _dispatching = false; } }; -} -} +} // namespace mercury +} // namespace bts diff --git a/src/lib/orderman/actors/FillStore.cpp b/src/lib/orderman/actors/FillStore.cpp index f5f114eb6..3d6652726 100644 --- a/src/lib/orderman/actors/FillStore.cpp +++ b/src/lib/orderman/actors/FillStore.cpp @@ -2,6 +2,7 @@ #include "lib/api/services/OrderService.pb.h" #include "lib/orderman/actors/SODPosition.h" #include "lib/orderman/events/NewExecutionReportEvent.h" +#include "lib/orderman/events/OrderDefinitionUpdateEvent.h" #include "lib/orderman/events/OrderStateUpdateEvent.h" #include "lib/orderman/events/StoredFillEvent.h" #include "lib/persistence/SqliteStore.h" @@ -20,14 +21,13 @@ struct FillStore::UnresolvedFills { }; struct FillStore::PImpl { - PImpl(md::SecurityOracle& oracle) - : store(new persistence::SqliteStore("fills")), - known_orders(), fills_with_unresolved_accounts(), sod_pos_map(), oracle(oracle) {} + PImpl(md::SecurityOracle &oracle) + : store(new persistence::SqliteStore("fills")), known_orders(), + fills_with_unresolved_accounts(), sod_pos_map(), oracle(oracle) {} std::unique_ptr store; std::unordered_set known_fills; - std::unordered_map - known_orders; + std::unordered_map known_orders; std::unordered_map fills_with_unresolved_accounts; mercury::Stream fill_stream; SODPosition sod_pos_map; @@ -40,7 +40,7 @@ void FillStore::init() { // Subscribe to NewExecutionReportEvent for new fills subscribe( - [this](auto const &ev) { this->on_execution_report(ev); }); + [this](auto const &ev) { this->on_execution_report(ev); }); // Load stored fills, resolve their securities and publish the lot api::orderman::Fill fill; @@ -49,8 +49,7 @@ void FillStore::init() { auto all = me->store->retrieve_all()[fills_ns]; LOG(persist, Info, "Finished loading all {} fills", all.size()); for (auto const &kvp : all) - if (utils::pb::from_string(kvp.second, - &fill)) { + if (utils::pb::from_string(kvp.second, &fill)) { auto sec = me->oracle.get_security(SecurityKey(fill.security_key())); if (sec) { @@ -60,25 +59,25 @@ void FillStore::init() { me->known_fills.insert(fk); } else LOG(persist, Error, - "Stored fill {} contains unresolved security {}. ", - kvp.first, fill.security_key()); + "Stored fill {} contains unresolved security {}. ", kvp.first, + fill.security_key()); } else LOG(persist, Error, - "Could not recover fill {} from storage. " - "This should be investigated", - kvp.first); + "Could not recover fill {} from storage. " + "This should be investigated", + kvp.first); me->fill_stream = make_stream(); LOG(OrderMan, Info, - "Fill Store published {} fills recoved from disk out of {} " - "total fills", - stored_batch.size(), all.size()); + "Fill Store published {} fills recoved from disk out of {} " + "total fills", + stored_batch.size(), all.size()); me->sod_pos_map.add_sod_pos_as_fill_events(stored_batch, me->oracle); publish_batch(me->fill_stream, stored_batch); - // subscribe to order updates so we can resolve + // subscribe to order definition updates so we can resolve // account ids for future execution reports - subscribe( - [this](auto const &ev) { this->on_order_state_update(ev); }); + subscribe( + [this](auto const &ev) { this->on_order_definition_update(ev); }); } FillStore::~FillStore() {} @@ -115,10 +114,11 @@ void FillStore::on_execution_report( fill.mutable_timestamp()->set_seconds(tv.tv_sec); fill.mutable_timestamp()->set_nanos(tv.tv_usec * 1000); - auto order_def = me->known_orders[er.order_key]; - if (order_def) - fill.set_account(order_def->account()); - else + auto it = me->known_orders.find(er.order_key); + if (it != me->known_orders.end()) { + auto &order_def = it->second; + fill.set_account(order_def.account()); + } else me->fills_with_unresolved_accounts[er.order_key] .fills.push_back(fill); @@ -134,17 +134,17 @@ void FillStore::on_execution_report( } // if u.events } -void FillStore::on_order_state_update( - mercury::Update const &u) { +void FillStore::on_order_definition_update( + mercury::Update const &u) { if (u.events) for (auto const &ev : *u.events) { - me->known_orders[ev.key] = ev.definition; + me->known_orders[ev.key] = *ev.def; // see if we can resolve the accounts for any fills that we // might have already received for this order auto &unresolved_fills = me->fills_with_unresolved_accounts[ev.key]; for (auto &f : unresolved_fills.fills) { - f.set_account(ev.definition->account()); + f.set_account(ev.def->account()); auto fv = utils::pb::to_string(f); me->store->update(fills_ns, f.fill_key(), fv); publish(me->fill_stream, f, *unresolved_fills.security); diff --git a/src/lib/orderman/actors/FillStore.h b/src/lib/orderman/actors/FillStore.h index 1d35e032c..f42a1ac7a 100644 --- a/src/lib/orderman/actors/FillStore.h +++ b/src/lib/orderman/actors/FillStore.h @@ -7,7 +7,7 @@ namespace bts { namespace orderman { class NewExecutionReportEvent; -class OrderStateUpdateEvent; +class OrderDefinitionUpdateEvent; // Listens for fill execution reports published by fix gateways, // republishing them as StoredFillEvent events and storing those on @@ -20,13 +20,12 @@ public: void init() override; private: - enum class State; struct PImpl; struct UnresolvedFills; std::unique_ptr me; void on_execution_report(const mercury::Update &); - void on_order_state_update(mercury::Update const&); + void on_order_definition_update(mercury::Update const&); }; }} diff --git a/src/lib/orderman/actors/OrderStore.cpp b/src/lib/orderman/actors/OrderStore.cpp index 4e5f43b38..292272751 100644 --- a/src/lib/orderman/actors/OrderStore.cpp +++ b/src/lib/orderman/actors/OrderStore.cpp @@ -5,6 +5,7 @@ #include "lib/config/protos/orders_fills_cleanup.pb.h" #include "lib/config/protos/toggles.pb.h" #include "lib/orderman/actors/SODPosition.h" +#include "lib/orderman/events/OrderDefinitionUpdateEvent.h" #include "lib/orderman/events/OrderStateUpdateEvent.h" #include "lib/orderman/events/StoredOrderEvent.h" #include "lib/persistence/SqliteStore.h" @@ -19,14 +20,18 @@ static auto const orders_ns = "orders"; struct OrderStore::PImpl { PImpl(md::SecurityOracle o) - : known_orders(), - store(new persistence::SqliteStore("orders")), order_stream(), + : known_orders(), store(new persistence::SqliteStore("orders")), + order_stream(), soft_cleanup_enabled( config::get().enabled()), oracle(o) {} const GatewayName gw_name; - std::unordered_map known_orders; + struct ORInfo { + api::orderman::OrderRecord rec; + bool is_saved; + }; + std::unordered_map known_orders; std::unique_ptr store; mercury::Stream order_stream; bool soft_cleanup_enabled; @@ -39,83 +44,112 @@ OrderStore::~OrderStore() {} void OrderStore::init() { - // subscribe to order updates so we can store them - subscribe( - [this](auto const &ev) { this->on_order_state_update(ev); }); + // subscribe to order updates so we can store them + subscribe( + [this](auto const &ev) { this->on_order_state_update(ev); }); - // now load orders from disk, for each order check if - // it reffers to a valid security. if so publish it. - api::orderman::OrderRecord rec; - std::vector stored_batch; + subscribe( + [this](auto const &ev) { this->on_order_definition_update(ev); }); - LOG(persist, Info, "Loading all orders"); - auto all = me->store->retrieve_all()[orders_ns]; - LOG(persist, Info, "Finished loading all {} orders", all.size()); + // now load orders from disk, for each order check if + // it reffers to a valid security. if so publish it. + api::orderman::OrderRecord rec; + std::vector stored_batch; - me->cutoff_time = SODPosition::get_order_cutoff_time(all); + LOG(persist, Info, "Loading all orders"); + auto all = me->store->retrieve_all()[orders_ns]; + LOG(persist, Info, "Finished loading all {} orders", all.size()); - for (auto const &kvp : all) - if (utils::pb::from_string( - kvp.second, &rec)) { - auto ok = OrderKey(std::stoi(kvp.first)); - auto sk = SecurityKey(rec.def().security_key()); - auto sec = me->oracle.get_security(sk); + me->cutoff_time = SODPosition::get_order_cutoff_time(all); - if (config::get() - .enabled() && sec == nullptr) { - LOG(OrderMan, Diag, - "Order {} refers to unresolved security {}", - ok.value(), sk.value()); - } else { - if (!_order_cutoff(rec)) - stored_batch.emplace_back(rec); - me->known_orders[ok] = rec.state(); - } - } else - LOG(OrderMan, Error, - "Could not recover order {} from storage. " - "This should be investigated", - kvp.first); + for (auto const &kvp : all) + if (utils::pb::from_string(kvp.second, + &rec)) { + auto ok = OrderKey(std::stoi(kvp.first)); + auto sk = SecurityKey(rec.def().security_key()); + auto sec = me->oracle.get_security(sk); - me->order_stream = make_stream(); - LOG(OrderMan, Info, - "Order Store published {} orders recoved from disk out of {} " - "total orders", - stored_batch.size(), all.size()); - publish_batch(me->order_stream, stored_batch); + if (config::get() + .enabled() && + sec == nullptr) { + LOG(OrderMan, Diag, "Order {} refers to unresolved security {}", + ok.value(), sk.value()); + } else { + if (!_order_cutoff(rec)) + stored_batch.emplace_back(rec); + me->known_orders[ok] = PImpl::ORInfo{rec, true}; + } + } else + LOG(OrderMan, Error, + "Could not recover order {} from storage. " + "This should be investigated", + kvp.first); + + me->order_stream = make_stream(); + LOG(OrderMan, Info, + "Order Store published {} orders recoved from disk out of {} " + "total orders", + stored_batch.size(), all.size()); + publish_batch(me->order_stream, stored_batch); } void OrderStore::on_order_state_update( mercury::Update const &u) { + + std::set modified_orders; if (u.events) for (auto const &ev : *u.events) { - api::orderman::OrderRecord order; - order.set_key(ev.key.value()); - order.set_parent_key(ev.parent_key.value()); - *order.mutable_def() = *ev.definition; - *order.mutable_state() = ev.rebuild_state(); - *order.mutable_state()->mutable_last_change() = utils::pb::pb_now(); - - auto it = me->known_orders.find(ev.key); - if (it == me->known_orders.end()) { - // new order - auto now = utils::pb::pb_now(); - *order.mutable_state()->mutable_created() = now; - me->known_orders[ev.key] = order.state(); - me->store->insert(orders_ns, std::to_string(order.key()), - utils::pb::to_string(order)); - } else { - // existing order - auto &existing_state = it->second; - existing_state.MergeFrom(order.state()); - *order.mutable_state() = existing_state; - me->store->update(orders_ns, std::to_string(order.key()), - utils::pb::to_string(order)); + auto &rec_info = me->known_orders[ev.key]; + auto &rec = rec_info.rec; + bts_assert(rec.has_def()); + rec.set_key(ev.key.value()); + rec.set_parent_key(ev.parent_key.value()); + modified_orders.insert(ev.key); + if (rec.has_state()) + rec.mutable_state()->MergeFrom(ev.rebuild_state()); + else { + *rec.mutable_state() = ev.rebuild_state(); + *rec.mutable_state()->mutable_created() = utils::pb::pb_now(); } - LOG(OrderMan, Diag, "Storing order {}", utils::pb::to_string(order)); - publish(me->order_stream, order); + *rec.mutable_state()->mutable_last_change() = utils::pb::pb_now(); } + store_and_publish_if_complete(modified_orders); +} + +void OrderStore::on_order_definition_update( + mercury::Update const &u) { + + std::set modified_orders; + if (u.events) + for (auto const &ev : *u.events) { + auto &rec_info = me->known_orders[ev.key]; + auto &rec = rec_info.rec; + rec.set_key(ev.key.value()); + rec_info.is_saved = rec.has_def(); + *rec.mutable_def() = *ev.def; + modified_orders.insert(ev.key); + } + store_and_publish_if_complete(modified_orders); +} + +void OrderStore::store_and_publish_if_complete( + std::set const &changed) { + for (auto k : changed) { + auto &rec_info = me->known_orders[k]; + auto &rec = rec_info.rec; + if (rec.has_def() && rec.has_state()) { + publish(me->order_stream, rec); + if (rec_info.is_saved) + me->store->update(orders_ns, std::to_string(k.value()), + utils::pb::to_string(rec)); + else { + me->store->insert(orders_ns, std::to_string(k.value()), + utils::pb::to_string(rec)); + rec_info.is_saved = true; + } + } + } } bool OrderStore::_order_cutoff(const api::orderman::OrderRecord &rec) { diff --git a/src/lib/orderman/actors/OrderStore.h b/src/lib/orderman/actors/OrderStore.h index 6b46df8ce..14a7e459e 100644 --- a/src/lib/orderman/actors/OrderStore.h +++ b/src/lib/orderman/actors/OrderStore.h @@ -9,6 +9,7 @@ namespace bts { namespace api {namespace orderman {class OrderRecord;}} namespace orderman { class OrderStateUpdateEvent; +class OrderDefinitionUpdateEvent; // listens for OrderStateUpdateEvent events and maps them to // StoredOrderEvent events, storing them to disk in the process. On @@ -21,12 +22,13 @@ public: void init() override; private: - enum class State; struct PImpl; std::unique_ptr me; bool _order_cutoff(const api::orderman::OrderRecord& rec); + void store_and_publish_if_complete(std::set const&); void on_order_state_update(mercury::Update const&ev); + void on_order_definition_update(mercury::Update const&ev); }; }} diff --git a/src/lib/orderman/actors/ServiceBridge.cpp b/src/lib/orderman/actors/ServiceBridge.cpp index 81e96c7b8..4d104dd5f 100644 --- a/src/lib/orderman/actors/ServiceBridge.cpp +++ b/src/lib/orderman/actors/ServiceBridge.cpp @@ -4,17 +4,18 @@ #include "lib/mercury/broker/BrokerProxy.h" #include "lib/orderman/events/ActivateOrderEvent.h" #include "lib/orderman/events/CancelOrderEvent.h" -#include "lib/orderman/events/CrackOrderEvent.h" +#include "lib/orderman/events/DetachOrderEvent.h" #include "lib/orderman/events/NewAdminDataEvent.h" #include "lib/orderman/events/OrderManagerReadyEvent.h" +#include "lib/orderman/events/OrderOpResultEvent.h" #include "lib/orderman/events/StoredFillEvent.h" #include "lib/orderman/events/StoredOrderEvent.h" #include "lib/orderman/events/UpdateOrderEvent.h" #include "lib/orderman/order_factory/OrderFactory.h" #include "lib/orderman/order_router/OrderRouter.h" #include "lib/orderman/securities/MapSecurityDB.h" -#include "lib/utils/PBUtils.h" #include "lib/tracing/PerfLog.h" +#include "lib/utils/PBUtils.h" #include "lib/api/services/OrderService.pb.h" #include "lib/orderman/orderman_utils/orderman_common.h" @@ -26,18 +27,19 @@ namespace orderman { struct ServiceBridge::PImpl { PImpl(OnReady const &on_ready, OnOrders const &on_orders, - OnFills const &on_fills, + OnFills const &on_fills, OnOrderOpResult const &on_order_op_result, DynamicOrderRegistry const &dyn_order_registry, mercury::BrokerProxy &service_call_marshaller, md::SecurityOracle o) : on_ready(on_ready), on_orders(on_orders), on_fills(on_fills), - have_orders(false), order_manager_ready(false), - sec_db(o), order_router(), + on_order_op_result(on_order_op_result), have_orders(false), + order_manager_ready(false), sec_db(o), order_router(), order_factory(sec_db, order_router, dyn_order_registry), known_orders(), service_call_marshaller(service_call_marshaller) {} OnReady on_ready; OnOrders on_orders; OnFills on_fills; + OnOrderOpResult on_order_op_result; bool have_orders; bool order_manager_ready; securities::MapSecurityDB sec_db; @@ -46,7 +48,7 @@ struct ServiceBridge::PImpl { mercury::Stream activate_order_pub; mercury::Stream update_order_pub; mercury::Stream cancel_order_pub; - mercury::Stream crack_order_pub; + mercury::Stream detach_order_pub; mercury::Stream new_admin_data_pub; std::unordered_set known_orders; std::vector> admin_data_updates; @@ -56,10 +58,12 @@ struct ServiceBridge::PImpl { ServiceBridge::ServiceBridge(OnReady const &on_ready, OnOrders const &on_orders, OnFills const &on_fills, + OnOrderOpResult const &on_order_op_result, DynamicOrderRegistry const &dyn_order_registry, - mercury::BrokerProxy &service_call_marshaller, md::SecurityOracle o) - : me(new PImpl(on_ready, on_orders, on_fills, dyn_order_registry, - service_call_marshaller, o)) {} + mercury::BrokerProxy &service_call_marshaller, + md::SecurityOracle o) + : me(new PImpl(on_ready, on_orders, on_fills, on_order_op_result, + dyn_order_registry, service_call_marshaller, o)) {} ServiceBridge::~ServiceBridge() {} @@ -70,11 +74,12 @@ void ServiceBridge::init() { subscribe([this](auto const &u) { this->on(u); }); subscribe([this](auto const &u) { this->on(u); }); subscribe([this](auto const &u) { this->on(u); }); + subscribe([this](auto const &u) { this->on(u); }); me->activate_order_pub = make_stream(); me->update_order_pub = make_stream(); me->cancel_order_pub = make_stream(); - me->crack_order_pub = make_stream(); + me->detach_order_pub = make_stream(); me->new_admin_data_pub = make_stream(); me->ready.set_value(); } @@ -119,106 +124,89 @@ void ServiceBridge::on(mercury::Update const &update) { me->order_router.update(*ev.admin_data); } -api::orderman::Response -ServiceBridge::create_order(api::orderman::Create const &c) { +void ServiceBridge::on(mercury::Update const &update) { + if (update.events) + for (auto ev : *(update.events)) + me->on_order_op_result(ev); +} + +void ServiceBridge::create_order(uint32_t rid, api::orderman::Create const &c) { + LOG(OrderMan, Info, "Received new order from client: {}", utils::pb::to_string(c)); - std::promise p; - auto f = p.get_future(); - - me->service_call_marshaller.schedule_action([this, &c, &p]() { - api::orderman::Response r; - + me->service_call_marshaller.schedule_action([this, c, rid]() { if (is_ready()) { auto &order = me->order_factory.create(null_order_key(), c.new_order()); me->known_orders.insert(order.key()); - publish(me->activate_order_pub, order, Price(c.price()), - Quantity(c.quantity()), trace::CorID()); - r.set_order_key(order.key().value()); - r.set_error_code(api::orderman::ORDER_ERROR_OK); + publish(me->activate_order_pub, rid, order, Price(c.price()), + Quantity(c.quantity())); } else - r.set_error_code(api::orderman::ORDER_ERROR_SERVER_NOT_READY); - p.set_value(r); + me->on_order_op_result(OrderOpResultEvent( + null_order_key(), rid, + OrderOpResult(api::orderman::ORDER_ERROR_SERVER_NOT_READY))); }); - return f.get(); } -api::orderman::Response -ServiceBridge::update_order(api::orderman::Update const &c) { +void ServiceBridge::update_order(uint32_t rid, api::orderman::Update const &c) { LOG(OrderMan, Info, "Received order update from client: {}", utils::pb::to_string(c)); - std::promise p; - auto f = p.get_future(); - - me->service_call_marshaller.schedule_action([this, &c, &p]() { - api::orderman::Response r; - + me->service_call_marshaller.schedule_action([this, c, rid]() { + auto ok = OrderKey(c.order_key()); if (is_ready()) { - auto ok = OrderKey(c.order_key()); - r.set_order_key(c.order_key()); - if (me->known_orders.count(ok)) { - publish(me->update_order_pub, ok, Price(c.price()), - Quantity(c.quantity())); - r.set_error_code(api::orderman::ORDER_ERROR_OK); - } else - r.set_error_code(api::orderman::ORDER_ERROR_UNKNOWN_ORDER); + if (me->known_orders.count(ok)) + publish(me->update_order_pub, rid, c); + else + me->on_order_op_result(OrderOpResultEvent( + ok, rid, + OrderOpResult(api::orderman::ORDER_ERROR_UNKNOWN_ORDER))); } else - r.set_error_code(api::orderman::ORDER_ERROR_SERVER_NOT_READY); - p.set_value(r); + me->on_order_op_result(OrderOpResultEvent( + ok, rid, + OrderOpResult(api::orderman::ORDER_ERROR_SERVER_NOT_READY))); }); - return f.get(); } -api::orderman::Response -ServiceBridge::cancel_order(api::orderman::Cancel const &c) { +void ServiceBridge::cancel_order(uint32_t rid, api::orderman::Cancel const &c) { LOG(OrderMan, Info, "Received order cancel from client: {}", utils::pb::to_string(c)); - std::promise p; - auto f = p.get_future(); - - me->service_call_marshaller.schedule_action([this, &c, &p]() { - api::orderman::Response r; - + me->service_call_marshaller.schedule_action([this, c, rid]() { + auto ok = OrderKey(c.order_key()); if (is_ready()) { - auto ok = OrderKey(c.order_key()); - r.set_order_key(c.order_key()); - if (me->known_orders.count(ok)) { - publish(me->cancel_order_pub, ok); - r.set_error_code(api::orderman::ORDER_ERROR_OK); - } else - r.set_error_code(api::orderman::ORDER_ERROR_UNKNOWN_ORDER); + if (me->known_orders.count(ok)) + publish(me->cancel_order_pub, rid, ok); + else + me->on_order_op_result(OrderOpResultEvent( + ok, rid, + OrderOpResult(api::orderman::ORDER_ERROR_UNKNOWN_ORDER))); } else - r.set_error_code(api::orderman::ORDER_ERROR_SERVER_NOT_READY); - p.set_value(r); + me->on_order_op_result(OrderOpResultEvent( + ok, rid, + OrderOpResult(api::orderman::ORDER_ERROR_SERVER_NOT_READY))); }); - return f.get(); } -api::orderman::Response -ServiceBridge::crack_order(api::orderman::Crack const &c) { - std::promise p; - auto f = p.get_future(); - - me->service_call_marshaller.schedule_action([this, &c, &p]() { - api::orderman::Response r; +void ServiceBridge::detach_order(uint32_t rid, api::orderman::Detach const &c) { + LOG(OrderMan, Info, "Received order detach from client: {}", + utils::pb::to_string(c)); + me->service_call_marshaller.schedule_action([this, c, rid]() { + auto ok = OrderKey(c.order_key()); if (is_ready()) { - auto ok = OrderKey(c.order_key()); - r.set_order_key(c.order_key()); - if (me->known_orders.count(ok)) { - publish(me->crack_order_pub, ok); - r.set_error_code(api::orderman::ORDER_ERROR_OK); - } else - r.set_error_code(api::orderman::ORDER_ERROR_UNKNOWN_ORDER); + if (me->known_orders.count(ok)) + publish(me->detach_order_pub, rid, ok); + else + me->on_order_op_result(OrderOpResultEvent( + ok, rid, + OrderOpResult(api::orderman::ORDER_ERROR_UNKNOWN_ORDER))); } else - r.set_error_code(api::orderman::ORDER_ERROR_SERVER_NOT_READY); - p.set_value(r); + me->on_order_op_result(OrderOpResultEvent( + ok, rid, + OrderOpResult(api::orderman::ORDER_ERROR_SERVER_NOT_READY))); }); - return f.get(); } void ServiceBridge::update_admin_data( diff --git a/src/lib/orderman/actors/ServiceBridge.h b/src/lib/orderman/actors/ServiceBridge.h index 1c949f061..bcf225db1 100644 --- a/src/lib/orderman/actors/ServiceBridge.h +++ b/src/lib/orderman/actors/ServiceBridge.h @@ -20,7 +20,7 @@ class Response; class Create; class Update; class Cancel; -class Crack; +class Detach; } // namespace orderman } // namespace api namespace orderman { @@ -28,6 +28,7 @@ class StoredFillEvent; class StoredOrderEvent; class OrderManagerReadyEvent; class NewAdminDataEvent; +class OrderOpResultEvent; class DynamicOrderRegistry; } // namespace orderman } // namespace bts @@ -48,7 +49,11 @@ class ServiceBridge : public mercury::Actor { using OnFills = std::function const &)>; + using OnOrderOpResult = + std::function; + ServiceBridge(OnReady const &, OnOrders const &, OnFills const &, + OnOrderOpResult const&, DynamicOrderRegistry const &, mercury::BrokerProxy &service_call_marshaller, md::SecurityOracle o); @@ -59,10 +64,11 @@ class ServiceBridge : public mercury::Actor { void block_until_ready(); // these can be called from any thread, after block_until_ready() returns - api::orderman::Response create_order(api::orderman::Create const &c); - api::orderman::Response update_order(api::orderman::Update const &c); - api::orderman::Response cancel_order(api::orderman::Cancel const &c); - api::orderman::Response crack_order(api::orderman::Crack const &c); + void create_order(uint32_t rid, api::orderman::Create const &c); + void update_order(uint32_t rid, api::orderman::Update const &c); + void cancel_order(uint32_t rid, api::orderman::Cancel const &c); + void detach_order(uint32_t rid, api::orderman::Detach const &c); + void update_admin_data(std::shared_ptr const &admin); @@ -76,6 +82,7 @@ class ServiceBridge : public mercury::Actor { void on(mercury::Update const &); void on(mercury::Update const &); void on(mercury::Update const &); + void on(mercury::Update const &); }; } // namespace orderman diff --git a/src/lib/orderman/actors/order_manager/ChildOrder.h b/src/lib/orderman/actors/order_manager/ChildOrder.h index 5e6c36d2a..29d55ed1a 100644 --- a/src/lib/orderman/actors/order_manager/ChildOrder.h +++ b/src/lib/orderman/actors/order_manager/ChildOrder.h @@ -11,70 +11,171 @@ namespace orderman { class ChildOrder { public: ChildOrder() - : _order(nullptr), _parent_order_services(nullptr), + : _child_order(nullptr), _parent_order_services(nullptr), _child_order_services(nullptr), _active(false) {} - ChildOrder(Order &o, OrderServices &services) - : _order(&o), _parent_order_services(&services), - _child_order_services(nullptr), _active(false) {} + ChildOrder(Order &child, OrderServices &parent_services) + : _child_order(&child), _parent_order_services(&parent_services), + _child_order_services(), _active(false) {} + + // This is used in attach, where the child order is already activated + // and ready to go. + ChildOrder(OrderServices &child_services, OrderServices &parent_services) + : _child_order(child_services._owner), + _parent_order_services(&parent_services), + _child_order_services(&child_services), _active(true) {} ChildOrder(ChildOrder &&src) { operator=(std::move(src)); } + ChildOrder(ChildOrder const &src) { operator=(src); } + + ChildOrder(api::orderman::OrderDefinition const &def, + OrderServices &parent_services) + : _child_order(&parent_services.make_child(def)), + _parent_order_services(&parent_services), _child_order_services(), + _active(false) {} ChildOrder &operator=(ChildOrder &&src) { - _order = src._order; + _child_order = src._child_order; _parent_order_services = src._parent_order_services; _child_order_services = src._child_order_services; _active = src._active; - src._order = nullptr; + src._child_order = nullptr; src._parent_order_services = nullptr; src._child_order_services = nullptr; src._active = false; return *this; } + ChildOrder &operator=(ChildOrder const &src) { + _child_order = src._child_order; + _parent_order_services = src._parent_order_services; + _child_order_services = src._child_order_services; + _active = src._active; + return *this; + } + + bool empty() const { + return _child_order == nullptr; + } OrderKey key() const { - bts_assert_d(_order); - return _order->key(); + bts_assert_d(_child_order); + return _child_order->key(); } bool is_active() const { return _active; } - void warm_up_activate() { bts_assert(!_active); - _parent_order_services->warm_up_activate_child(*_order); + _parent_order_services->warm_up_activate_child(*_child_order); } - - void activate(Price p, Quantity q, trace::CorID const &trace = trace::CorID()) { - bts_assert(_order); + + // Activate + void activate(Price p, Quantity q) { + bts_assert(_child_order); bts_assert(!_active); - _child_order_services = - &_parent_order_services->activate_child(*_order, p, q, trace); + _parent_order_services->activate_child(*_child_order, p, q); + _child_order_services = _child_order->_services.get(); _active = true; } - void update(Price p, Quantity q, trace::CorID const &trace = trace::CorID()) { - bts_assert(_order); + template + void activate(Price p, Quantity q, CB const &on_activate_result) { + bts_assert(_child_order); + bts_assert(!_active); + + auto on_activate_result_wrapper = [this, on_activate_result]( + OrderOpResult const &r) { + _parent_order_services->call_with_reentrancy_guard( + [r, on_activate_result](auto const &) { on_activate_result(r); }); + }; + + _parent_order_services->activate_child(*_child_order, p, q, + on_activate_result_wrapper); + _child_order_services = _child_order->_services.get(); + _active = true; + } + // End Activate + + // Mark detached + void mark_detached_from_parent() { + bts_assert(_child_order); bts_assert(_active); - _child_order_services->update(p, q, trace); + _child_order_services->mark_detached_from_parent(); } - void crack(trace::CorID const &trace = trace::CorID()) { - bts_assert(_order); + // Update + void update(Price p, Quantity q) { + bts_assert(_child_order); bts_assert(_active); - _child_order_services->crack(trace); + _child_order_services->update(p, q); } - void cancel(trace::CorID const &trace = trace::CorID()) { - bts_assert(_order); + + template void update(Price p, Quantity q, CB const &on_result) { + bts_assert(_child_order); bts_assert(_active); - _child_order_services->cancel(trace); + + auto on_result_w = [this, on_result](OrderOpResult const &r) { + _parent_order_services->call_with_reentrancy_guard( + [r, on_result](auto const &) { on_result(r); }); + }; + _child_order_services->update(p, q, on_result_w); } + void update(api::orderman::Update const &update) { + bts_assert(_child_order); + bts_assert(_active); + _child_order_services->update(update); + } + template + void update(api::orderman::Update const &update, CB const &on_result) { + bts_assert(_child_order); + bts_assert(_active); + auto on_result_w = [this, on_result](OrderOpResult const &r) { + _parent_order_services->call_with_reentrancy_guard( + [r, on_result](auto const &) { on_result(r); }); + }; + _child_order_services->update(update, on_result_w); + } + // End Update + + // Detach + void detach() { + bts_assert(_child_order); + bts_assert(_active); + _child_order_services->detach(); + } + template void detach(CB const &on_result) { + bts_assert(_child_order); + bts_assert(_active); + auto on_result_w = [this, on_result](OrderOpResult const &r) { + _parent_order_services->call_with_reentrancy_guard( + [r, on_result](auto const &) { on_result(r); }); + }; + _child_order_services->detach(on_result); + } + // End Detach + + // Cancel + void cancel() { + bts_assert(_child_order); + bts_assert(_active); + _child_order_services->cancel(); + } + template void cancel(CB const &on_result) { + bts_assert(_child_order); + bts_assert(_active); + auto on_result_w = [this, on_result](OrderOpResult const &r) { + _parent_order_services->call_with_reentrancy_guard( + [r, on_result](auto const &) { on_result(r); }); + }; + _child_order_services->cancel(on_result_w); + } + // End Cancel private: friend class OrderBuilder; - Order *_order; + Order *_child_order; OrderServices *_parent_order_services; OrderServices *_child_order_services; bool _active; diff --git a/src/lib/orderman/actors/order_manager/OrderBuilder.h b/src/lib/orderman/actors/order_manager/OrderBuilder.h index 1a446d59e..deb45213e 100644 --- a/src/lib/orderman/actors/order_manager/OrderBuilder.h +++ b/src/lib/orderman/actors/order_manager/OrderBuilder.h @@ -5,7 +5,6 @@ #include "lib/orderman/actors/order_manager/ChildOrder.h" #include "lib/orderman/actors/order_manager/OrderServices.h" #include "lib/orderman/orderman_utils/orderman_common.h" -#include "lib/orderman/orders/PreActivationOrderServices.h" #include #include @@ -13,40 +12,51 @@ namespace bts { namespace orderman { class OrderBuilder { - public: +public: OrderBuilder() - : _parent_key(null_order_key()), _definition(), _reserve_sz(0), - _order_stash(), _builder_id(), _order_services(nullptr) {} + : _parent_key(null_order_key()), _definition(), _reserve_sz(0), + _order_stash(), _builder_id(), _order_services(nullptr) {} OrderBuilder(OrderBuilder &&src) { operator=(std::move(src)); } OrderBuilder(OrderKey parent_key, api::orderman::OrderDefinition const &def, - PreActivationOrderServices const &srv, size_t reserve_sz = 1) - : _parent_key(parent_key), _definition(def), _reserve_sz(reserve_sz), - _order_stash(), _builder_id(++_current_builder_id), - _order_services(nullptr) + IOrderFactory &factory, size_t reserve_sz = 1) + : _parent_key(parent_key), _definition(def), _reserve_sz(reserve_sz), + _order_stash(), _builder_id(++_current_builder_id), + _order_services(nullptr) { bts_assert(parent_key != null_order_key()); while (_order_stash.size() != reserve_sz) - _order_stash.push_back( - &srv.order_factory.create(parent_key, _definition)); + _order_stash.push_back(&factory.create(parent_key, _definition)); } + OrderBuilder(OrderKey parent_key, api::orderman::OrderDefinition const &def, + size_t reserve_sz = 1) + : _parent_key(parent_key), _definition(def), _reserve_sz(reserve_sz), + _order_stash(), _builder_id(++_current_builder_id), + _order_services(nullptr) + + { + bts_assert(parent_key != null_order_key()); + } + + bool is_activated() { return _order_services != nullptr; } + void activate(OrderServices &order_services) { bts_assert(!_order_services); _order_services = &order_services; _order_services->subscribe_to_order_creation_reply( - _builder_id, [this](auto const &order_ev) { - _order_stash.insert(_order_stash.end(), order_ev.orders.begin(), - order_ev.orders.end()); - }); + _builder_id, [this](auto const &order_ev) { + _order_stash.insert(_order_stash.end(), order_ev.orders.begin(), + order_ev.orders.end()); + }); } ChildOrder build() { bts_assert_msg( - _order_services, - "OrderBuilder::activate() must be called before orders can be built"); + _order_services, + "OrderBuilder::activate() must be called before orders can be built"); ChildOrder result; if (_order_stash.size()) { @@ -59,8 +69,8 @@ class OrderBuilder { "This will have an impact on performance", _parent_key); result = ChildOrder( - _order_services->order_factory().create(_parent_key, _definition), - *_order_services); + _order_services->order_factory().create(_parent_key, _definition), + *_order_services); } if (_reserve_sz > _order_stash.size()) { auto need = _reserve_sz - _order_stash.size(); @@ -75,9 +85,14 @@ class OrderBuilder { return *this; } - private: + OrderServices &services() { + bts_assert(_order_services != nullptr); + return *_order_services; + } + +private: void move_here(OrderBuilder &src) { - bts_assert(!_order_services); + _order_services = src._order_services; _parent_key = src._parent_key; _definition = src._definition; _reserve_sz = src._reserve_sz; diff --git a/src/lib/orderman/actors/order_manager/OrderManager.cpp b/src/lib/orderman/actors/order_manager/OrderManager.cpp index 37f03c800..e393c90f4 100644 --- a/src/lib/orderman/actors/order_manager/OrderManager.cpp +++ b/src/lib/orderman/actors/order_manager/OrderManager.cpp @@ -5,10 +5,10 @@ #include "lib/orderman/actors/order_manager/OrderServices.h" #include "lib/orderman/actors/order_manager/OrderServicesData.h" #include "lib/orderman/events/NewAdminDataEvent.h" +#include "lib/orderman/events/NewSecuritiesEvent.h" #include "lib/orderman/events/OrderManagerReadyEvent.h" #include "lib/orderman/events/StoredFillEvent.h" #include "lib/orderman/events/StoredOrderEvent.h" -#include "lib/orderman/events/NewSecuritiesEvent.h" #include "lib/orderman/order_factory/OrderFactory.h" #include "lib/orderman/orders/Order.h" #include "lib/orderman/securities/ISecurityDB.h" @@ -32,8 +32,9 @@ enum class OrderManager::State { }; struct OrderManager::PImpl { - PImpl(OrderManager &owner, DynamicOrderRegistry const &b, trace::PerfLog &l, md::SecurityOracle o) - : state(State::WAIT_ADMIN), services_data(owner, b, l, o) {} + PImpl(OrderManager &owner, DynamicOrderRegistry const &b, trace::PerfLog &l, + md::SecurityOracle o) + : state(State::WAIT_ADMIN), services_data(owner, b, l, o) {} State state; std::unordered_map orders; @@ -43,7 +44,8 @@ struct OrderManager::PImpl { mercury::Stream pub_ready; }; -OrderManager::OrderManager(DynamicOrderRegistry const &b, trace::PerfLog &l, md::SecurityOracle o) +OrderManager::OrderManager(DynamicOrderRegistry const &b, trace::PerfLog &l, + md::SecurityOracle o) : me(new PImpl(*this, b, l, o)) {} OrderManager::~OrderManager() {} @@ -76,7 +78,7 @@ void OrderManager::on_securities( const mercury::Update &update) { // forward to execution gateways - for (auto &osd : me->services_data.sessions) + for (auto &osd : me->services_data.sessions) osd->gw.on_securities(update); if (update.events) { @@ -147,14 +149,15 @@ void OrderManager::on_order_recovery( for (auto const &ev : *(update.events)) { auto &order = me->services_data.order_factory.recover(ev.order_record); + auto const &def = order.def(); + publish_order_def_update(OrderKey(ev.key()), def); order.init_order_services(me->services_data); auto r = me->orders.emplace(order.key(), &order); bts_assert(r.second); auto const &ostate = ev.order_record.state(); order.on_activate(Price(ostate.price()), - Quantity(ostate.quantity()), *order._services, - trace::CorID()); + Quantity(ostate.quantity()), *order._services); } // signal that we are ready @@ -184,11 +187,13 @@ void OrderManager::on_execution_report( auto order = &me->services_data.order_factory.recreate_from_exe_report( *report.data); + auto const &def = order->def(); + publish_order_def_update(OrderKey(k), def); order->init_order_services(me->services_data); auto r = me->orders.emplace(order->key(), order); bts_assert(r.second); order->on_activate(report.data->price, report.data->quantity, - *order->_services, trace::CorID()); + *order->_services); } } } @@ -198,10 +203,20 @@ void OrderManager::on_activate_order( if (m.events) for (auto const &ev : *m.events) { auto order = ev.order; + + auto const &def = order->def(); + publish_order_def_update(order->key(), def); order->init_order_services(me->services_data); auto r = me->orders.emplace(order->key(), order); bts_assert(r.second); - order->_services->activate(ev.price, ev.quantity, ev.trace); + + auto rid = ev.req_id; + auto k = order->key(); + auto on_response = [this, rid, k](auto const &order_op_result) { + publish(me->services_data.report_order_op_result_pub, k, rid, + order_op_result); + }; + order->_services->activate(ev.price, ev.quantity, on_response); } } @@ -210,9 +225,24 @@ void OrderManager::on_update_order(const mercury::Update &m) { for (auto const &ev : *m.events) { auto k = ev.key(); auto it = me->orders.find(k); - if (it != me->orders.end()) - it->second->_services->update(ev.price, ev.quantity, ev.trace); - else { + auto rid = ev.req_id(); + + auto on_order_op_result = [this, rid, k](auto const &order_op_result) { + publish(me->services_data.report_order_op_result_pub, k, rid, + order_op_result); + }; + + if (it != me->orders.end()) { + if (ev.is_full_update()) + it->second->_services->update(ev.full_update(), + on_order_op_result); + else + it->second->_services->update(Price(ev.price()), + Quantity(ev.quantity()), + on_order_op_result); + } else { + on_order_op_result(OrderOpResult{ + api::orderman::ORDER_ERROR_UNKNOWN_ORDER, "Unknown order"}); LOG(OrderMan, Error, "Received an update request for an unknown order {}. " "This should not happen and likely indicates a serious bug. ", @@ -226,9 +256,18 @@ void OrderManager::on_cancel_order(const mercury::Update &m) { for (auto const &ev : *m.events) { auto k = ev.key(); auto it = me->orders.find(k); + auto rid = ev.req_id; + + auto on_order_op_result = [this, rid, k](auto const &order_op_result) { + publish(me->services_data.report_order_op_result_pub, k, rid, + order_op_result); + }; + if (it != me->orders.end()) - it->second->_services->cancel(ev.trace); + it->second->_services->cancel(on_order_op_result); else { + on_order_op_result(OrderOpResult{ + api::orderman::ORDER_ERROR_UNKNOWN_ORDER, "Unknown order"}); LOG(OrderMan, Error, "Received a cancel request for an unknown order {}. " "This should not happen and likely indicates a serious bug. ", @@ -237,16 +276,26 @@ void OrderManager::on_cancel_order(const mercury::Update &m) { } } -void OrderManager::on_crack_order(const mercury::Update &m) { +void OrderManager::on_detach_order(const mercury::Update &m) { if (m.events) for (auto const &ev : *m.events) { auto k = ev.key(); auto it = me->orders.find(k); + auto rid = ev.req_id; + + auto on_order_op_result = [this, rid, k](auto const &order_op_result) { + publish(me->services_data.report_order_op_result_pub, k, rid, + order_op_result); + }; + if (it != me->orders.end()) - it->second->_services->crack(ev.trace); + it->second->_services->detach(on_order_op_result); else { + on_order_op_result(OrderOpResult{ + api::orderman::ORDER_ERROR_UNKNOWN_ORDER, "Unknown Order"}); + LOG(OrderMan, Error, - "Received a crack request for an unknown order {}. " + "Received a detach request for an unknown order {}. " "This should not happen and likely indicates a serious bug. ", ev.key().value()); } @@ -262,14 +311,22 @@ void OrderManager::on_gateway_state( } } -OrderServices &OrderManager::activate_child(OrderServices &parent, Order &order, - Price p, Quantity q, - trace::CorID const &trace) { - order.init_order_services(me->services_data, parent); - auto r = me->orders.emplace(order.key(), &order); +void OrderManager::add_child_order(OrderServices &parent, Order &child) { + auto const &def = child.def(); + publish_order_def_update(child.key(), def); + + child.init_order_services(me->services_data, parent); + auto r = me->orders.emplace(child.key(), &child); bts_assert(r.second); - order.on_activate(p, q, *order._services, trace); - return *order._services; +} + +Order *OrderManager::lookup_order(OrderKey k) { + auto it = me->orders.find(k); + if (it == me->orders.end()) { + return nullptr; + } else { + return it->second; + } } void OrderManager::on_new_fix_buffer( @@ -302,6 +359,7 @@ OrderManager::free_buffers(std::string const &session_name) { void OrderManager::init_order_services() { auto& log = me->services_data.log; + for (auto &s : me->services_data.sessions) { auto gw_name = GatewayName(s->session); @@ -343,35 +401,41 @@ void OrderManager::init_order_services() { // can impose more fine-grained and light weight filtering on // top of those topic subscriptions through the // ContentSubscription helper class. + + // we intercept report event updates so that we can set the current + // trace object + std::function on_exe_r = + [this](NewExecutionReportEvent const &ev) { + me->services_data.cor_id = ev.trace; + }; s->exe_report_subs = std::make_unique>( - *this, gw_name,log); + *this, gw_name, on_exe_r,log); s->cancel_reject_subs = std::make_unique>(*this, - gw_name, - log); + gw_name,log); s->gateway_status_subs = std::make_unique< - ContentSubscription>(*this, gw_name,log); + ContentSubscription>(*this, gw_name,log); // publishers for execution reports, gateway status and cancel // reject evets auto s_ptr = s.get(); s->exe_report_pub = make_stream(gw_name); - s->gw.on_exe_report() = [s_ptr,this] (auto const &er, auto const &t) { - publish(s_ptr->exe_report_pub, &er,t); + s->gw.on_exe_report() = [s_ptr, this](auto const &er, auto const &t) { + publish(s_ptr->exe_report_pub, &er, t); }; s->gw_status_change_pub = make_stream(gw_name); - s->gw.on_gw_status_change() = [s_ptr,this,gw_name] (bool b) { - publish(s_ptr->gw_status_change_pub, gw_name,b); + s->gw.on_gw_status_change() = [s_ptr, this, gw_name](bool b) { + publish(s_ptr->gw_status_change_pub, gw_name, b); }; s->cancel_reject_pub = make_stream(gw_name); - s->gw.on_cancel_reject() = [s_ptr,this] (auto const &k,auto const&msg) { - publish(s_ptr->cancel_reject_pub, k,msg); + s->gw.on_cancel_reject() = [s_ptr, this](auto const &k, auto const &msg) { + publish(s_ptr->cancel_reject_pub, k, msg); }; // handlers are ready so we can start processing fix events s->gw.start(); - + reload_fix_buffer(*s); } @@ -382,8 +446,8 @@ void OrderManager::init_order_services() { [this](auto const &ev) { this->on_update_order(ev); }); subscribe( [this](auto const &ev) { this->on_cancel_order(ev); }); - subscribe( - [this](auto const &ev) { this->on_crack_order(ev); }); + subscribe( + [this](auto const &ev) { this->on_detach_order(ev); }); // Clock subscribe( @@ -402,40 +466,55 @@ void OrderManager::init_order_services() { me->services_data.settlement_request_pub = make_stream(); me->services_data.report_order_state_pub = - make_stream(); + make_stream(); + me->services_data.report_order_definition_pub = + make_stream(); me->pub_ready = make_stream(); + me->services_data.report_order_op_result_pub = + make_stream(); // md subs are peculiar in that we try to make them on demand, so // we publish an event announcing the subscription std::function on_md_sub = [this](SecurityKey k) { - publish(me->services_data.md_request_pub, k,MDRequestType::BOOK); + publish(me->services_data.md_request_pub, k, MDRequestType::BOOK); }; std::function on_ticker_sub = [this](SecurityKey k) { - publish(me->services_data.md_request_pub, k,MDRequestType::TICKER); + publish(me->services_data.md_request_pub, k, MDRequestType::TICKER); }; std::function on_settlement_sub = [this](SecurityKey k) { publish(me->services_data.settlement_request_pub, k); }; + + // We need to intercept book updates before they are disseminated + // to orders so we can set the current trace object, which will be + // used to correlate activities triggered by the same market data + // event + std::function on_book_update = + [this](BookUpdateEvent const &ev) { + me->services_data.cor_id = ev.trace; + }; me->services_data.md_subs = - std::make_unique>(*this, on_md_sub,log); + std::make_unique>(*this, on_md_sub, + on_book_update,log); me->services_data.ticker_subs = - std::make_unique>(*this, on_ticker_sub,log); + std::make_unique>(*this, + on_ticker_sub,log); me->services_data.settlement_subs = std::make_unique>( - *this, on_settlement_sub,log); - + *this, on_settlement_sub,log); me->services_data.time_subs = - std::make_unique>(*this,log); + std::make_unique>(*this,log); me->services_data.order_creation_subs = - std::make_unique>(*this,log); + std::make_unique>(*this,log); } void OrderManager::after_event() { if (me->state == State::READY) { + me->services_data.cor_id = trace::CorID{}; for (auto &osd : me->services_data.sessions) { auto &fix_stream = osd->current_buffer->first_stream(); if (fix_stream.n_msgs()) { - auto scoped_do_work = trace::log_scope(me->services_data.log, {}, "OrderManager::after_event", 0, osd->session.c_str()); + auto scoped_do_work = trace::log_scope(me->services_data.log, {}, "OrderManager::after_event"); fix_stream.close(); osd->gw.send_fix(osd->current_buffer, osd->current_trace); reload_fix_buffer(*osd); @@ -457,11 +536,17 @@ void OrderManager::reload_fix_buffer(SessionServicesData &osd) { } } -void OrderManager::on_poll(trace::PerfLog& log) { - auto scoped_do_work = trace::log_scope(log, {}, "OrderManager::dispatch_incoming_fix_messages", utils::TimeStamp::Interval::from_microseconds(2)); +void OrderManager::on_poll(trace::PerfLog&log) { + auto scoped_do_work = trace::log_scope(log, {}, "OrderManager::dispatch_incoming_fix_messages"); for (auto &osd : me->services_data.sessions) osd->gw.dispatch_incoming_fix_messages(); } +void OrderManager::publish_order_def_update( + OrderKey k, + std::shared_ptr const &def) { + publish(me->services_data.report_order_definition_pub, k, def); +} + } // namespace orderman } // namespace bts diff --git a/src/lib/orderman/actors/order_manager/OrderManager.h b/src/lib/orderman/actors/order_manager/OrderManager.h index 8b2d6f20e..bc702c5a5 100644 --- a/src/lib/orderman/actors/order_manager/OrderManager.h +++ b/src/lib/orderman/actors/order_manager/OrderManager.h @@ -7,7 +7,7 @@ #include "lib/md/SecurityOracle.h" #include "lib/orderman/events/ActivateOrderEvent.h" #include "lib/orderman/events/CancelOrderEvent.h" -#include "lib/orderman/events/CrackOrderEvent.h" +#include "lib/orderman/events/DetachOrderEvent.h" #include "lib/orderman/events/UpdateOrderEvent.h" #include "lib/utils/inplace_function.h" @@ -15,7 +15,9 @@ // fwd namespace bts { -namespace trace {class PerfLog;} +namespace trace { +class PerfLog; +} namespace mercury { class TimerEvent; } @@ -25,7 +27,7 @@ class NewExecutionReportEvent; class ActivateOrderEvent; class UpdateOrderEvent; class CancelOrderEvent; -class CrackOrderEvent; +class DetachOrderEvent; class StoredOrderEvent; class StoredFillEvent; class OrderServices; @@ -46,22 +48,22 @@ namespace orderman { // - an order factory (OrderFactory) // - a security database (SecurityDB) // - a limiter which enforces risk limits (Limiter) +// - a set of execution gateways // - subscriptions to interesting events such as: -// - execution gateway messages (execution reports, rejects, etc) // - market data book updates -// - security creation events +// - security discuovery events // - timer updates -// - order state changes // // Additionally handles order maintenance events: // - create // - cancel -// - crack +// - detach // - update class OrderManager : public mercury::Actor, public mercury::IPollableActor { public: OrderManager(DynamicOrderRegistry const &dyn_order_builder, trace::PerfLog &, md::SecurityOracle); + ~OrderManager(); void init() override; @@ -76,7 +78,7 @@ class OrderManager : public mercury::Actor, public mercury::IPollableActor { void on_activate_order(const mercury::Update &); void on_update_order(const mercury::Update &); void on_cancel_order(const mercury::Update &); - void on_crack_order(const mercury::Update &); + void on_detach_order(const mercury::Update &); void on_new_fix_buffer(const mercury::Update &); void on_gateway_state(const mercury::Update &); void on_timer(const mercury::Update &); @@ -89,8 +91,13 @@ class OrderManager : public mercury::Actor, public mercury::IPollableActor { void reload_fix_buffer(SessionServicesData &dt); void after_event() override; - OrderServices &activate_child(OrderServices &parent, Order &, Price, - Quantity, trace::CorID const &); + + void add_child_order(OrderServices &parent, Order &child); + Order* lookup_order(OrderKey k); + + void publish_order_def_update( + OrderKey k, + std::shared_ptr const &def); std::vector &free_buffers(std::string const &); enum class State; diff --git a/src/lib/orderman/actors/order_manager/OrderServices.cpp b/src/lib/orderman/actors/order_manager/OrderServices.cpp new file mode 100644 index 000000000..a6ed180f3 --- /dev/null +++ b/src/lib/orderman/actors/order_manager/OrderServices.cpp @@ -0,0 +1,235 @@ +#include "OrderServices.h" +#include "lib/orderman/actors/order_manager/ChildOrder.h" + +namespace bts { +namespace orderman { + +using namespace api::orderman; + +std::function OrderServices::ignore = + [](auto const &) {}; + +OrderServices::OrderServices(Order &owner) + : _busy(false), _pending_calls(), _owner(&owner), _data(), _parent(nullptr), + _child_update_cb([](auto const &) {}), _book_updates(), _ticker_updates(), + _settlement_updates(), _time_change(), _sessions() { + _last_state_update.key = null_order_key(); +} + +void OrderServices::init(OrderServicesData &data, OrderServices &parent) { + _parent = &parent; + init(data); +} + +bool OrderServices::has_reported_state() const { + return _last_state_update.key != null_order_key(); +} + +void OrderServices::init(OrderServicesData &data) { + _data = &data; + _book_updates.init(*data.md_subs); + _ticker_updates.init(*data.ticker_subs); + _settlement_updates.init(*data.settlement_subs); + _time_change.init(*data.time_subs); + if (_sessions.empty()) + for (auto &sd : data.sessions) + _sessions.emplace_back(*sd); + _create_order_reply.init(*data.order_creation_subs); +} + +void OrderServices::report_definition( + const api::orderman::OrderDefinition &def) { + _owner->set_def(def); + _data->owner.publish(_data->report_order_definition_pub, _owner->key(), + _owner->def()); + + // Force re-publication of state when we get a new definition + // (provided we previously reported a state, so that we do not end + // up publishing an empty state object) + if (has_reported_state()) { + auto st = _last_state_update.rebuild_state(); + report_state(st); + } +} + +void OrderServices::report_state(const api::orderman::OrderState &state) { + bts_assert(state.status() != api::orderman::ORDER_STATUS_INACTIVE); + + _owner->set_status(state.status()); + _last_state_update.init(_owner->key(), _owner->parent_key(), _owner->def(), + state); + _data->owner.publish(_data->report_order_state_pub, _last_state_update); + if (_parent) + _parent->on_child_update(_last_state_update); + + if (orderman::in_terminal_state(state.status())) { + LOG(OrderMan, Info, + "Order {} transitioned to a terminal state. Canceling all " + "subscriptions", + _owner->key().value()); + unsubscribe_from_child_updates(); + _book_updates.unsub_all(); + _ticker_updates.unsub_all(); + _settlement_updates.unsub_all(); + _time_change.unsub_all(); + _create_order_reply.unsub_all(); + } +} + +SessionServices & +OrderServices::get_session_services(std::string const &for_session) { + for (auto &s : _sessions) + if (s.session_name() == for_session) + return s; + bts_assert(false); +} + +void OrderServices::unsubscribe_from_order_creation_reply( + CreateOrderReplySubID sid) { + _create_order_reply.unsub(sid); +} + +void OrderServices::send_order_create_req( + size_t builder_id, OrderKey pk, api::orderman::OrderDefinition const &def, + size_t n_orders) { + _data->owner.publish(_data->create_order_req_pub, builder_id, pk, def, + n_orders); +} + +void OrderServices::mark_detached_from_parent() { + call_with_reentrancy_guard([this](OrderServices &self) { + self._parent = nullptr; + self._owner->set_parent_key(null_order_key()); + if (has_reported_state()) { + self._last_state_update.parent_key = null_order_key(); + self._data->owner.publish(self._data->report_order_state_pub, + self._last_state_update); + } + }); +} + +// Called by user code when attempting to attach to an existing order +void OrderServices::attach(OrderKey child_key, AttachCallback const &cb) { + + // wrap the user provided callback so we avoid reentrancy issues. + auto protected_cb = + AttachCallback([cb, this](OrderOpResult r, ChildOrder const &child, + OrderDefinition const &child_def, + OrderState const &child_state) { + call_with_reentrancy_guard( + [cb, r, child, child_def, child_state](auto const &) { + cb(r, child, child_def, child_state); + }); + }); + + // lookup the order we are supposed to attach to + auto child_order = _data->owner.lookup_order(child_key); + + // if we found a matching order, try to attach to it, passing the + // return CB so that the child order on_attach call can report on + // the attachment success or failure + if (child_order) { + child_order->_services->on_attach(*this, protected_cb); + } else { + // if we cannot find a matching child then we abort the + // attachment attempt + protected_cb({ORDER_ERROR_UNKNOWN_ORDER, "Unknown child order"}, {}, {}, + {}); + } +} + +// Called by parent order to try to attach to this order +void OrderServices::on_attach(OrderServices &new_parent, + AttachCallback const &cb) { + + call_with_reentrancy_guard([cb, &new_parent](OrderServices &self) { + // Make sure we can be attached to + auto check_result = self.check_is_attachable(); + if (check_result.fail()) { + cb(check_result, {}, {}, {}); + return; + } + + // Set my new parent information + self._parent = &new_parent; + self._owner->set_parent_key(new_parent._owner->key()); + + // Report our state again to make sure the new parent key is + // seen by all + self._last_state_update.parent_key = new_parent._owner->key(); + self._data->owner.publish(self._data->report_order_state_pub, + self._last_state_update); + + // Now create the child order that will represent us in the new + // parent + ChildOrder me_as_child{self, *self._parent}; + + // Now recover the state and definition and call on_attached() + // at this point this must work because orders cannot refuse attachments + cb({}, me_as_child, *self._owner->def(), + self._last_state_update.rebuild_state()); + + self._owner->on_attached(*new_parent._owner->def()); + }); +} + +OrderRouter::RouteQueryResult +OrderServices::route_order(UserID user_id, AccountID account_id, + api::Security const &sec) { + return _data->order_router.get_routing_record(user_id, account_id, sec); +} + +OrderOpResult OrderServices::check_is_attachable() { + + using namespace api::orderman; + + // It this order working? + switch (_owner->status()) { + case ORDER_STATUS_REJECTED_BY_SPARK: + case ORDER_STATUS_COMPLETED: + case ORDER_STATUS_CANCELED: + case ORDER_STATUS_DISCONNECTED: + case ORDER_STATUS_ERROR: + case ORDER_STATUS_PENDING_WORKING: + return OrderOpResult{ + ORDER_ERROR_INVALID_OP, + "Cannot attach to an order that is terminated or disconnected"}; + case ORDER_STATUS_WORKING: + break; + case ORDER_STATUS_INACTIVE: + case OrderStatus_INT_MIN_SENTINEL_DO_NOT_USE_: + case OrderStatus_INT_MAX_SENTINEL_DO_NOT_USE_: + bts_assert(false); + break; + } + + // this order is in a working state, to be attachable it must also + // have either no parent or a dead parent. + if (_owner->parent_key() != null_order_key()) { + auto current_parent = _data->owner.lookup_order(_owner->parent_key()); + bts_assert(current_parent); + + switch (current_parent->status()) { + case ORDER_STATUS_PENDING_WORKING: + case ORDER_STATUS_DISCONNECTED: + case ORDER_STATUS_WORKING: + return OrderOpResult{ORDER_ERROR_INVALID_OP, + "Child order already has a working parent"}; + break; + case ORDER_STATUS_REJECTED_BY_SPARK: + case ORDER_STATUS_COMPLETED: + case ORDER_STATUS_CANCELED: + case ORDER_STATUS_ERROR: + break; + case ORDER_STATUS_INACTIVE: + case OrderStatus_INT_MIN_SENTINEL_DO_NOT_USE_: + case OrderStatus_INT_MAX_SENTINEL_DO_NOT_USE_: + bts_assert(false); + break; + } + } + return OrderOpResult{}; // all good if we reach here +} + +} // namespace orderman +} // namespace bts diff --git a/src/lib/orderman/actors/order_manager/OrderServices.h b/src/lib/orderman/actors/order_manager/OrderServices.h index 0fb55a980..322b2a7a8 100644 --- a/src/lib/orderman/actors/order_manager/OrderServices.h +++ b/src/lib/orderman/actors/order_manager/OrderServices.h @@ -5,10 +5,12 @@ #include "lib/logging/logging.h" #include "lib/orderman/actors/order_manager/OrderManager.h" #include "lib/orderman/actors/order_manager/OrderServicesData.h" +#include "lib/orderman/actors/order_manager/SessionServices.h" #include "lib/orderman/events/TickerUpdateEvent.h" #include "lib/orderman/governor/Governor.h" #include "lib/orderman/orderman_utils/EventStream.h" #include "lib/orderman/orders/Order.h" + #include "lib/tracing/PerfLog.h" #include @@ -17,119 +19,20 @@ namespace bts { namespace orderman { -class OrderServices; -class SessionServices { - friend class OrderServices; - EventStream _exe_reports; - EventStream _cancel_rejects; - EventStream _gateway_status; - SessionServicesData *_session_data; - EventStream::SubID - _gateway_status_sub; - - public: - SessionServices(SessionServices &&ss) { operator=(std::move(ss)); } - - SessionServices(SessionServices const &ss) { operator=(ss); } - - SessionServices(SessionServicesData &session_data) - : _exe_reports(*session_data.exe_report_subs), - _cancel_rejects(*session_data.cancel_reject_subs), - _gateway_status(*session_data.gateway_status_subs), - _session_data(&session_data), _gateway_status_sub() {} - - SessionServices &operator=(SessionServices &&src) { - _exe_reports = std::move(src._exe_reports); - _cancel_rejects = std::move(src._cancel_rejects); - _gateway_status = std::move(src._gateway_status); - _session_data = src._session_data; - src._session_data = nullptr; - _gateway_status_sub = src._gateway_status_sub; - return *this; - } - - SessionServices &operator=(SessionServices const &src) { - _exe_reports = src._exe_reports; - _cancel_rejects = src._cancel_rejects; - _gateway_status = src._gateway_status; - _session_data = src._session_data; - _gateway_status_sub = src._gateway_status_sub; - return *this; - } - - protected: - std::string const &session_name() const { return _session_data->session; } - - config::JetFIX::Connection const &session_cfg() const { - return _session_data->cfg; - } - - void queue_fix(jetfix::MessageTypes mt, jetfix::FIXFragment const &f, - trace::CorID const &trace) { - auto &stream = _session_data->current_buffer->first_stream(); - stream.new_msg(mt).append(f); - - if (stream.n_msgs() == 1) - _session_data->current_trace = trace; - } - - bool is_gateway_connected() const { return _session_data->gw_connected; } - Governor &governor() { return _session_data->governor; } - - // Subscriptions - using ExeReportSubID = EventStream::SubID; - using CancelRejectSubID = EventStream::SubID; - - template - ExeReportSubID subscribe_to_exe_report(OrderKey k, CB &&cb) { - return _exe_reports.sub(k, std::forward(cb)); - } - void unsubscribe_from_exe_report(ExeReportSubID sid) { - _exe_reports.unsub(sid); - } - - template - CancelRejectSubID subscribe_to_cancel_reject(OrderKey k, CB &&cb) { - return _cancel_rejects.sub(k, std::forward(cb)); - } - void unsubscribe_from_cancel_reject(CancelRejectSubID sid) { - _cancel_rejects.unsub(sid); - } - - template void subscribe_to_gateway_status(CB &&cb) { - _gateway_status_sub = _gateway_status.sub(std::forward(cb)); - } - void unsubscribe_from_gateway_status() { - _gateway_status.unsub(_gateway_status_sub); - } -}; - class OrderServices { + friend class OrderManager; + public: - OrderServices(Order &owner) - : _busy(false), _pending_calls(), _owner(&owner), _data(), - _parent(nullptr), _child_update_cb([](auto const &) {}), - _book_updates(), _ticker_updates(), _settlement_updates(), - _time_change(), _sessions(), _create_order_reply() {} - - void init(OrderServicesData &data, OrderServices &parent) { - _parent = &parent; - init(data); - } - - void init(OrderServicesData &data) { - _data = &data; - _book_updates.init(*data.md_subs); - _ticker_updates.init(*data.ticker_subs); - _settlement_updates.init(*data.settlement_subs); - _time_change.init(*data.time_subs); - if (_sessions.empty()) - for (auto &sd : data.sessions) - _sessions.emplace_back(*sd); - _create_order_reply.init(*data.order_creation_subs); - } + OrderServices(Order &owner); + void init(OrderServicesData &, OrderServices &); + void init(OrderServicesData &); securities::ISecurityDB &sec_db() { return _data->sec_db; } + IOrderFactory &order_factory() { return _data->order_factory; } + + Order &make_child (api::orderman::OrderDefinition const&def) { + return _data->order_factory.create (_owner->key(),def); + } mercury::TimeStampStr const &get_time_str() const { return _data->last_timer_ev.ts_str; @@ -146,57 +49,33 @@ class OrderServices { Governor &governor(SessionServices &ss) { return ss.governor(); } void queue_fix(SessionServices &ss, jetfix::MessageTypes mt, - jetfix::FIXFragment const &f, trace::CorID const &trace) { - ss.queue_fix(mt, f, trace); + jetfix::FIXFragment const &f) { + ss.queue_fix(mt, f, corid()); } - void log(trace::CorID cid, const char *entry_kind, uint64_t uint64_1 = 0, + void log(const char *entry_kind, uint64_t uint64_1 = 0, const char *txt_1 = "", uint32_t uint32_1 = 0) { - _data->log.log(cid, entry_kind, uint64_1, txt_1, uint32_1); + _data->log.log(corid(), entry_kind, uint64_1, txt_1, uint32_1); } - trace::ScopedPerfLogEntry log_scope(trace::CorID cid, const char *entry_kind, + trace::ScopedPerfLogEntry log_scope(const char *entry_kind, uint64_t uint64_1 = 0, const char *txt_1 = "", uint32_t uint32_1 = 0) { - return trace::ScopedPerfLogEntry(_data->log, cid, entry_kind, uint64_1, - txt_1, uint32_1); + return trace::ScopedPerfLogEntry(_data->log, corid(), entry_kind, + uint64_1, txt_1, uint32_1); } - void report_state(const api::orderman::OrderState &state, - trace::CorID const &trace = trace::CorID()) { + void report_definition(const api::orderman::OrderDefinition &); - bts_assert(state.status() != api::orderman::ORDER_STATUS_INACTIVE); - - OrderStateUpdateEvent ev(_owner->key(), _owner->parent_key(), - _owner->definition(), state, trace); - _data->owner.publish(_data->report_order_state_pub, ev); - - if (orderman::in_terminal_state(state.status())) { - LOG(OrderMan, Info, - "Order {} transitioned to a terminal state. Canceling all " - "subscriptions", - _owner->key().value()); - unsubscribe_from_child_updates(); - _book_updates.unsub_all(); - _ticker_updates.unsub_all(); - _settlement_updates.unsub_all(); - _time_change.unsub_all(); - _create_order_reply.unsub_all(); - } - - if (_parent) - _parent->on_child_update(ev); - } + void report_state(const api::orderman::OrderState &); + OrderRouter::RouteQueryResult route_order(UserID, AccountID, + api::Security const&); + Limiter &limiter() { return _data->limiter; } - SessionServices &get_session_services(std::string const &for_session) { - for (auto &s : _sessions) - if (s.session_name() == for_session) - return s; - bts_assert(false); - } + SessionServices &get_session_services(std::string const &for_session); // Subscriptions ------------------------------ @@ -237,7 +116,8 @@ class OrderServices { // Execution Reports using ExeReportSubID = EventStream::SubID; template - ExeReportSubID subscribe_to_exe_report(SessionServices &ss, OrderKey k, CB &&cb) { + ExeReportSubID subscribe_to_exe_report(SessionServices &ss, OrderKey k, + CB &&cb) { return ss.subscribe_to_exe_report( k, [this, cb](auto const &ev) { this->on_external_event(ev, cb); }); } @@ -280,10 +160,13 @@ class OrderServices { // End Subscriptions ------------------------------ + // Caller is the future parent of an existing order, + // i.e. caller will attach to an existing order. + void attach(OrderKey attach_target, AttachCallback const &); + private: friend class OrderBuilder; - friend class OrderManager; - + template void on_external_event(EV const &ev, C const &c) { bts_assert(!_busy); @@ -297,7 +180,7 @@ class OrderServices { _busy = false; } - template void on_inter_order_call(C const &c) { + template void call_with_reentrancy_guard(C const &c) { if (_busy) _pending_calls.emplace_back(c); else { @@ -312,8 +195,6 @@ class OrderServices { } } - IOrderFactory &order_factory() { return _data->order_factory; } - using CreateOrderReplySubID = EventStream::SubID; template @@ -321,52 +202,78 @@ class OrderServices { CB &&cb) { return _create_order_reply.sub(req_id, std::forward(cb)); } - void unsubscribe_from_order_creation_reply(CreateOrderReplySubID sid) { - _create_order_reply.unsub(sid); - } - void send_order_create_req(size_t builder_id, OrderKey pk, - api::orderman::OrderDefinition const &def, - size_t n_orders) { - _data->owner.publish(_data->create_order_req_pub, builder_id, pk, def, - n_orders); - } + void unsubscribe_from_order_creation_reply(CreateOrderReplySubID); + + void send_order_create_req(size_t builder_id, OrderKey, + api::orderman::OrderDefinition const &, + size_t n_orders); friend class ChildOrder; - OrderServices &activate_child(Order &o, Price p, Quantity q, - trace::CorID const &trace) { - return _data->owner.activate_child(*this, o, p, q, trace); + // Activate this order + template + void activate(Price p, Quantity q, CB const &on_order_op = ignore) { + bts_assert(_owner->def()); + call_with_reentrancy_guard([p, q, on_order_op](OrderServices &self) { + on_order_op(self._owner->on_activate(p, q, self)); + }); } + + // Mark detached + void mark_detached_from_parent(); - void warm_up_activate_child(Order &o) { - o.warm_up_activate(*_data,*this); - } - - void activate(Price p, Quantity q, trace::CorID const &trace) { - on_inter_order_call([p, q, trace](OrderServices &self) { - self._owner->on_activate(p, q, self,trace); + // Update + void update(Price p, Quantity q, + OrderOpCallback const &on_order_op = ignore) { + call_with_reentrancy_guard([p, q, on_order_op](OrderServices &self) { + on_order_op(self._owner->on_update(p, q)); }); } - void update(Price p, Quantity q, trace::CorID const &trace) { - on_inter_order_call([p, q, trace](OrderServices &self) { - self._owner->on_update(p, q, trace); + void update(api::orderman::Update const &update, + OrderOpCallback const &on_order_op = ignore) { + call_with_reentrancy_guard([update, on_order_op](OrderServices &self) { + on_order_op(self._owner->on_update(update)); }); } - void crack(trace::CorID const &trace) { - on_inter_order_call( - [trace](OrderServices &self) { self._owner->on_crack(trace); }); - } - void cancel(trace::CorID const &trace) { - on_inter_order_call( - [trace](OrderServices &self) { self._owner->on_cancel(trace); }); + + // Detach + void detach(OrderOpCallback const &on_order_op = ignore) { + call_with_reentrancy_guard([on_order_op](OrderServices &self) { + on_order_op(self._owner->on_detach()); + }); } + + // Cancel + void cancel(OrderOpCallback const &on_order_op = ignore) { + call_with_reentrancy_guard([on_order_op](OrderServices &self) { + on_order_op(self._owner->on_cancel()); + }); + } + // Activate a child of this order + void activate_child(Order &o, Price p, Quantity q, + OrderOpCallback const &cb = ignore) { + _data->owner.add_child_order(*this, o); + o._services->activate(p, q, cb); + } + + // Notify this order that a new parent wants to attach + void on_attach(OrderServices &new_parent, AttachCallback const &); + + // Notify this order that one of its children updated void on_child_update(OrderStateUpdateEvent const &ev) { - on_inter_order_call( + call_with_reentrancy_guard( [ev](OrderServices &self) { self._child_update_cb(ev); }); } + void warm_up_activate_child(Order &o) { o.warm_up_activate(*_data, *this); } + + trace::CorID corid() { return _data->cor_id; } + + OrderOpResult check_is_attachable(); + bool has_reported_state() const; + bool _busy; boost::container::small_vector, 10> _pending_calls; @@ -374,6 +281,8 @@ class OrderServices { OrderServicesData *_data; OrderServices *_parent; std::function _child_update_cb; + static std::function ignore; + OrderStateUpdateEvent _last_state_update; EventStream _book_updates; EventStream _ticker_updates; EventStream _settlement_updates; @@ -381,6 +290,6 @@ class OrderServices { boost::container::small_vector _sessions; EventStream::SubID _time_change_sub; EventStream _create_order_reply; -}; +}; // namespace orderman } // namespace orderman } // namespace bts diff --git a/src/lib/orderman/actors/order_manager/OrderServicesData.h b/src/lib/orderman/actors/order_manager/OrderServicesData.h index 21afdbc4d..259f02397 100644 --- a/src/lib/orderman/actors/order_manager/OrderServicesData.h +++ b/src/lib/orderman/actors/order_manager/OrderServicesData.h @@ -15,7 +15,7 @@ #include "lib/orderman/events/TickerUpdateEvent.h" #include "lib/orderman/events/CancelOrderEvent.h" #include "lib/orderman/events/CancelRejectEvent.h" -#include "lib/orderman/events/CrackOrderEvent.h" +#include "lib/orderman/events/DetachOrderEvent.h" #include "lib/orderman/events/CreateFIXBufferReplyEvent.h" #include "lib/orderman/events/CreateFIXBufferRequestEvent.h" #include "lib/orderman/events/CreateOrderReplyEvent.h" @@ -23,6 +23,8 @@ #include "lib/orderman/events/GatewayStatusChangeEvent.h" #include "lib/orderman/events/MDRequestEvent.h" #include "lib/orderman/events/NewExecutionReportEvent.h" +#include "lib/orderman/events/OrderDefinitionUpdateEvent.h" +#include "lib/orderman/events/OrderOpResultEvent.h" #include "lib/orderman/events/OrderStateUpdateEvent.h" #include "lib/orderman/events/SettlementRequestEvent.h" #include "lib/orderman/events/SettlementUpdateEvent.h" @@ -45,7 +47,8 @@ struct ParentKey { }; struct SessionServicesData { - SessionServicesData(config::JetFIX::Connection const &cfg, trace::PerfLog &log) + SessionServicesData(config::JetFIX::Connection const &cfg, + trace::PerfLog &log) : session(cfg.name()), gw_connected(false), cfg(cfg), governor(cfg.max_order_msgs_per_window(), cfg.window_duration_msecs()), gw(cfg, log) {} @@ -73,7 +76,6 @@ struct SessionServicesData { class OrderServicesData { public: - OrderServicesData(OrderManager &owner, DynamicOrderRegistry const &b, trace::PerfLog &l, md::SecurityOracle); @@ -85,6 +87,7 @@ class OrderServicesData { OrderFactory order_factory; std::unique_ptr> md_subs; std::unique_ptr> ticker_subs; + trace::CorID cor_id; std::unique_ptr> settlement_subs; std::unique_ptr< @@ -98,7 +101,8 @@ class OrderServicesData { mercury::Stream md_request_pub; mercury::Stream settlement_request_pub; mercury::Stream report_order_state_pub; - + mercury::Stream report_order_definition_pub; + mercury::Stream report_order_op_result_pub; mercury::TimerEvent last_timer_ev; std::vector> sessions; diff --git a/src/lib/orderman/actors/order_manager/SessionServices.h b/src/lib/orderman/actors/order_manager/SessionServices.h new file mode 100644 index 000000000..eab64257e --- /dev/null +++ b/src/lib/orderman/actors/order_manager/SessionServices.h @@ -0,0 +1,108 @@ +#pragma once + +#include "lib/api/services/OrderService.pb.h" +#include "lib/jetfix/common/OutFIX.h" +#include "lib/logging/logging.h" +#include "lib/orderman/actors/order_manager/OrderManager.h" +#include "lib/orderman/actors/order_manager/OrderServicesData.h" +#include "lib/orderman/events/TickerUpdateEvent.h" +#include "lib/orderman/governor/Governor.h" +#include "lib/orderman/orderman_utils/EventStream.h" +#include "lib/orderman/orders/Order.h" + +#include "lib/tracing/PerfLog.h" +#include + +#include + +namespace bts { +namespace orderman { + +class OrderServices; +class SessionServices { + friend class OrderServices; + EventStream _exe_reports; + EventStream _cancel_rejects; + EventStream _gateway_status; + SessionServicesData *_session_data; + EventStream::SubID + _gateway_status_sub; + + public: + SessionServices(SessionServices &&ss) { operator=(std::move(ss)); } + + SessionServices(SessionServices const &ss) { operator=(ss); } + + SessionServices(SessionServicesData &session_data) + : _exe_reports(*session_data.exe_report_subs), + _cancel_rejects(*session_data.cancel_reject_subs), + _gateway_status(*session_data.gateway_status_subs), + _session_data(&session_data), _gateway_status_sub() {} + + SessionServices &operator=(SessionServices &&src) { + _exe_reports = std::move(src._exe_reports); + _cancel_rejects = std::move(src._cancel_rejects); + _gateway_status = std::move(src._gateway_status); + _session_data = src._session_data; + src._session_data = nullptr; + _gateway_status_sub = src._gateway_status_sub; + return *this; + } + + SessionServices &operator=(SessionServices const &src) { + _exe_reports = src._exe_reports; + _cancel_rejects = src._cancel_rejects; + _gateway_status = src._gateway_status; + _session_data = src._session_data; + _gateway_status_sub = src._gateway_status_sub; + return *this; + } + + protected: + std::string const &session_name() const { return _session_data->session; } + + config::JetFIX::Connection const &session_cfg() const { + return _session_data->cfg; + } + + void queue_fix(jetfix::MessageTypes mt, jetfix::FIXFragment const &f, + trace::CorID const &corid) { + auto &stream = _session_data->current_buffer->first_stream(); + stream.new_msg(mt).append(f); + + if (stream.n_msgs() == 1) + _session_data->current_trace = corid; + } + + bool is_gateway_connected() const { return _session_data->gw_connected; } + Governor &governor() { return _session_data->governor; } + + // Subscriptions + using ExeReportSubID = EventStream::SubID; + using CancelRejectSubID = EventStream::SubID; + + template + ExeReportSubID subscribe_to_exe_report(OrderKey k, CB &&cb) { + return _exe_reports.sub(k, std::forward(cb)); + } + void unsubscribe_from_exe_report(ExeReportSubID sid) { + _exe_reports.unsub(sid); + } + + template + CancelRejectSubID subscribe_to_cancel_reject(OrderKey k, CB &&cb) { + return _cancel_rejects.sub(k, std::forward(cb)); + } + void unsubscribe_from_cancel_reject(CancelRejectSubID sid) { + _cancel_rejects.unsub(sid); + } + + template void subscribe_to_gateway_status(CB &&cb) { + _gateway_status_sub = _gateway_status.sub(std::forward(cb)); + } + void unsubscribe_from_gateway_status() { + _gateway_status.unsub(_gateway_status_sub); + } +}; + +}} diff --git a/src/lib/orderman/core/IOrderServices.cpp b/src/lib/orderman/core/IOrderServices.cpp new file mode 100644 index 000000000..d2640c03f --- /dev/null +++ b/src/lib/orderman/core/IOrderServices.cpp @@ -0,0 +1 @@ +//#include "lib/orderman/core/IOrderServices.h" diff --git a/src/lib/orderman/core/IOrderServices.h b/src/lib/orderman/core/IOrderServices.h new file mode 100644 index 000000000..8aaad79de --- /dev/null +++ b/src/lib/orderman/core/IOrderServices.h @@ -0,0 +1,113 @@ +#pragma once + +#include "lib/api/services/OrderService.pb.h" +#include "lib/domain_model/common.h" +#include "lib/orderman/actors/order_manager/ChildOrder.h" +#include "lib/orderman/orders/OrderOpResult.h" +#include + +// fwds +namespace bts { +namespace api { +namespace orderman { +class OrderDefinition; +class CustomOrderDefinition; +class OrderState; +class Update; +class OrderRecord; +} // namespace orderman +} // namespace api +namespace mercury { +class TimerEvent; +} +namespace orderman { +class ChildOrder; +class ISecurityDB; +class IAlgoServices; +class IOrderFactory; +class BookUpdateEvent; +class TickerUpdateEvent; +class SettlementUpdateEvent; +class OrderStateUpdateEvent; +} // namespace orderman +} // namespace bts + +namespace bts { +namespace orderman { + +template +using Callback = std::function; +using OrderOpCB = Callback; +OrderOpCB ignore() { + return [](auto &) {}; +}; + +struct AttachOpResult { + OrderOpResult result; + ChildOrder child; +}; + +class AlgoOrder { + public: + virtual void on_init_new(api::orderman::OrderDefinition const &, + ISecurityDB &, IOrderFactory &) = 0; + + virtual void on_activate(Price, Quantity, IAlgoServices &, + OrderOpCB const &) = 0; + + virtual void on_update(Price, Quantity, OrderOpCB const &) = 0; + virtual void on_update(api::orderman::Update const &, + OrderOpCB const &on_result) { + on_result(OrderOpResult{api::orderman::ORDER_ERROR_INVALID_OP, + "Operation not supported"}); + } + + virtual void on_cancel(OrderOpCB const &) = 0; + virtual void on_detach(OrderOpCB const &) = 0; + virtual void on_attached(OrderKey /*new_parent*/) {}; + virtual void on_detached() {} +}; + +class IOrderServices { + public: + // reporting state and definition changes + virtual void + report_definition(const api::orderman::CustomOrderDefinition &) = 0; + virtual void report_state(const api::orderman::OrderState &) = 0; + + // Child order creation/control + virtual void + make_child_orders(api::orderman::OrderDefinition const &, size_t how_many, + Callback const &>) = 0; + virtual void activate(ChildOrder &, Price, Quantity, + OrderOpCB const & = ignore()) = 0; + virtual void update(ChildOrder &, Price, Quantity, + OrderOpCB const & = ignore()) = 0; + virtual void update(ChildOrder &, api::orderman::Update const &, + OrderOpCB const & = ignore()) = 0; + virtual void cancel(ChildOrder &, OrderOpCB const & = ignore()) = 0; + virtual void attach(OrderKey, Callback const &) = 0; + virtual void detach(ChildOrder const &, OrderOpCB const & = ignore()); + // End child control + + // Events + virtual void subscribe_to_book(SecurityKey, + Callback const &) = 0; + virtual void unsubscribe_from_book(SecurityKey) = 0; + virtual void subscribe_to_ticker(SecurityKey, + Callback const &) = 0; + virtual void unsubscribe_from_ticker(SecurityKey) = 0; + virtual void + subscribe_to_settlement(SecurityKey, + Callback const &) = 0; + virtual void unsubscribe_from_settlement(SecurityKey) = 0; + virtual void + subscribe_to_time(Callback const &) = 0; + virtual void unsubscribe_from_time() = 0; + virtual void + subscribe_to_child_updates(Callback const &) = 0; + virtual void unsubscribe_from_child_updates() = 0; + // End events +}; +} // namespace orderman +} // namespace bts diff --git a/src/lib/orderman/doc/attach_detach.org b/src/lib/orderman/doc/attach_detach.org new file mode 100644 index 000000000..6e11ea3f3 --- /dev/null +++ b/src/lib/orderman/doc/attach_detach.org @@ -0,0 +1,65 @@ +** Attach/Detach semantics +*** Semantics +- An order base definition can include a list of running orders to attach + to +- Each custom definition can have parameters that allow configuration + of the specific order type with respect to the attachment + list. Obvious configuration alternatives are: + - Attach to each of the listed orders directly or + - Forward attachment list to children +- Only orders with no parent or parents in a terminal state can be + attached to +- a detach(order_key) message can be sent to any order, even if that + order was not started through attachment to an existing order. the + expected semantics is for the order in question to stop managing the + child order and transition to completed. + +*** API +- IOrderServices: + - attach_to_order(ok, std::function + on_attach_complete); + - detach(ChildOrder) +- Order + - on_detach(order_key) + - on_attached(); + - on_detached(); +message OrderDefinition { + CTICode cti_code = 9; + l CUSTOMERORFIRM customer_or_firm = 10; + OrderSubType sub_type = 12; ++ repeated uint32 attach_to_order = 13; + CustomOrderDefinition custom_def = 11; +} +* Order fields +| Field | Group | Muttable | on_attach | +|------------------------+--------------+----------+-------------| +| security_key | standard def | N | from child | +| side | | N | from child | +| user | | N | from parent | +| user_id | | Y | from parent | +| account | | Y | from parent | +| account_id | | Y | from parent | +| time_in_force | | N | from child | +| manual_order_indicator | | Y | from parent | +| cti_code | | N | from child | +| customer_or_firm | | N | from child | +| sub_type | | N | | +| attach_order | | N | | +|------------------------+--------------+----------+-------------| +| custom_def | custom_def | Y | from child | +| | | | | +|------------------------+--------------+----------+-------------| +| key | order_record | N | | +| parent_key | | Y | from parent | +|------------------------+--------------+----------+-------------| +| status | order_state | Y | | +| price | | Y | | +| quantity | | Y | | +| filled_quantity | | Y | | +| last_price | | Y | | +| avg_price | | Y | | +| last_msg | | Y | | +| created | | Y | | +| last_change | | Y | | +| custom_state | custom_state | Y | | + diff --git a/src/lib/orderman/doc/order_man_notes.org b/src/lib/orderman/doc/order_man_notes.org index ac97e466f..abd25b529 100644 --- a/src/lib/orderman/doc/order_man_notes.org +++ b/src/lib/orderman/doc/order_man_notes.org @@ -1,3 +1,12 @@ +* Iceberg specification +| | paused | synched | pending_w | in_flight_update | +| pending_w | X | | | | +| working | X | | | | +| completed | O | | | | +| canceled | canceled | | | | +| error | X | | | | +| disconnected | | | | | +| rejected by spark | X | | | | * References ** To Exchange - [[https://www.cmegroup.com/confluence/display/EPICSANDBOX/New+Order][NewOrderSingle]] @@ -394,23 +403,15 @@ ExecRefID * Open Issues - Re-Connection is done on the fast thread, slowing everything down -- Consider multiple gateways for MSGW -- Need to quiesce orders when they are done - Need to make sure there are no duplicate order state update events -- We need to decouple OM from fix gateway, so that we can have a slow - OM and a fast OM going against the same gateway - Once we have multiple OM's we will need to guarantee that they can see each others order, which means we need to use some sort of synopsis or other mechanism to ensure that they are synchronized -- Self match protection - fill mitigation - should cancel on disconnect be on -- handling of business reject - handling of reject - garbage collection of orders - garbage collection of fills -- need spread leg fills for limits -- need to get a handle on transact time - consider including restatement reason - see if handling of cancel rejects is any good - impossible to shutdown orderservice at the moment @@ -547,8 +548,6 @@ digraph G { - maybe an enum can be used to distinguish the subscription features: SINGLETON| SEE_ADV -* Check with taha on wheter there is overlap between his merging of the book and the one that eric needs -* Run a burn test for the shell, see memory usage * Mistakes - Needed one single normalized DB - Orders should be persisted always so we don't have to do crazy stuff @@ -557,8 +556,7 @@ digraph G { - FIX generation - Multiple kinds of native orders - Limit enforcement + - Routing - Recovery from disk -- There should be a better correlation between an order request and - its outcome. In the case of errors its pretty lame. - Jetfix gateway threading model is wrong, cannot take one thread for each session diff --git a/src/lib/orderman/events/ActivateOrderEvent.h b/src/lib/orderman/events/ActivateOrderEvent.h index 91f0f5f46..991e1850e 100644 --- a/src/lib/orderman/events/ActivateOrderEvent.h +++ b/src/lib/orderman/events/ActivateOrderEvent.h @@ -2,32 +2,27 @@ #include -#include "lib/orderman/orderman_utils/orderman_common.h" #include "lib/mercury/events/Event.h" +#include "lib/orderman/orderman_utils/orderman_common.h" #include "lib/tracing/PerfLog.h" namespace bts { namespace orderman { class Order; -class ActivateOrderEvent : public mercury::Event -{ -public: +class ActivateOrderEvent : public mercury::Event { + public: using SynopsisPolicy = mercury::NoSynopsis; - - ActivateOrderEvent (Order &o,Price p, Quantity q) : - order (&o),price(p),quantity(q), trace() + + ActivateOrderEvent(uint32_t req_id, Order &o, Price p, Quantity q) + : req_id(req_id), order(&o), price(p), quantity(q) {} - ActivateOrderEvent (Order &o,Price p, Quantity q,trace::CorID trace) : - order (&o),price(p),quantity(q), trace(trace) - {} - - Order* order; + uint32_t req_id; + Order *order; Price price; Quantity quantity; - trace::CorID trace; }; -}} - +} // namespace orderman +} // namespace bts diff --git a/src/lib/orderman/events/BookUpdateEvent.h b/src/lib/orderman/events/BookUpdateEvent.h index bf71357a8..1dea8f25d 100644 --- a/src/lib/orderman/events/BookUpdateEvent.h +++ b/src/lib/orderman/events/BookUpdateEvent.h @@ -17,6 +17,8 @@ class BookUpdateEvent : public mercury::Event { trace::CorID trace; SecurityKey key() const { return book.security_key(); } + BookUpdateEvent(const Book &b) + : book(b), trace() {} BookUpdateEvent(const Book &b, trace::CorID const &trace) : book(b), trace(trace) {} }; diff --git a/src/lib/orderman/events/CancelOrderEvent.h b/src/lib/orderman/events/CancelOrderEvent.h index cdc2fa563..ae85d1e44 100644 --- a/src/lib/orderman/events/CancelOrderEvent.h +++ b/src/lib/orderman/events/CancelOrderEvent.h @@ -2,26 +2,28 @@ #include -#include "lib/orderman/orderman_utils/orderman_common.h" #include "lib/mercury/events/Event.h" +#include "lib/orderman/orderman_utils/orderman_common.h" #include "lib/tracing/PerfLog.h" namespace bts { namespace orderman { -class CancelOrderEvent : public mercury::Event -{ -public: +class CancelOrderEvent : public mercury::Event { + public: using SynopsisPolicy = mercury::NoSynopsis; - - CancelOrderEvent (OrderKey k) : k (k), trace() {} - CancelOrderEvent (OrderKey k,trace::CorID const&trace) : k (k), trace(trace) {} -// used by ContentSubscription - OrderKey key() const {return k;} + CancelOrderEvent(uint32_t req_id, OrderKey k) + : req_id(req_id), k(k), trace() {} + CancelOrderEvent(uint32_t req_id, OrderKey k, trace::CorID const &trace) + : req_id(req_id), k(k), trace(trace) {} + + uint32_t req_id; + // used by ContentSubscription + OrderKey key() const { return k; } OrderKey k; trace::CorID trace; }; -}} - +} // namespace orderman +} // namespace bts diff --git a/src/lib/orderman/events/CrackOrderEvent.h b/src/lib/orderman/events/CrackOrderEvent.h index 115826241..5efd60408 100644 --- a/src/lib/orderman/events/CrackOrderEvent.h +++ b/src/lib/orderman/events/CrackOrderEvent.h @@ -9,20 +9,17 @@ namespace bts { namespace orderman { -class CrackOrderEvent : public mercury::Event { +class DetachOrderEvent : public mercury::Event { public: using SynopsisPolicy = mercury::NoSynopsis; - CrackOrderEvent(OrderKey k) - : k(k), trace() {} - - CrackOrderEvent(OrderKey k, trace::CorID const &trace) - : k(k), trace(trace) {} + DetachOrderEvent(uint32_t req_id, OrderKey k) + : req_id(req_id), k(k) {} + uint32_t req_id; // used by ContentSubscription OrderKey key() const { return k; } OrderKey k; - trace::CorID trace; }; -} -} +} // namespace orderman +} // namespace bts diff --git a/src/lib/orderman/events/DetachOrderEvent.h b/src/lib/orderman/events/DetachOrderEvent.h new file mode 100644 index 000000000..5efd60408 --- /dev/null +++ b/src/lib/orderman/events/DetachOrderEvent.h @@ -0,0 +1,25 @@ +#pragma once + +#include + +#include "lib/mercury/events/Event.h" +#include "lib/orderman/orderman_utils/orderman_common.h" +#include "lib/tracing/PerfLog.h" + +namespace bts { +namespace orderman { + +class DetachOrderEvent : public mercury::Event { + public: + using SynopsisPolicy = mercury::NoSynopsis; + + DetachOrderEvent(uint32_t req_id, OrderKey k) + : req_id(req_id), k(k) {} + + uint32_t req_id; + // used by ContentSubscription + OrderKey key() const { return k; } + OrderKey k; +}; +} // namespace orderman +} // namespace bts diff --git a/src/lib/orderman/events/OrderDefinitionUpdateEvent.h b/src/lib/orderman/events/OrderDefinitionUpdateEvent.h new file mode 100644 index 000000000..744da9043 --- /dev/null +++ b/src/lib/orderman/events/OrderDefinitionUpdateEvent.h @@ -0,0 +1,26 @@ +#pragma once + +#include "lib/api/services/OrderService.pb.h" +#include "lib/mercury/events/Event.h" +#include "lib/tracing/PerfLog.h" + +#include + +namespace bts { +namespace orderman { + +class OrderDefinitionUpdateEvent + : public mercury::Event { + public: + using SynopsisPolicy = mercury::CacheAll; + + OrderDefinitionUpdateEvent( + OrderKey k, std::shared_ptr const &def) + : key(k), def(def) {} + + OrderKey key; + std::shared_ptr def; +}; + +} // namespace orderman +} // namespace bts diff --git a/src/lib/orderman/events/OrderOpResultEvent.h b/src/lib/orderman/events/OrderOpResultEvent.h new file mode 100644 index 000000000..3db99532b --- /dev/null +++ b/src/lib/orderman/events/OrderOpResultEvent.h @@ -0,0 +1,30 @@ +#pragma once + +#include + +#include "lib/orderman/orderman_utils/orderman_common.h" +#include "lib/mercury/events/Event.h" +#include "lib/orderman/orders/Order.h" + +namespace bts { +namespace orderman { +class Order; + +class OrderOpResultEvent : public mercury::Event +{ +public: + using SynopsisPolicy = mercury::NoSynopsis; + + OrderOpResultEvent (OrderKey k, uint32_t req_id,OrderOpResult const &r ) : + ok(k), + req_id(req_id), + result (r) + {} + + OrderKey ok; + uint32_t req_id; + OrderOpResult result; +}; + +}} + diff --git a/src/lib/orderman/events/OrderStateUpdateEvent.h b/src/lib/orderman/events/OrderStateUpdateEvent.h index 40a489962..7556ce6b4 100644 --- a/src/lib/orderman/events/OrderStateUpdateEvent.h +++ b/src/lib/orderman/events/OrderStateUpdateEvent.h @@ -1,7 +1,8 @@ #pragma once -#include "lib/mercury/events/Event.h" #include "lib/api/services/OrderService.pb.h" +#include "lib/mercury/events/Event.h" +#include "lib/orderman/order_factory/OrderFactory.h" #include "lib/tracing/PerfLog.h" #include @@ -12,12 +13,22 @@ namespace orderman { class OrderStateUpdateEvent : public mercury::Event { public: using SynopsisPolicy = mercury::CacheAll; - OrderStateUpdateEvent(OrderKey key, OrderKey parent_key, - api::orderman::OrderDefinition const &def, - api::orderman::OrderState const &state, - trace::CorID const &trace = trace::CorID()) - : key(key), parent_key(parent_key), trace(trace), definition(&def) { + OrderStateUpdateEvent() + : key(null_order_key()), parent_key(null_order_key()) {} + + OrderStateUpdateEvent(OrderKey k, OrderKey pk, + std::shared_ptr const &def, + api::orderman::OrderState const &state) { + init(k, pk, def,state); + } + + void init(OrderKey k, OrderKey pk, + std::shared_ptr const &def, + api::orderman::OrderState const &state) { + key = k; + parent_key = pk; + definition = def; status = state.status(); price = state.price(); quantity = state.quantity(); @@ -26,9 +37,9 @@ class OrderStateUpdateEvent : public mercury::Event { avg_price = state.avg_price(); last_msg = state.last_msg(); display_status = state.display_status(); - + custom = state.custom_case(); - + auto native_state = get_native_state(state); if (native_state) { exchange_order_id = native_state->exchange_order_id(); @@ -41,9 +52,11 @@ class OrderStateUpdateEvent : public mercury::Event { &last_transact_time); } } + OrderKey key; OrderKey parent_key; - + std::shared_ptr definition; + // common state api::orderman::OrderStatus status; double price; @@ -53,8 +66,7 @@ class OrderStateUpdateEvent : public mercury::Event { double avg_price; std::string last_msg; api::orderman::OrderState::DisplayStatus display_status; - - trace::CorID trace; + api::orderman::OrderState::CustomCase custom; // native order state @@ -66,9 +78,7 @@ class OrderStateUpdateEvent : public mercury::Event { api::orderman::NativeOrderType native_type; mercury::TimeStampStr last_transact_time; - api::orderman::OrderDefinition const *definition; - - api::orderman::OrderState rebuild_state() const { + api::orderman::OrderState quick_rebuild_state() const { api::orderman::OrderState result; result.set_status(status); result.set_price(price); @@ -78,7 +88,11 @@ class OrderStateUpdateEvent : public mercury::Event { result.set_avg_price(avg_price); result.set_last_msg(last_msg); result.set_display_status(display_status); - + return result; + } + + api::orderman::OrderState rebuild_state() const { + api::orderman::OrderState result = quick_rebuild_state(); switch (custom) { case api::orderman::OrderState::kMarket: rebuild_native_state(result.mutable_market()->mutable_native_state()); @@ -90,7 +104,8 @@ class OrderStateUpdateEvent : public mercury::Event { rebuild_native_state(result.mutable_stop()->mutable_native_state()); break; case api::orderman::OrderState::kStopLimit: - rebuild_native_state(result.mutable_stop_limit()->mutable_native_state()); + rebuild_native_state( + result.mutable_stop_limit()->mutable_native_state()); break; case api::orderman::OrderState::kIceberg: result.mutable_iceberg(); @@ -122,25 +137,27 @@ class OrderStateUpdateEvent : public mercury::Event { case api::orderman::OrderState::kOffset: result.mutable_offset(); break; + case api::orderman::OrderState::kQueueHolder: + result.mutable_queue_holder(); + break; case api::orderman::OrderState::kOco: result.mutable_oco(); - break; + break; case api::orderman::OrderState::kPricer: result.mutable_pricer(); - break; + break; case api::orderman::OrderState::kDynamic: result.mutable_dynamic(); break; case api::orderman::OrderState::CUSTOM_NOT_SET: break; } - + return result; } -private: - void rebuild_native_state(api::orderman::NativeOrderState *st) const - { + private: + void rebuild_native_state(api::orderman::NativeOrderState *st) const { st->set_exchange_order_id(exchange_order_id); st->set_last_msg_seq_num(last_msg_seq_num); st->set_sub_error_code(sub_error_code); @@ -149,8 +166,7 @@ private: st->set_native_type(native_type); st->set_last_transact_time(to_str(last_transact_time)); } - - + api::orderman::NativeOrderState const * get_native_state(api::orderman::OrderState const &st) { switch (st.custom_case()) { @@ -166,7 +182,6 @@ private: return nullptr; }; } - }; } // namespace orderman diff --git a/src/lib/orderman/events/UpdateOrderEvent.h b/src/lib/orderman/events/UpdateOrderEvent.h index c514c9649..210ee00d4 100644 --- a/src/lib/orderman/events/UpdateOrderEvent.h +++ b/src/lib/orderman/events/UpdateOrderEvent.h @@ -14,21 +14,20 @@ class UpdateOrderEvent : public mercury::Event public: using SynopsisPolicy = mercury::NoSynopsis; - UpdateOrderEvent (OrderKey k, Price p, Quantity q) : - k(k), price(p), quantity(q), trace() - {} - - UpdateOrderEvent (OrderKey k, Price p, Quantity q,trace::CorID const&trace) : - k(k), price(p), quantity(q), trace(trace) + UpdateOrderEvent (uint32_t rid,api::orderman::Update const&update) : + _req_id(rid), _update(update) {} // used by ContentSubscription - OrderKey key() const {return k;} - - OrderKey k; - Price price; - Quantity quantity; - trace::CorID trace; + OrderKey key() const {return OrderKey(_update.order_key());} + Price price() const {return Price(_update.price());} + Quantity quantity() const {return Quantity(_update.quantity());} + bool is_full_update() const {return _update.has_custom();} + api::orderman::Update const &full_update() const {return _update;} + uint32_t req_id() const {return _req_id;} +private: + uint32_t _req_id; + api::orderman::Update _update; }; }} diff --git a/src/lib/orderman/order_factory/DynamicAlgoBuilder.h b/src/lib/orderman/order_factory/DynamicAlgoBuilder.h new file mode 100644 index 000000000..f79c27296 --- /dev/null +++ b/src/lib/orderman/order_factory/DynamicAlgoBuilder.h @@ -0,0 +1,12 @@ +#pragma once + +#include +#include + +namespace bts { +namespace orderman { + +class IAlgoOrder; +using DynamicAlgoBuilder = std::function()>; + +}} diff --git a/src/lib/orderman/order_factory/DynamicOrderBuilder.h b/src/lib/orderman/order_factory/DynamicOrderBuilder.h index 9a2262396..602c70138 100644 --- a/src/lib/orderman/order_factory/DynamicOrderBuilder.h +++ b/src/lib/orderman/order_factory/DynamicOrderBuilder.h @@ -7,8 +7,8 @@ namespace bts { namespace orderman { -class DynamicOrder; +class Order; -using DynamicOrderBuilder = std::function()>; +using DynamicOrderBuilder = std::function()>; }} diff --git a/src/lib/orderman/order_factory/DynamicOrderRegistry.cpp b/src/lib/orderman/order_factory/DynamicOrderRegistry.cpp index a2fda91b4..1bc03ad39 100644 --- a/src/lib/orderman/order_factory/DynamicOrderRegistry.cpp +++ b/src/lib/orderman/order_factory/DynamicOrderRegistry.cpp @@ -1,5 +1,7 @@ #include "DynamicOrderRegistry.h" #include "lib/orderman/orders/DynamicOrder.h" +#include "lib/orderman/orders/algo/AlgoWrapperOrder.h" +#include "lib/orderman/orders/algo/IAlgoOrder.h" #include @@ -22,7 +24,17 @@ void DynamicOrderRegistry::register_dynamic_order( me->dyn_orders[desc.dynamic_order_type()] = std::make_pair(b, desc); } -std::unique_ptr +void DynamicOrderRegistry::register_dynamic_algo_order( + api::orderman::DynamicOrderDescriptor const &desc, + DynamicAlgoBuilder const &b) { + auto order_builder = [b]() { + return std::make_unique(b()); + }; + me->dyn_orders[desc.dynamic_order_type()] = + std::make_pair(order_builder, desc); +} + +std::unique_ptr DynamicOrderRegistry::build(std::string const &dynamic_order_type) const { auto it = me->dyn_orders.find(dynamic_order_type); if (it != me->dyn_orders.end()) diff --git a/src/lib/orderman/order_factory/DynamicOrderRegistry.h b/src/lib/orderman/order_factory/DynamicOrderRegistry.h index 9a53edd2f..835503012 100644 --- a/src/lib/orderman/order_factory/DynamicOrderRegistry.h +++ b/src/lib/orderman/order_factory/DynamicOrderRegistry.h @@ -1,27 +1,37 @@ #pragma once +#include "lib/orderman/order_factory/DynamicAlgoBuilder.h" #include "lib/orderman/order_factory/DynamicOrderBuilder.h" + #include "lib/api/services/OrderService.pb.h" namespace bts { namespace orderman { - class DynamicOrderRegistry { -public: + public: DynamicOrderRegistry(); ~DynamicOrderRegistry(); - - void register_dynamic_order(api::orderman::DynamicOrderDescriptor const&desc, - DynamicOrderBuilder const&builder); + + // deprecated + void + register_dynamic_order(api::orderman::DynamicOrderDescriptor const &desc, + DynamicOrderBuilder const &builder); + + void register_dynamic_algo_order( + api::orderman::DynamicOrderDescriptor const &desc, + DynamicAlgoBuilder const &builder); // can return a null if no such order type exists - std::unique_ptr build(std::string const&dynamic_order_type) const; + std::unique_ptr build(std::string const &dynamic_order_type) const; - std::vector get_all_dynamic_order_types() const; -private: + std::vector + get_all_dynamic_order_types() const; + + private: struct PImpl; - std::unique_ptr me; + std::unique_ptr me; }; -}} +} // namespace orderman +} // namespace bts diff --git a/src/lib/orderman/order_factory/IOrderFactory.h b/src/lib/orderman/order_factory/IOrderFactory.h index 70557bf26..80cc9207b 100644 --- a/src/lib/orderman/order_factory/IOrderFactory.h +++ b/src/lib/orderman/order_factory/IOrderFactory.h @@ -18,6 +18,8 @@ namespace orderman { inline OrderKey null_order_key() {return OrderKey(0);} + + class IOrderFactory { public: diff --git a/src/lib/orderman/order_factory/OrderFactory.cpp b/src/lib/orderman/order_factory/OrderFactory.cpp index c184a660d..2cbac4d4b 100644 --- a/src/lib/orderman/order_factory/OrderFactory.cpp +++ b/src/lib/orderman/order_factory/OrderFactory.cpp @@ -10,18 +10,21 @@ // order types #include "lib/orderman/order_factory/DynamicOrderRegistry.h" #include "lib/orderman/orders/DynamicOrder.h" -#include "lib/orderman/orders/IcebergOrder.h" #include "lib/orderman/orders/NativeOrder.h" #include "lib/orderman/orders/TimeBoxOrder.h" #include "lib/orderman/orders/TriggerOrder.h" -#include "lib/orderman/orders/book_algos/CoverOrder.h" -#include "lib/orderman/orders/book_algos/JoinOrder.h" -#include "lib/orderman/orders/book_algos/LeanOrder.h" -#include "lib/orderman/orders/book_algos/OffsetOrder.h" +#include "lib/orderman/orders/algo/AlgoWrapperOrder.h" +#include "lib/orderman/orders/algo/algo_orders/CoverAlgo.h" +#include "lib/orderman/orders/algo/algo_orders/JoinAlgo.h" +#include "lib/orderman/orders/algo/algo_orders/TopAlgo.h" +#include "lib/orderman/orders/algo/algo_orders/IcebergAlgo.h" +#include "lib/orderman/orders/algo/algo_orders/LeanAlgo.h" #include "lib/orderman/orders/book_algos/OCOOrder.h" +#include "lib/orderman/orders/book_algos/OffsetOrder.h" #include "lib/orderman/orders/book_algos/PricerOrder.h" -#include "lib/orderman/orders/book_algos/TopOrder.h" #include "lib/orderman/orders/spreader_orders/SpreaderOrder.h" +#include "lib/orderman/orders/CompositeOrder.h" +#include "lib/orderman/orders/queue_holder/QueueHolderOrder.h" #include #include @@ -73,22 +76,27 @@ Order &OrderFactory::create(OrderKey parent, auto k = gen_order_id(); auto pk = parent; auto &order = allocate(k, pk, def); + api::orderman::OrderDefinition const *def_ptr = &def; + api::orderman::OrderDefinition corrected_def; - // For non native orders we force the ManalOrderIndicator to be 'N' - // since all non native order are algos and we would rather not - // rely on the order creator (be it shell or another algo) to set - // this correctly for every single algo. + // For non native orders we force the ManualOrderIndicator to be + // 'N' since anything that is not a native order is an algo and we + // would rather not depend on the shell and every algo setting this + // field correctly. Algos will just propagate the value of this + // field down so eventually native orders launched by algos will + // get the right value. if (dynamic_cast(&order) == nullptr && def.manual_order_indicator() == api::orderman::MANUAL_ORDER_INDICATOR_YES) { - auto corrected_def = def; + // An algo order incorrectly marked as a manual order + corrected_def = def; corrected_def.set_manual_order_indicator( api::orderman::MANUAL_ORDER_INDICATOR_NO); - order.on_init_new(corrected_def, PreActivationOrderServices{ - me->sec_db, *this, me->router}); - } else - order.on_init_new( - def, PreActivationOrderServices{me->sec_db, *this, me->router}); + def_ptr = &corrected_def; + } + order.set_def(*def_ptr); + order.on_init_new(*def_ptr, + PreActivationOrderServices{me->sec_db, *this, me->router}); return order; } @@ -96,6 +104,7 @@ Order &OrderFactory::recover(api::orderman::OrderRecord const &rec) { auto k = OrderKey(rec.key()); auto pk = OrderKey(rec.parent_key()); auto &order = allocate(k, pk, rec.def()); + order.set_def(rec.def()); order.on_init_recovered( rec, PreActivationOrderServices{me->sec_db, *this, me->router}); return order; @@ -110,10 +119,11 @@ Order &OrderFactory::recreate_from_exe_report(ExecutionReport const &r) { case NATIVE_ORDER_TYPE_STOP: case NATIVE_ORDER_TYPE_STOP_LIMIT: { auto native_order = std::make_unique(); - native_order->on_init_from_exe_report( - r, PreActivationOrderServices{me->sec_db, *this, me->router}); native_order->_key = r.order_key; native_order->_parent_key = null_order_key(); + auto def = native_order->on_init_from_exe_report( + r, PreActivationOrderServices{me->sec_db, *this, me->router}); + native_order->set_def(def); me->my_orders.emplace_back(); auto &order_ptr = me->my_orders.back(); order_ptr.reset(native_order.release()); @@ -140,7 +150,8 @@ Order &OrderFactory::allocate(OrderKey k, OrderKey pk, order_ptr.reset(new NativeOrder()); break; case CustomOrderDefinition::kIceberg: - order_ptr.reset(new IcebergOrder()); + order_ptr.reset( + new orderman::AlgoWrapperOrder(std::make_unique())); break; case CustomOrderDefinition::kSpreader: order_ptr.reset(new orderman::SpreaderOrder()); @@ -152,29 +163,36 @@ Order &OrderFactory::allocate(OrderKey k, OrderKey pk, bts_assert(false); break; case CustomOrderDefinition::kLean: - order_ptr.reset(new orderman::LeanOrder()); + order_ptr.reset( + new orderman::AlgoWrapperOrder(std::make_unique())); break; case CustomOrderDefinition::kJoin: - order_ptr.reset(new orderman::JoinOrder()); + order_ptr.reset( + new orderman::AlgoWrapperOrder(std::make_unique())); break; case CustomOrderDefinition::kTop: - order_ptr.reset(new orderman::TopOrder()); + order_ptr.reset( + new orderman::AlgoWrapperOrder(std::make_unique())); break; case CustomOrderDefinition::kTrigger: order_ptr.reset(new orderman::TriggerOrder()); break; case CustomOrderDefinition::kCover: - order_ptr.reset(new orderman::CoverOrder()); + order_ptr.reset( + new orderman::AlgoWrapperOrder(std::make_unique())); break; case CustomOrderDefinition::kOffset: order_ptr.reset(new orderman::OffsetOrder()); - break; + break; + case CustomOrderDefinition::kQueueHolder: + order_ptr.reset(new orderman::QueueHolderOrder()); + break; case CustomOrderDefinition::kOco: order_ptr.reset(new orderman::OCOOrder()); - break; + break; case CustomOrderDefinition::kPricer: order_ptr.reset(new orderman::PricerOrder()); - break; + break; case CustomOrderDefinition::kDynamic: { order_ptr = me->dynamic_order_registry.build( def.custom_def().dynamic().dynamic_order_type()); @@ -186,6 +204,9 @@ Order &OrderFactory::allocate(OrderKey k, OrderKey pk, } break; } + case CustomOrderDefinition::kComposite: + order_ptr.reset(new orderman::CompositeOrder()); + break; case CustomOrderDefinition::CUSTOM_NOT_SET: bts_assert(false); break; diff --git a/src/lib/orderman/orderman_utils/orderman_common.h b/src/lib/orderman/orderman_utils/orderman_common.h index 4fa5f145b..14fe0aec1 100644 --- a/src/lib/orderman/orderman_utils/orderman_common.h +++ b/src/lib/orderman/orderman_utils/orderman_common.h @@ -67,11 +67,19 @@ template inline std::string to_str(T const &t) { } template -std::pair to_trim_str(std::array const &in) { - for (auto i = (size_t)0; i < N; i++) - if (in[i] == ' ') - return std::make_pair(&in[0], i); - return std::make_pair(&in[0], N); +std::pair find_trim_str(std::array const &in) { + auto i = N; + for (; i!= 0; i--) + if (in[i-1] != ' ') + break; + + return std::make_pair(&in[0], i); +} + +template +std::string to_trim_str(T const&t) { + auto ts = find_trim_str(t.value()); + return std::string(ts.first,ts.second); } inline bool in_terminal_state(bts::api::orderman::OrderStatus order_status) { diff --git a/src/lib/orderman/orderman_utils/orderman_utils.cpp b/src/lib/orderman/orderman_utils/orderman_utils.cpp new file mode 100644 index 000000000..8099a0b5a --- /dev/null +++ b/src/lib/orderman/orderman_utils/orderman_utils.cpp @@ -0,0 +1,53 @@ +#include "orderman_utils.h" +#include "lib/utils/bts_assert.h" + +using namespace bts::api::orderman; + +namespace bts { +namespace orderman { + +bool can_consume_attachment(api::orderman::CustomOrderDefinition::CustomCase order_kind) { + switch (order_kind) { + case CustomOrderDefinition::kIceberg: + case CustomOrderDefinition::kDynamic: + case CustomOrderDefinition::kJoin: + case CustomOrderDefinition::kTop: + case CustomOrderDefinition::kCover: + case CustomOrderDefinition::kLean: + return true; + default: + return false; + } +} + +bool should_forward_attachment( + const api::orderman::CustomOrderDefinition &cdef) { + + switch (cdef.custom_case()) { + case CustomOrderDefinition::kIceberg: + return + cdef.iceberg().has_child() && + can_consume_attachment(cdef.iceberg().child().custom_case()); + case CustomOrderDefinition::kJoin: + return + cdef.join().has_child() && + can_consume_attachment(cdef.join().child().custom_case()); + case CustomOrderDefinition::kTop: + return + cdef.top().has_child() && + can_consume_attachment(cdef.top().child().custom_case()); + case CustomOrderDefinition::kCover: + return + cdef.cover().has_child() && + can_consume_attachment(cdef.cover().child().custom_case()); + case CustomOrderDefinition::kLean: + return + cdef.lean().has_child() && + can_consume_attachment(cdef.lean().child().custom_case()); + default: + return false; + } +} + +} // namespace orderman +} // namespace bts diff --git a/src/lib/orderman/orderman_utils/orderman_utils.h b/src/lib/orderman/orderman_utils/orderman_utils.h index 32194c4c3..50b97ce43 100644 --- a/src/lib/orderman/orderman_utils/orderman_utils.h +++ b/src/lib/orderman/orderman_utils/orderman_utils.h @@ -1,30 +1,34 @@ #include "lib/api/services/OrderService.pb.h" -namespace bts{ -namespace orderman{ +namespace bts { +namespace orderman { -using namespace bts::api::orderman; -inline bool order_in_error_state(OrderStatus order_status){ +inline bool order_in_error_state(bts::api::orderman::OrderStatus order_status) { + using namespace bts::api::orderman; return order_status == OrderStatus::ORDER_STATUS_ERROR || order_status == OrderStatus::ORDER_STATUS_DISCONNECTED || order_status == OrderStatus::ORDER_STATUS_REJECTED_BY_SPARK; } -inline bool order_in_working_state(OrderStatus order_status){ +inline bool order_in_working_state(bts::api::orderman::OrderStatus order_status) { + using namespace bts::api::orderman; return order_status == OrderStatus::ORDER_STATUS_WORKING || order_status == OrderStatus::ORDER_STATUS_PENDING_WORKING; } -inline bool is_exchange_order(const OrderState& state){ - return state.has_market() || - state.has_limit() || - state.has_stop() || +inline bool is_exchange_order(const bts::api::orderman::OrderState &state) { + using namespace bts::api::orderman; + return state.has_market() || state.has_limit() || state.has_stop() || state.has_stop_limit(); } -inline bool is_parent_order(const OrderRecord& ord){ - return ord.parent_key()==0; +inline bool is_parent_order(const bts::api::orderman::OrderRecord &ord) { + return ord.parent_key() == 0; } -}} \ No newline at end of file +bool should_forward_attachment(const api::orderman::CustomOrderDefinition &def); +bool can_consume_attachment(api::orderman::CustomOrderDefinition::CustomCase) ; + +} // namespace orderman +} // namespace bts diff --git a/src/lib/orderman/orders/CompositeOrder.cpp b/src/lib/orderman/orders/CompositeOrder.cpp new file mode 100644 index 000000000..abc8f9536 --- /dev/null +++ b/src/lib/orderman/orders/CompositeOrder.cpp @@ -0,0 +1,150 @@ +#include "lib/orderman/orders/CompositeOrder.h" +#include "lib/api/services/OrderService.pb.h" +#include "lib/orderman/actors/order_manager/ChildOrder.h" +#include "lib/orderman/actors/order_manager/OrderBuilder.h" +#include "lib/orderman/orders/PreActivationOrderServices.h" +#include "lib/utils/PBUtils.h" + +#include "lib/utils/bts_assert.h" + +namespace bts { +namespace orderman { + +using namespace api::orderman; + +struct CompositeOrder::PImpl { + ChildOrder child_order; + OrderBuilder order_builder; + OrderServices *services; + api::orderman::OrderState state; + api::orderman::OrderDefinition definition; +}; + +CompositeOrder::CompositeOrder() : me(new PImpl()) {} +CompositeOrder::~CompositeOrder() {} + +void CompositeOrder::on_init_new(api::orderman::OrderDefinition const &def, + const PreActivationOrderServices &serv) { + bts_assert(def.custom_def().has_composite()); + me->definition = def; + api::orderman::OrderDefinition child_def = def; + *child_def.mutable_custom_def() = def.custom_def().composite().definition(); + me->order_builder = OrderBuilder{key(), child_def, serv.order_factory, 1}; + me->state.set_status(ORDER_STATUS_INACTIVE); +} + +void CompositeOrder::on_init_recovered(OrderRecord const &rec, + const PreActivationOrderServices &) { + + me->state = rec.state(); + // Infer internal status from persisted external status + switch (me->state.status()) { + + case ORDER_STATUS_WORKING: + case ORDER_STATUS_PENDING_WORKING: + case ORDER_STATUS_DISCONNECTED: + me->state.set_status(ORDER_STATUS_ERROR); + me->state.set_last_msg("System restarted with active composite order"); + return; + + // Terminal states + case ORDER_STATUS_ERROR: + case ORDER_STATUS_REJECTED_BY_SPARK: + case ORDER_STATUS_COMPLETED: + case ORDER_STATUS_CANCELED: + break; + + // It should not be possible to reach these + case ORDER_STATUS_INACTIVE: + case OrderStatus_INT_MIN_SENTINEL_DO_NOT_USE_: + case OrderStatus_INT_MAX_SENTINEL_DO_NOT_USE_: + bts_assert(false); + break; + } +} + +OrderOpResult CompositeOrder::on_activate(Price p, Quantity q, + OrderServices &services) { + me->services = &services; + switch (me->state.status()) { + case ORDER_STATUS_INACTIVE: + me->state.set_status(ORDER_STATUS_WORKING); + me->order_builder.activate(services); + me->child_order = me->order_builder.build(); + me->child_order.activate(p, q); + services.subscribe_to_child_updates([this](auto const &u) { + this->on_child_order_update(u.key, u.quick_rebuild_state()); + }); + break; + + // Terminal states + case ORDER_STATUS_ERROR: + case ORDER_STATUS_REJECTED_BY_SPARK: + case ORDER_STATUS_COMPLETED: + case ORDER_STATUS_CANCELED: + break; + + // It should not be possible to reach these + case ORDER_STATUS_DISCONNECTED: + case ORDER_STATUS_WORKING: + case ORDER_STATUS_PENDING_WORKING: + case OrderStatus_INT_MIN_SENTINEL_DO_NOT_USE_: + case OrderStatus_INT_MAX_SENTINEL_DO_NOT_USE_: + bts_assert(false); + break; + } + services.report_state(me->state); + return {}; +} + +OrderOpResult CompositeOrder::on_update(Price p, Quantity q) { + if (!me->child_order.empty()) + me->child_order.update(p, q); + return {}; +} + +OrderOpResult CompositeOrder::on_update(api::orderman::Update const &u) { + if (!me->child_order.empty()) { + Update child_update; + child_update.set_price(u.price()); + child_update.set_quantity(u.quantity()); + child_update.set_order_key(me->child_order.key().value()); + + if (u.has_custom()) { + bts_assert(u.custom().has_composite()); + auto const &cupdate = u.custom().composite().definition(); + *child_update.mutable_custom() = cupdate; + *me->definition.mutable_custom_def() = u.custom(); + me->services->report_definition(me->definition); + } + me->child_order.update(child_update); + me->services->report_state(me->state); + } + return {}; +} + +OrderOpResult CompositeOrder::on_detach() { + if (!me->child_order.empty()) { + me->child_order.mark_detached_from_parent(); + me->child_order = {}; + me->state.set_status(ORDER_STATUS_CANCELED); + me->services->report_state(me->state); + } + return {}; +} + +OrderOpResult CompositeOrder::on_cancel() { + if (!me->child_order.empty()) + me->child_order.cancel(); + return {}; +} + +void CompositeOrder::on_child_order_update( + OrderKey, api::orderman::OrderState const &st) { + me->services->report_state(st); +} + +void CompositeOrder::on_attached(api::orderman::OrderDefinition const &) {} + +} // namespace orderman +} // namespace bts diff --git a/src/lib/orderman/orders/CompositeOrder.h b/src/lib/orderman/orders/CompositeOrder.h new file mode 100644 index 000000000..5016641ae --- /dev/null +++ b/src/lib/orderman/orders/CompositeOrder.h @@ -0,0 +1,30 @@ +#pragma once + +#include "lib/orderman/orders/Order.h" + +namespace bts { +namespace orderman { + +class CompositeOrder : public Order { + public: + CompositeOrder(); + ~CompositeOrder(); + + void on_init_new(api::orderman::OrderDefinition const &, + const PreActivationOrderServices &) override; + void on_init_recovered(api::orderman::OrderRecord const &, + const PreActivationOrderServices &) override; + OrderOpResult on_activate(Price, Quantity, OrderServices &) override; + OrderOpResult on_update(Price, Quantity) override; + OrderOpResult on_update(api::orderman::Update const &) override; + OrderOpResult on_detach() override; + OrderOpResult on_cancel() override; + void on_attached(api::orderman::OrderDefinition const &new_parent) override; + + private: + struct PImpl; + std::unique_ptr me; + void on_child_order_update(OrderKey, api::orderman::OrderState const &); +}; +} // namespace orderman +} // namespace bts diff --git a/src/lib/orderman/orders/DynamicOrder.cpp b/src/lib/orderman/orders/DynamicOrder.cpp index df6670c3f..c2a651506 100644 --- a/src/lib/orderman/orders/DynamicOrder.cpp +++ b/src/lib/orderman/orders/DynamicOrder.cpp @@ -19,10 +19,6 @@ DynamicOrder::DynamicOrder() : me(new PImpl()) {} DynamicOrder::~DynamicOrder() {} -api::orderman::OrderDefinition const &DynamicOrder::definition() const { - return me->def; -} - void DynamicOrder::on_init_new(api::orderman::OrderDefinition const &def, const PreActivationOrderServices &) { me->def = def; @@ -48,14 +44,13 @@ void DynamicOrder::on_init_recovered(api::orderman::OrderRecord const &rec, me->state.set_last_msg(msg); } -void DynamicOrder::on_activate(Price, Quantity, OrderServices &services, - trace::CorID const &) { +OrderOpResult DynamicOrder::on_activate(Price, Quantity, OrderServices &services) { services.report_state(me->state); + return OrderOpResult{}; } -void DynamicOrder::on_update(Price, Quantity, trace::CorID const &) {} -void DynamicOrder::on_crack(trace::CorID const &) {} -void DynamicOrder::on_cancel(trace::CorID const &) {} +OrderOpResult DynamicOrder::on_update(Price, Quantity) {return OrderOpResult{};} +OrderOpResult DynamicOrder::on_cancel() {return OrderOpResult{};} } // namespace orderman } // namespace bts diff --git a/src/lib/orderman/orders/DynamicOrder.h b/src/lib/orderman/orders/DynamicOrder.h index d346b6b5c..a1b9de7a5 100644 --- a/src/lib/orderman/orders/DynamicOrder.h +++ b/src/lib/orderman/orders/DynamicOrder.h @@ -14,15 +14,13 @@ class DynamicOrder : public Order public: DynamicOrder(); ~DynamicOrder(); - api::orderman::OrderDefinition const&definition() const override; void on_init_new(api::orderman::OrderDefinition const&, const PreActivationOrderServices&) override; void on_init_recovered(api::orderman::OrderRecord const&, const PreActivationOrderServices &) override; - void on_activate(Price,Quantity,OrderServices &, trace::CorID const&) override ; - void on_update(Price , Quantity,trace::CorID const&) override ; - void on_crack(trace::CorID const&) override ; - void on_cancel(trace::CorID const&) override ; + OrderOpResult on_activate(Price,Quantity,OrderServices &) override ; + OrderOpResult on_update(Price , Quantity) override ; + OrderOpResult on_cancel() override ; private: struct PImpl; diff --git a/src/lib/orderman/orders/IcebergOrder.cpp b/src/lib/orderman/orders/IcebergOrder.cpp deleted file mode 100644 index 00ef5dd0a..000000000 --- a/src/lib/orderman/orders/IcebergOrder.cpp +++ /dev/null @@ -1,358 +0,0 @@ -#include "IcebergOrder.h" -#include "lib/config/config.h" -#include "lib/config/protos/orderman_cfg.pb.h" -#include "lib/logging/logging.h" -#include "lib/mercury/events/TimerEvent.h" -#include "lib/orderman/actors/order_manager/OrderBuilder.h" -#include "lib/utils/PBUtils.h" -#include "lib/utils/bts_chrono.h" - -#include - -namespace bts { -namespace orderman { - -using namespace api::orderman; - -struct IcebergOrder::ActiveChild { - ActiveChild() {} - ChildOrder order; - - api::orderman::OrderState state; - OrderKey key; - - void clear() { - state = api::orderman::OrderState(); - key = null_order_key(); - } -}; - -enum class IcebergOrder::WorkingSubStatus { WORKING, PAUSED }; - -struct IcebergOrder::PImpl { - PImpl() - : services(nullptr), child(), - working_sub_status(WorkingSubStatus::PAUSED), - start_of_pause(Timer::now()) {} - - OrderServices *services; - api::orderman::OrderDefinition def; - api::orderman::OrderState state; - OrderBuilder child_builder; - ActiveChild child; - Quantity show_quantity; - WorkingSubStatus working_sub_status; - TimeStamp start_of_pause; - uint32_t pause_between_orders; -}; - -IcebergOrder::IcebergOrder() : me(new PImpl()) {} - -IcebergOrder::~IcebergOrder() {} - -api::orderman::OrderDefinition const &IcebergOrder::definition() const { - return me->def; -} - -void IcebergOrder::on_init_new(api::orderman::OrderDefinition const &def, - const PreActivationOrderServices &services) { - me->def = def; - me->state.mutable_iceberg(); - - auto const &iceberg_def = def.custom_def().iceberg(); - me->show_quantity = Quantity(iceberg_def.show_quantity()); - me->pause_between_orders = - config::get().default_iceberg_pause_secs(); - - auto child_def = def; - *child_def.mutable_custom_def() = iceberg_def.child(); - if (me->show_quantity.value() != 0) { - me->child_builder = OrderBuilder( - key(), child_def, services, - std::max((size_t)1, (size_t)(me->show_quantity).value() / 10)); - transition(ORDER_STATUS_INACTIVE); - } else { - auto msg = fmt::format("Show quantity must be greater than 0"); - me->state.set_last_msg(msg); - transition(ORDER_STATUS_REJECTED_BY_SPARK, msg); - } -} - -void IcebergOrder::on_init_recovered(api::orderman::OrderRecord const &rec, - const PreActivationOrderServices &) { - auto const &def = rec.def(); - me->def = def; - me->state = rec.state(); - - switch (me->state.status()) { - - case ORDER_STATUS_WORKING: - case ORDER_STATUS_DISCONNECTED: { - auto msg = "System restarted with active iceberg order"; - me->state.set_last_msg(msg); - transition(ORDER_STATUS_ERROR, msg); - break; - } - // terminal states - case ORDER_STATUS_ERROR: - case ORDER_STATUS_REJECTED_BY_SPARK: - case ORDER_STATUS_COMPLETED: - case ORDER_STATUS_CANCELED: - break; - - case ORDER_STATUS_PENDING_WORKING: - case ORDER_STATUS_INACTIVE: - case OrderStatus_INT_MIN_SENTINEL_DO_NOT_USE_: - case OrderStatus_INT_MAX_SENTINEL_DO_NOT_USE_: - bts_assert(false); - break; - } -} - -void IcebergOrder::on_activate(Price p, Quantity q, OrderServices &services, - trace::CorID const &) { - bts_assert(!me->services); - me->services = &services; - me->child_builder.activate(services); - - switch (me->state.status()) { - case ORDER_STATUS_INACTIVE: - me->state.set_price(p.value()); - me->state.set_quantity(q.value()); - if (me->pause_between_orders) - services.subscribe_to_time( - [this](auto const &time) { this->on_time(time); }); - services.subscribe_to_child_updates( - [this](auto const &os) { this->on_child_order_update(os); }); - transition(ORDER_STATUS_WORKING); - me->working_sub_status = WorkingSubStatus::WORKING; - send_next_child_order(); - break; - - // these are not possible since the on_init_recovered code - // would have transitioned us to error already - case ORDER_STATUS_WORKING: - case ORDER_STATUS_PENDING_WORKING: - case ORDER_STATUS_DISCONNECTED: { - bts_assert(false); - break; - } - // terminal states - case ORDER_STATUS_ERROR: - case ORDER_STATUS_REJECTED_BY_SPARK: - case ORDER_STATUS_COMPLETED: - case ORDER_STATUS_CANCELED: - break; - case OrderStatus_INT_MIN_SENTINEL_DO_NOT_USE_: - case OrderStatus_INT_MAX_SENTINEL_DO_NOT_USE_: - bts_assert(false); - break; - } - report_state(); -} - -void IcebergOrder::on_update(Price p, Quantity q, trace::CorID const &) { - switch (me->state.status()) { - case ORDER_STATUS_WORKING: - case ORDER_STATUS_PENDING_WORKING: - LOG(OrderMan, Info, "Updating Iceberg order {} to price {} quantity {}", - key().value(), p.value(), q.value()); - me->state.set_price(p.value()); - me->state.set_quantity(q.value()); - break; - case ORDER_STATUS_DISCONNECTED: - case ORDER_STATUS_REJECTED_BY_SPARK: - case ORDER_STATUS_COMPLETED: - case ORDER_STATUS_CANCELED: - case ORDER_STATUS_ERROR: - transition(me->state.status(), "Cannot update order"); - break; - - case ORDER_STATUS_INACTIVE: - case OrderStatus_INT_MIN_SENTINEL_DO_NOT_USE_: - case OrderStatus_INT_MAX_SENTINEL_DO_NOT_USE_: - bts_assert(false); - break; - } - report_state(); -} - -void IcebergOrder::on_crack(trace::CorID const &) {} - -void IcebergOrder::on_cancel(trace::CorID const &) { - switch (me->state.status()) { - case ORDER_STATUS_WORKING: - LOG(OrderMan, Info, "Canceling Iceberg Order {}", key().value()); - me->child.order.cancel(); - transition(ORDER_STATUS_CANCELED); - break; - case ORDER_STATUS_PENDING_WORKING: - case ORDER_STATUS_DISCONNECTED: - case ORDER_STATUS_REJECTED_BY_SPARK: - case ORDER_STATUS_COMPLETED: - case ORDER_STATUS_CANCELED: - case ORDER_STATUS_ERROR: - transition(me->state.status(), "Cannot cancel order"); - break; - - case ORDER_STATUS_INACTIVE: - case OrderStatus_INT_MIN_SENTINEL_DO_NOT_USE_: - case OrderStatus_INT_MAX_SENTINEL_DO_NOT_USE_: - bts_assert(false); - break; - } - report_state(); -} - -void IcebergOrder::transition(api::orderman::OrderStatus new_status, - std::string const &msg) { - auto const &from = OrderStatus_Name(me->state.status()); - auto const &to = OrderStatus_Name(new_status); - LOG(OrderMan, Info, "Transitioning iceberg order {} from {} to {}. Msg: {}", - key().value(), from, to, msg); - me->state.set_last_msg(msg); - me->state.set_status(new_status); -} - -void IcebergOrder::transition(api::orderman::OrderStatus new_status) { - auto const &from = OrderStatus_Name(me->state.status()); - auto const &to = OrderStatus_Name(new_status); - LOG(OrderMan, Info, "Transitioning iceberg order {} from {} to {}", - key().value(), from, to); - me->state.set_status(new_status); -} - -void IcebergOrder::report_state() { - if (me->child.state.filled_quantity()) { - api::orderman::OrderState merged_state; - merge_states(me->state, me->child.state, &merged_state); - me->services->report_state(merged_state); - } else - me->services->report_state(me->state); -} - -void IcebergOrder::merge_states(api::orderman::OrderState const &iceberg_state, - api::orderman::OrderState const &child_state, - api::orderman::OrderState *merged) { - auto child_order_fills = child_state.filled_quantity(); - auto child_order_avg_price = child_state.avg_price(); - auto child_order_last_price = child_state.last_price(); - - auto iceberg_fills = iceberg_state.filled_quantity(); - auto iceberg_avg_price = iceberg_state.avg_price(); - - *merged = iceberg_state; - merged->set_filled_quantity(child_order_fills + iceberg_fills); - merged->set_last_price(child_order_last_price); - merged->set_avg_price((child_order_fills * child_order_avg_price + - iceberg_fills * iceberg_avg_price) / - (child_order_fills + iceberg_fills)); -} - -void IcebergOrder::send_next_child_order() { - bts_assert(me->state.quantity() > me->state.filled_quantity()); - - auto remaining = me->state.quantity() - me->state.filled_quantity(); - auto to_send = std::min(remaining, me->show_quantity.value()); - - me->child.order = me->child_builder.build(); - me->child.key = me->child.order.key(); - - LOG(OrderMan, Info, - "Iceberg order {} creating new child order {} with size " - "{} price {}. Filled {} so far out of {}", - key().value(), me->child.key.value(), to_send, me->state.price(), - me->state.filled_quantity(), me->state.quantity()); - - me->child.order.activate(Price(me->state.price()), Quantity(to_send), trace::CorID()); -} - -void IcebergOrder::on_child_order_update(OrderStateUpdateEvent const &ev) { - switch (me->state.status()) { - case ORDER_STATUS_WORKING: - if (ev.key == me->child.key) { - me->child.state = ev.rebuild_state(); - - switch (ev.status) { - - case ORDER_STATUS_WORKING: - case ORDER_STATUS_PENDING_WORKING: - // nothing to do but report new state - break; - - case ORDER_STATUS_COMPLETED: { - api::orderman::OrderState merged_state; - merge_states(me->state, me->child.state, &merged_state); - me->state = merged_state; - me->child.clear(); - if (me->state.quantity() > me->state.filled_quantity()) { - if (me->pause_between_orders) { - me->working_sub_status = WorkingSubStatus::PAUSED; - me->start_of_pause = Timer::now(); - } else - send_next_child_order(); - } else - transition(ORDER_STATUS_COMPLETED); - break; - } - - case ORDER_STATUS_CANCELED: - LOG(OrderMan, Info, - "Unexpected cancel of child {} in Iceberg Order {}. Canceling " - "parent", - ev.key.value(), key().value()); - transition(ORDER_STATUS_CANCELED); - break; - - case ORDER_STATUS_DISCONNECTED: - case ORDER_STATUS_REJECTED_BY_SPARK: - case ORDER_STATUS_ERROR: - me->child.clear(); - transition(ORDER_STATUS_ERROR, "Unexpected child order state"); - break; - - case ORDER_STATUS_INACTIVE: - case OrderStatus_INT_MIN_SENTINEL_DO_NOT_USE_: - case OrderStatus_INT_MAX_SENTINEL_DO_NOT_USE_: - bts_assert(false); - break; - } - - } else { - LOG(OrderMan, Info, - "Iceberg order {} received update for non active child order {}." - "update state = {}", - key().value(), me->child.key.value(), - utils::pb::to_string(ev.rebuild_state())); - } - break; - - case ORDER_STATUS_CANCELED: - case ORDER_STATUS_ERROR: - case ORDER_STATUS_DISCONNECTED: - case ORDER_STATUS_COMPLETED: - break; - - case ORDER_STATUS_PENDING_WORKING: - case ORDER_STATUS_REJECTED_BY_SPARK: - case ORDER_STATUS_INACTIVE: - case OrderStatus_INT_MIN_SENTINEL_DO_NOT_USE_: - case OrderStatus_INT_MAX_SENTINEL_DO_NOT_USE_: - bts_assert(false); - break; - } - report_state(); -} - -void IcebergOrder::on_time(mercury::TimerEvent const &t) { - bts_assert(me->pause_between_orders); - if (sec_diff(t.ts, me->start_of_pause) >= me->pause_between_orders && - me->state.status() == ORDER_STATUS_WORKING && - me->working_sub_status == WorkingSubStatus::PAUSED) { - me->working_sub_status = WorkingSubStatus::WORKING; - send_next_child_order(); - } -} - -} // namespace orderman -} // namespace bts diff --git a/src/lib/orderman/orders/IcebergOrder.h b/src/lib/orderman/orders/IcebergOrder.h deleted file mode 100644 index c0b3f8ceb..000000000 --- a/src/lib/orderman/orders/IcebergOrder.h +++ /dev/null @@ -1,47 +0,0 @@ -#pragma once - -#include -#include "lib/orderman/orders/Order.h" -#include "lib/api/services/OrderService.server.pb.h" - -namespace bts { -namespace mercury {class TimerEvent;} -namespace orderman { - -class OrderStateUpdateEvent; - -class IcebergOrder : public Order -{ -public: - IcebergOrder(); - ~IcebergOrder(); - api::orderman::OrderDefinition const&definition() const override; - void on_init_new(api::orderman::OrderDefinition const&, - const PreActivationOrderServices&) override; - void on_init_recovered(api::orderman::OrderRecord const&, - const PreActivationOrderServices &) override; - void on_activate(Price,Quantity,OrderServices &, trace::CorID const&) override ; - void on_update(Price , Quantity,trace::CorID const&) override ; - void on_crack(trace::CorID const&) override ; - void on_cancel(trace::CorID const&) override ; - -private: - void report_state(); - void send_next_child_order(); - - void merge_states(api::orderman::OrderState const &iceberg_state, - api::orderman::OrderState const &child_state, - api::orderman::OrderState *merged); - - void on_child_order_update(OrderStateUpdateEvent const&); - void transition(api::orderman::OrderStatus new_state,std::string const&msg); - void transition(api::orderman::OrderStatus new_state); - void on_time (mercury::TimerEvent const&); - - enum class WorkingSubStatus; - struct ActiveChild; - struct PImpl; - std::unique_ptr me; -}; - -}} diff --git a/src/lib/orderman/orders/NativeOrder.cpp b/src/lib/orderman/orders/NativeOrder.cpp index ae7d39416..2103fd02f 100644 --- a/src/lib/orderman/orders/NativeOrder.cpp +++ b/src/lib/orderman/orders/NativeOrder.cpp @@ -11,7 +11,6 @@ #include "lib/orderman/orderman_utils/fix_order_codec.h" #include "lib/orderman/orders/PreActivationOrderServices.h" #include "lib/orderman/securities/ISecurityDB.h" -#include "lib/tracing/bts_trace.h" #include "lib/utils/PBUtils.h" #include "lib/utils/bts_chrono.h" @@ -31,7 +30,9 @@ struct NativeOrder::PImpl { PImpl() : services(nullptr), session_services(), sec(nullptr), previous_position_contribution(0), definition(), state(), - price_encoding_precision(7), received_exchanged_order_id(false) {} + price_encoding_precision(7), exchange_order_id() { + exchange_order_id.reserve(100); + } OrderServices *services; SessionServices *session_services; @@ -42,7 +43,7 @@ struct NativeOrder::PImpl { OrderDefinition definition; OrderState state; int price_encoding_precision; - bool received_exchanged_order_id; + std::string exchange_order_id; jetfix::FIXFragment update_encoding; jetfix::FIXFragment::Bookmark update_price_bm; @@ -62,6 +63,9 @@ struct NativeOrder::PImpl { OrderServices::ExeReportSubID exe_report_sid; OrderServices::CancelRejectSubID cancel_reject_sid; + + bool buffered_cancel = false; + std::optional> buffered_update; }; NativeOrder::NativeOrder() : me(new PImpl()) {} @@ -162,8 +166,10 @@ void NativeOrder::on_init_recovered(OrderRecord const &rec, // if we made it this far we are good. init_fix(); - if (me->state.status() != ORDER_STATUS_PENDING_WORKING) + if (me->state.status() != ORDER_STATUS_PENDING_WORKING) { + me->exchange_order_id = native_state.exchange_order_id(); add_exchange_order_id_to_fix(); + } return; } @@ -182,8 +188,9 @@ void NativeOrder::on_init_recovered(OrderRecord const &rec, } } -void NativeOrder::on_init_from_exe_report( - ExecutionReport const &er, const PreActivationOrderServices &os) { +api::orderman::OrderDefinition +NativeOrder::on_init_from_exe_report(ExecutionReport const &er, + const PreActivationOrderServices &os) { auto k = er.order_key; OrderRecord orecord; @@ -196,7 +203,8 @@ void NativeOrder::on_init_from_exe_report( auto sec = os.sec_db.resolve(SecurityKey(def.security_key())); auto rev_rec = os.order_router.get_reverse_routing_record( - er.cfg->name(), to_str(er.operator_id), to_str(er.account_name), sec); + er.cfg->name(), to_trim_str(er.operator_id), + to_trim_str(er.account_name), sec); if (rev_rec.ok) { def.set_user(rev_rec.user); @@ -206,7 +214,7 @@ void NativeOrder::on_init_from_exe_report( } else { LOG(OrderMan, Error, "Could not recover account and user information from order {}" - "The following information is available: {}. ", + ". The following information is available: {}. ", k.value(), rev_rec.error_msg); def.set_user(""); def.set_user_id(0); @@ -259,27 +267,52 @@ void NativeOrder::on_init_from_exe_report( } auto &native_state = get_native_state(state); - auto ts = to_trim_str(er.exchange_order_id.value()); - native_state.set_exchange_order_id(std::string(ts.first, ts.second)); + native_state.set_exchange_order_id(to_trim_str(er.exchange_order_id)); native_state.set_last_msg_seq_num(er.msg_seq_num); native_state.set_native_type(er.order_type); auto &rr = *native_state.mutable_routing_record(); rr.set_session(er.cfg->name()); - rr.set_account(to_str(er.account_name)); - rr.set_operator_id(to_str(er.operator_id)); + rr.set_account(to_trim_str(er.account_name)); + rr.set_operator_id(to_trim_str(er.operator_id)); rr.set_cti_code(CTICode(er.cfg->cti_code()[0])); rr.set_customer_or_firm(CustomerOrFirm(er.cfg->customer_or_firm())); - + rr.set_location(er.cfg->sender_locationid()); on_init_recovered(orecord, os); + return orecord.def(); } NativeOrder::~NativeOrder() {} -bool NativeOrder::_on_activate(log::Level reject_level, - log::Level transition_level, Price p, Quantity q, - bts::orderman::OrderServices &services) { +void NativeOrder::warm_up_activate(OrderServicesData &data, + OrderServices &services) { + bts_assert(!me->services); + me->services = &services; + init_order_services(data, services); + + // save these so we can re-instate them after we are done with the warmup + auto before_state = me->state.status(); + auto before_msg = me->state.last_msg(); + + _on_activate(NoLog, NoLog, Price(0), Quantity(0), services); + + // undo warm up side effects + me->state.set_status(before_state); + me->state.set_last_msg(before_msg); + + me->services->unsubscribe_from_exe_report(*me->session_services, + me->exe_report_sid); + me->services->unsubscribe_from_cancel_reject(*me->session_services, + me->cancel_reject_sid); + me->services->unsubscribe_from_gateway_status(*me->session_services); + me->services = nullptr; +} + +OrderOpResult +NativeOrder::_on_activate(log::Level reject_level, log::Level transition_level, + Price p, Quantity q, + bts::orderman::OrderServices &services) { me->state.set_price(p.value()); me->state.set_quantity(q.value()); me->state.set_filled_quantity(0); @@ -297,9 +330,9 @@ bool NativeOrder::_on_activate(log::Level reject_level, "Attempt to send order to a disconnected gateway. " "Dropping order {}", key().value()); - transition(transition_level, ORDER_STATUS_REJECTED_BY_SPARK, - "Exchange gateway is down"); - return false; + auto msg = "Exchange gateway is down"; + transition(transition_level, ORDER_STATUS_REJECTED_BY_SPARK, msg); + return OrderOpResult{ORDER_ERROR_GATEWAY_NOT_READY, msg}; } // can we trade? @@ -313,9 +346,9 @@ bool NativeOrder::_on_activate(log::Level reject_level, me->definition.user(), me->definition.account(), lqr.error_msg, key().value()); - transition(transition_level, ORDER_STATUS_REJECTED_BY_SPARK, - fmt::format("Unauthorized order: {}", lqr.error_msg)); - return false; + auto msg = fmt::format("Unauthorized order: {}", lqr.error_msg); + transition(transition_level, ORDER_STATUS_REJECTED_BY_SPARK, msg); + return OrderOpResult{ORDER_ERROR_UNAUTHORIZED, msg}; } // can we trade this security, with this size? @@ -330,9 +363,9 @@ bool NativeOrder::_on_activate(log::Level reject_level, me->definition.user(), me->definition.account(), lqr.error_msg, key().value()); - transition(transition_level, ORDER_STATUS_REJECTED_BY_SPARK, - fmt::format("Order would breach limit: {}", lqr.error_msg)); - return false; + auto msg = fmt::format("Order would breach limit: {}", lqr.error_msg); + transition(transition_level, ORDER_STATUS_REJECTED_BY_SPARK, msg); + return OrderOpResult{ORDER_ERROR_LIMIT_BREACH, msg}; } // are we under the messaging threshold? @@ -341,9 +374,9 @@ bool NativeOrder::_on_activate(log::Level reject_level, "New order would cause breach of messaging " "limits. Dropping order {}", key().value()); - transition(transition_level, ORDER_STATUS_REJECTED_BY_SPARK, - "Messaging threshold breached"); - return false; + auto msg = "Messaging threshold breached"; + transition(transition_level, ORDER_STATUS_REJECTED_BY_SPARK, msg); + return OrderOpResult(ORDER_ERROR_MESSAGING_LIMIT_BREACH, msg); } // if we are here we are good. @@ -382,58 +415,43 @@ bool NativeOrder::_on_activate(log::Level reject_level, auto const &ts = services.get_time_str(); me->create_transact_time_bm = encoding.overwrite( me->create_transact_time_bm, &ts.value()[0], ts.value().size()); - return true; + return OrderOpResult{}; } -void NativeOrder::warm_up_activate(OrderServicesData &data, - OrderServices &services) { +OrderOpResult NativeOrder::on_activate(Price p, Quantity q, + bts::orderman::OrderServices &services) { bts_assert(!me->services); me->services = &services; - init_order_services(data, services); - - // save these so we can re-instate them after we are done with the warmup - auto before_state = me->state.status(); - auto before_msg = me->state.last_msg(); - - _on_activate(NoLog, NoLog, Price(0), Quantity(0), services); - - // undo warm up side effects - me->services->unsubscribe_from_exe_report(*me->session_services, - me->exe_report_sid); - me->services->unsubscribe_from_cancel_reject(*me->session_services, - me->cancel_reject_sid); - me->services->unsubscribe_from_gateway_status(*me->session_services); - me->services = nullptr; - me->state.set_status(before_state); - me->state.set_last_msg(before_msg); -} - -void NativeOrder::on_activate(Price p, Quantity q, - bts::orderman::OrderServices &services, - trace::CorID const &trace) { - - bts_assert(!me->services); - me->services = &services; - + auto result = OrderOpResult{}; switch (me->state.status()) { + case ORDER_STATUS_INACTIVE: { auto scoped_log = - services.log_scope(trace, "NativeOrder::on_activate", key().value()); + services.log_scope("NativeOrder::on_activate", key().value()); // this is a brand new order - if (_on_activate(Warn, Info, p, q, services)) { + + result = _on_activate(Warn, Info, p, q, services); + if (result.ok()) { me->services->queue_fix(*me->session_services, jetfix::MessageTypes::NewOrderSingle, - me->create_encoding, trace); + me->create_encoding); me->services->governor(*me->session_services).record_sent(); me->state.set_status(ORDER_STATUS_PENDING_WORKING); LOG(OrderMan, Info, "Sent new order with key {} to gateway", key().value()); - // early return so we skip the expensive report_state() call - return; - }} + + // Early return so we skip the expensive report_state() + // call. It is OK to spkip it because we are bound to report + // our state once the excange aknowledges the order. + return OrderOpResult{}; + } + + // When the order fails its limits checks we fall through the + // switch to report the error state at the end of this function break; + } // all cases below are for orders recovered from disk case ORDER_STATUS_WORKING: @@ -449,8 +467,11 @@ void NativeOrder::on_activate(Price p, Quantity q, *me->session_services, [this](auto const &gw) { this->on_gateway_status(gw); }); - if (!me->services->is_gateway_connected(*me->session_services)) + if (!me->services->is_gateway_connected(*me->session_services)) { + result.error = ORDER_ERROR_GATEWAY_NOT_READY; + result.error_msg = "Gateway is disconnected"; transition(ORDER_STATUS_DISCONNECTED); + } break; case ORDER_STATUS_DISCONNECTED: @@ -496,11 +517,13 @@ void NativeOrder::on_activate(Price p, Quantity q, break; } report_state(); + return result; } -void NativeOrder::on_update(Price p, Quantity q, trace::CorID const &trace) { +OrderOpResult NativeOrder::on_update(Price p, Quantity q) { auto scoped_log = - me->services->log_scope(trace, "NativeOrder::on_update", key().value()); + me->services->log_scope("NativeOrder::on_update", key().value()); + auto result = OrderOpResult{}; switch (me->state.status()) { @@ -528,12 +551,16 @@ void NativeOrder::on_update(Price p, Quantity q, trace::CorID const &trace) { "Order update failed due to limit breach. Order: {} Msg: {}", key().value(), lqr.error_msg); + // if we are not being driven by an algo we just signal the + // error but keep running. otherwise we stop. if (parent_key() == null_order_key()) transition(me->state.status(), msg); else { me->state.set_last_msg(msg); - on_cancel(trace); + on_cancel(); } + result.error = api::orderman::ORDER_ERROR_LIMIT_BREACH; + result.error_msg = lqr.error_msg; break; } @@ -543,12 +570,17 @@ void NativeOrder::on_update(Price p, Quantity q, trace::CorID const &trace) { "Cannot update order {} because of messaging limits. ", key().value()); auto msg = "Messaging threshold breached"; + + // if we are not being driven by an algo we just signal the + // error but keep running. otherwise we stop. if (parent_key() == null_order_key()) transition(me->state.status(), msg); else { me->state.set_last_msg(msg); - on_cancel(trace); + on_cancel(); } + result.error = api::orderman::ORDER_ERROR_MESSAGING_LIMIT_BREACH; + result.error_msg = msg; break; } @@ -567,7 +599,7 @@ void NativeOrder::on_update(Price p, Quantity q, trace::CorID const &trace) { me->services->queue_fix(*me->session_services, jetfix::MessageTypes::CancelReplace, - me->update_encoding, trace); + me->update_encoding); me->services->governor(*me->session_services).record_sent(); update_working_position(); @@ -575,16 +607,21 @@ void NativeOrder::on_update(Price p, Quantity q, trace::CorID const &trace) { me->state.set_last_msg(""); // early return so we skip report_state (for speed) - return; + return OrderOpResult{}; } case ORDER_STATUS_DISCONNECTED: case ORDER_STATUS_PENDING_WORKING: + LOG(OrderMan, Warn, + "Cannot apply update to order {}. Update: {}@{}. Buffering", + key().value(), q.value(), p.value()); + me->buffered_update.emplace(p, q); + break; + case ORDER_STATUS_REJECTED_BY_SPARK: case ORDER_STATUS_COMPLETED: case ORDER_STATUS_CANCELED: case ORDER_STATUS_ERROR: - transition(me->state.status(), "Cannot update order"); break; case ORDER_STATUS_INACTIVE: @@ -594,13 +631,75 @@ void NativeOrder::on_update(Price p, Quantity q, trace::CorID const &trace) { break; } report_state(); + return result; } -void NativeOrder::on_crack(trace::CorID const &) {} +OrderOpResult NativeOrder::on_update(api::orderman::Update const &update) { + return on_update(Price(update.price()), Quantity(update.quantity())); +} -void NativeOrder::on_cancel(trace::CorID const &trace) { +OrderOpResult NativeOrder::on_detach() { return OrderOpResult{}; } + +void NativeOrder::on_attached( + api::orderman::OrderDefinition const &new_parent) { + switch (me->state.status()) { + + case ORDER_STATUS_PENDING_WORKING: + case ORDER_STATUS_DISCONNECTED: + case ORDER_STATUS_WORKING: { + LOG(OrderMan, Info, "Native order {} has been attached to by {}", + key().value(), utils::pb::to_string(new_parent)); + + // Update FIX tags to reflect new parent's information + auto rq = me->services->route_order(UserID(new_parent.user_id()), + AccountID(new_parent.account_id()), + *me->sec); + + if (!rq.has_route) { + auto msg = fmt::format("Cannot update order routing information: {}", + rq.error_msg); + transition(me->state.status(), msg); + report_state(); + return; + } + + auto &native_state = get_native_state(me->state); + *native_state.mutable_routing_record() = rq.routing_record; + init_fix(); + if (has_exchange_order_id()) + add_exchange_order_id_to_fix(); + + // Update user, account and manual order indicator based on new parent + me->definition.set_manual_order_indicator( + api::orderman::ManualOrderIndicator::MANUAL_ORDER_INDICATOR_NO); + me->definition.set_user(new_parent.user()); + me->definition.set_user_id(new_parent.user_id()); + me->definition.set_account(new_parent.account()); + me->definition.set_account_id(new_parent.account_id()); + me->services->report_definition(me->definition); + report_state(); + break; + } + + case ORDER_STATUS_CANCELED: + case ORDER_STATUS_REJECTED_BY_SPARK: + case ORDER_STATUS_COMPLETED: + case ORDER_STATUS_ERROR: + break; + + case ORDER_STATUS_INACTIVE: + case OrderStatus_INT_MIN_SENTINEL_DO_NOT_USE_: + case OrderStatus_INT_MAX_SENTINEL_DO_NOT_USE_: + bts_assert(false); + break; + } +} + +OrderOpResult NativeOrder::on_cancel() { auto scoped_log = - me->services->log_scope(trace, "NativeOrder::on_cancel", key().value()); + me->services->log_scope("NativeOrder::on_cancel", key().value()); + auto result = OrderOpResult{}; + switch (me->state.status()) { case ORDER_STATUS_WORKING: { @@ -610,21 +709,39 @@ void NativeOrder::on_cancel(trace::CorID const &trace) { me->cancel_transact_time_bm, &ts.value()[0], ts.value().size()); me->services->queue_fix(*me->session_services, - jetfix::MessageTypes::Cancel, me->cancel_encoding, - trace); + jetfix::MessageTypes::Cancel, + me->cancel_encoding); break; } - case ORDER_STATUS_DISCONNECTED: - case ORDER_STATUS_PENDING_WORKING: + case ORDER_STATUS_CANCELED: case ORDER_STATUS_REJECTED_BY_SPARK: case ORDER_STATUS_COMPLETED: - case ORDER_STATUS_CANCELED: case ORDER_STATUS_ERROR: - transition(me->state.status(), "Cannot cancel order"); break; + case ORDER_STATUS_PENDING_WORKING: { + me->buffered_cancel = true; + LOG(OrderMan, Warn, + "Cannot cancel order {} while in the pending working state. " + "Buffering cancel", + key().value()); + break; + } + + case ORDER_STATUS_DISCONNECTED: { + me->buffered_cancel = true; + LOG(OrderMan, Warn, + "Cannot cancel order {} while in the disconnected state. Buffering " + "cancel", + key().value()); + auto msg = "Order will be canceled when re-connected"; + result.error = ORDER_ERROR_GATEWAY_NOT_READY; + result.error_msg = msg; + transition(me->state.status(), msg); + break; + } case ORDER_STATUS_INACTIVE: case OrderStatus_INT_MIN_SENTINEL_DO_NOT_USE_: case OrderStatus_INT_MAX_SENTINEL_DO_NOT_USE_: @@ -632,6 +749,7 @@ void NativeOrder::on_cancel(trace::CorID const &trace) { break; } report_state(); + return result; } bool NativeOrder::is_old_exe_report( @@ -657,8 +775,8 @@ bool NativeOrder::is_old_exe_report( } void NativeOrder::on_exe_report(const NewExecutionReportEvent &er) { - auto scoped_log = me->services->log_scope( - er.trace, "NativeOrder::on_exe_report", key().value()); + auto scoped_log = + me->services->log_scope("NativeOrder::on_exe_report", key().value()); auto &state = me->state; auto &native_state = get_native_state(state); @@ -710,10 +828,10 @@ void NativeOrder::on_exe_report(const NewExecutionReportEvent &er) { native_state.set_native_status(er.data->order_status); native_state.set_native_type(er.data->order_type); - bool got_first_exchange_order_id = !me->received_exchanged_order_id; + bool got_first_exchange_order_id = !has_exchange_order_id(); if (got_first_exchange_order_id) { - auto ts = to_trim_str(er.data->exchange_order_id.value()); - native_state.set_exchange_order_id(std::string(ts.first, ts.second)); + me->exchange_order_id = to_trim_str(er.data->exchange_order_id); + native_state.set_exchange_order_id(me->exchange_order_id); add_exchange_order_id_to_fix(); } @@ -737,8 +855,27 @@ void NativeOrder::on_exe_report(const NewExecutionReportEvent &er) { if (external_status == ORDER_STATUS_WORKING && !me->services->is_gateway_connected(*me->session_services)) transition(ORDER_STATUS_DISCONNECTED); - else + else { transition(external_status); + if (external_status == ORDER_STATUS_WORKING) { + if (me->buffered_cancel) { + LOG(OrderMan, Warn, + "Applying buffered cancel to order {}, on first ack", + key().value()); + on_cancel(); + } + else if (me->buffered_update.has_value()) { + auto [p, q] = me->buffered_update.value(); + me->buffered_update.reset(); + LOG(OrderMan, Warn, + "Applying buffered update ({}@{}) to order {}, on " + "first ack", + q.value(),p.value(), + key().value()); + on_update(p, q); + } + } + } break; case ORDER_STATUS_WORKING: @@ -753,7 +890,7 @@ void NativeOrder::on_exe_report(const NewExecutionReportEvent &er) { bts_assert(false); break; } - report_state(er.trace); + report_state(); // we only need the exhange order id and the routing record // reported once, since they are both immutable, so we clear them @@ -801,6 +938,24 @@ void NativeOrder::on_gateway_status(const GatewayStatusChangeEvent &ev) { case ORDER_STATUS_DISCONNECTED: { auto const &native_state = get_native_state(me->state); transition(map_external_status(native_state.native_status())); + + if (me->state.status() == ORDER_STATUS_WORKING) { + if (me->buffered_cancel) { + LOG(OrderMan, Warn, + "Applying buffered cancel to order {}, on re-connection", + key().value()); + on_cancel(); + } else if (me->buffered_update.has_value()) { + auto [p, q] = me->buffered_update.value(); + me->buffered_update.reset(); + LOG(OrderMan, Warn, + "Applying buffered update ({}@{}) to order {}, on " + "re-connection", + q.value(),p.value(), + key().value()); + on_update(p, q); + } + } break; } case ORDER_STATUS_INACTIVE: @@ -855,14 +1010,19 @@ void NativeOrder::update_working_position() { key().value(), me->definition.security_key()); } -void NativeOrder::report_state(trace::CorID const &trace) { +void NativeOrder::report_state() { update_working_position(); - me->services->report_state(me->state, trace); + me->services->report_state(me->state); } void NativeOrder::init_fix() { bts_assert(me->sec); + using namespace jetfix; + me->create_encoding = FIXFragment{}; + me->update_encoding = FIXFragment{}; + me->cancel_encoding = FIXFragment{}; + auto const &def = me->definition; auto const &sec = *me->sec; auto const &rr = get_native_state(me->state).routing_record(); @@ -1004,12 +1164,8 @@ void NativeOrder::init_fix() { void NativeOrder::add_exchange_order_id_to_fix() { bts_assert(has_exchange_order_id()); - auto &state = get_native_state(me->state); - auto &eoid = state.exchange_order_id(); - - me->update_encoding.add(eoid); - me->cancel_encoding.add(eoid); - me->received_exchanged_order_id = true; + me->update_encoding.add(me->exchange_order_id); + me->cancel_encoding.add(me->exchange_order_id); } OrderStatus map_external_status(NativeOrderStatus status) { @@ -1050,20 +1206,7 @@ OrderStatus map_external_status(NativeOrderStatus status) { } bool NativeOrder::has_exchange_order_id() { - return get_native_state(me->state).exchange_order_id().size(); -} - -void NativeOrder::transition(log::Level level, - api::orderman::OrderStatus new_status, - std::string const &msg) { - auto const &from = OrderStatus_Name(me->state.status()); - auto const &to = OrderStatus_Name(new_status); - if (me->state.status() != new_status) { - LOG(OrderMan, level, "Transitioning order {} from {} to {}. Msg: {}", - key().value(), from, to, msg); - } - me->state.set_status(new_status); - me->state.set_last_msg(msg); + return me->exchange_order_id.size(); } void NativeOrder::transition(api::orderman::OrderStatus new_status, @@ -1071,10 +1214,22 @@ void NativeOrder::transition(api::orderman::OrderStatus new_status, transition(Info, new_status, msg); } +void NativeOrder::transition(log::Level level, + api::orderman::OrderStatus new_status, + std::string const &msg) { + auto const &from = OrderStatus_Name(me->state.status()); + auto const &to = OrderStatus_Name(new_status); + if (from != to) + LOG(OrderMan, level, "Transitioning order {} from {} to {}. Msg: {}", + key().value(), from, to, msg); + me->state.set_status(new_status); + me->state.set_last_msg(msg); +} + void NativeOrder::transition(api::orderman::OrderStatus new_status) { auto const &from = OrderStatus_Name(me->state.status()); auto const &to = OrderStatus_Name(new_status); - if (me->state.status() != new_status) + if (from != to) LOG(OrderMan, Info, "Transitioning order {} from {} to {}", key().value(), from, to); else diff --git a/src/lib/orderman/orders/NativeOrder.h b/src/lib/orderman/orders/NativeOrder.h index 616042a8c..8f6f0fbc0 100644 --- a/src/lib/orderman/orders/NativeOrder.h +++ b/src/lib/orderman/orders/NativeOrder.h @@ -18,19 +18,22 @@ class NativeOrder : public Order { NativeOrder(); ~NativeOrder() override; - api::orderman::OrderDefinition const &definition() const override; + api::orderman::OrderDefinition const &definition() const; void on_init_new(api::orderman::OrderDefinition const &, const PreActivationOrderServices &) override; void on_init_recovered(api::orderman::OrderRecord const &, const PreActivationOrderServices &) override; - void on_activate(Price, Quantity, OrderServices &, - trace::CorID const &) override; - void on_update(Price, Quantity, trace::CorID const &) override; - void on_crack(trace::CorID const &) override; - void on_cancel(trace::CorID const &) override; - void on_init_from_exe_report(ExecutionReport const &, - const PreActivationOrderServices &); + OrderOpResult on_activate(Price, Quantity, OrderServices &) override; + OrderOpResult on_update(Price, Quantity) override; + OrderOpResult on_update(api::orderman::Update const &) override; + OrderOpResult on_detach() override; + OrderOpResult on_cancel() override; + void on_attached(api::orderman::OrderDefinition const &new_parent) override; + + api::orderman::OrderDefinition + on_init_from_exe_report(ExecutionReport const &, + const PreActivationOrderServices &); protected: void warm_up_activate(OrderServicesData &, OrderServices &) override; @@ -38,18 +41,18 @@ class NativeOrder : public Order { private: struct PImpl; std::unique_ptr me; - - bool _on_activate(log::Level reject_level, log::Level transition_level, - Price, Quantity, bts::orderman::OrderServices &); void on_exe_report(const NewExecutionReportEvent &); void on_cancel_reject(const CancelRejectEvent &); void on_gateway_status(const GatewayStatusChangeEvent &); - void report_state(trace::CorID const &trace = trace::CorID()); - + void report_state(); + OrderOpResult _on_activate(log::Level reject_level, + log::Level transition_level, Price p, Quantity q, + bts::orderman::OrderServices &services); void init_fix(); void add_exchange_order_id_to_fix(); - void transition(log::Level level, api::orderman::OrderStatus new_state, + void transition(log::Level, + api::orderman::OrderStatus new_state, std::string const &msg); void transition(api::orderman::OrderStatus new_state, std::string const &msg); diff --git a/src/lib/orderman/orders/Order.cpp b/src/lib/orderman/orders/Order.cpp index a25ba3779..98db21101 100644 --- a/src/lib/orderman/orders/Order.cpp +++ b/src/lib/orderman/orders/Order.cpp @@ -5,21 +5,46 @@ namespace bts { namespace orderman { Order::Order() -{ - _services = std::make_unique(*this); -} + : _key(null_order_key()), _parent_key(null_order_key()), _def(), + _status(api::orderman::ORDER_STATUS_INACTIVE), + _services(std::make_unique(*this)) {} -void Order::init_order_services(OrderServicesData &osd) -{ +void Order::init_order_services(OrderServicesData &osd) { _services->init(osd); } -void Order::init_order_services(OrderServicesData &osd,OrderServices &parent) -{ - _services->init(osd,parent); +void Order::init_order_services(OrderServicesData &osd, OrderServices &parent) { + _services->init(osd, parent); } Order::~Order() {} +void Order::set_def(api::orderman::OrderDefinition const &def) { + _def = std::make_shared(def); +} + +std::shared_ptr const & +Order::def() const { + return _def; +} + +void Order::set_status(api::orderman::OrderStatus status) { _status = status; } + +api::orderman::OrderStatus Order::status() const { return _status; } + +void Order::set_parent_key(OrderKey parent_key) { _parent_key = parent_key; } + +OrderOpResult Order::on_update(api::orderman::Update const &) { + return OrderOpResult{api::orderman::ORDER_ERROR_INVALID_OP, + "Not implemented"}; +} + +OrderOpResult Order::on_detach() { + return OrderOpResult{api::orderman::ORDER_ERROR_INVALID_OP, + "Not implemented"}; +} + +void Order::on_attached(api::orderman::OrderDefinition const &) {} + } // namespace orderman } // namespace bts diff --git a/src/lib/orderman/orders/Order.h b/src/lib/orderman/orders/Order.h index 32a58ebb1..f9cbb720f 100644 --- a/src/lib/orderman/orders/Order.h +++ b/src/lib/orderman/orders/Order.h @@ -1,26 +1,30 @@ #pragma once #include "lib/orderman/orderman_utils/orderman_common.h" +#include "lib/orderman/orders/OrderOpResult.h" + #include // fwd namespace bts { -namespace trace {struct CorID;} +namespace trace { +struct CorID; +} namespace securities { class ISecurityDB; } namespace orderman { class IOrderFactory; class OrderServicesData; -} +} // namespace orderman namespace api { namespace orderman { class OrderDefinition; class OrderRecord; class OrderState; -} -} -} +} // namespace orderman +} // namespace api +} // namespace bts // end fwd namespace bts { @@ -28,6 +32,11 @@ namespace orderman { class PreActivationOrderServices; class OrderServices; +class ChildOrder; +using OrderOpCallback = std::function; +using AttachCallback = std::function; class Order { public: @@ -36,35 +45,54 @@ class Order { OrderKey key() const { return _key; } OrderKey parent_key() const { return _parent_key; } + std::shared_ptr const &def() const; - virtual api::orderman::OrderDefinition const &definition() const = 0; - - // construction - can be slow + // Construction, the order is not yet live and it may never + // be. This can be slow. virtual void on_init_new(api::orderman::OrderDefinition const &, const PreActivationOrderServices &) = 0; virtual void on_init_recovered(api::orderman::OrderRecord const &, const PreActivationOrderServices &) = 0; - // activation - cannot be slow - virtual void on_activate(Price, Quantity, OrderServices &, trace::CorID const&) = 0; + // Activation, the order is now live, these should be fast + virtual OrderOpResult on_activate(Price, Quantity, OrderServices &) = 0; - // order is running, maintenance - virtual void on_update(Price, Quantity, trace::CorID const&) = 0; - virtual void on_crack(trace::CorID const&) = 0; - virtual void on_cancel(trace::CorID const&) = 0; + // Order Updates, post activation + virtual OrderOpResult on_update(Price, Quantity) = 0; + virtual OrderOpResult on_update(api::orderman::Update const &); -protected: - virtual void warm_up_activate(OrderServicesData&,OrderServices&) {} + // Detach + virtual OrderOpResult on_detach(); + + // Cancel + virtual OrderOpResult on_cancel() = 0; + + // Order has been attached to + virtual void on_attached(api::orderman::OrderDefinition const &new_parent); + + protected: + virtual void warm_up_activate(OrderServicesData &, OrderServices &) {} void init_order_services(OrderServicesData &); - void init_order_services(OrderServicesData &,OrderServices &parent); + void init_order_services(OrderServicesData &, OrderServices &parent); private: OrderKey _key; OrderKey _parent_key; + std::shared_ptr _def; + api::orderman::OrderStatus _status; std::unique_ptr _services; + + void set_def(api::orderman::OrderDefinition const &); + + void set_status(api::orderman::OrderStatus status); + api::orderman::OrderStatus status() const; + + void set_parent_key(OrderKey parent_key); + friend class OrderFactory; friend class OrderManager; friend class OrderServices; + friend class ChildOrder; }; -} -} +} // namespace orderman +} // namespace bts diff --git a/src/lib/orderman/orders/OrderOpResult.h b/src/lib/orderman/orders/OrderOpResult.h new file mode 100644 index 000000000..7905c1152 --- /dev/null +++ b/src/lib/orderman/orders/OrderOpResult.h @@ -0,0 +1,25 @@ +#pragma once + +#include "lib/api/services/OrderService.pb.h" +#include + +namespace bts { +namespace orderman { + +struct OrderOpResult { + OrderOpResult() : error(api::orderman::ORDER_ERROR_OK), error_msg() {} + + OrderOpResult(api::orderman::OrderError e, std::string const &error_msg) + : error(e), error_msg(error_msg) {} + + OrderOpResult(api::orderman::OrderError e) : error(e), error_msg() {} + + bool ok() const {return error == api::orderman::ORDER_ERROR_OK;} + bool fail() const {return !ok();} + + api::orderman::OrderError error; + std::string error_msg; +}; + +} // namespace orderman +} // namespace bts diff --git a/src/lib/orderman/orders/TimeBoxOrder.cpp b/src/lib/orderman/orders/TimeBoxOrder.cpp index 8ad686489..4a36edc28 100644 --- a/src/lib/orderman/orders/TimeBoxOrder.cpp +++ b/src/lib/orderman/orders/TimeBoxOrder.cpp @@ -1,6 +1,7 @@ #include "TimeBoxOrder.h" #include "lib/orderman/actors/order_manager/OrderBuilder.h" #include "lib/utils/PBUtils.h" +#include "lib/orderman/orders/PreActivationOrderServices.h" #include namespace bts { @@ -43,7 +44,7 @@ void TimeBoxOrder::on_init_new(api::orderman::OrderDefinition const &def, *child_def.mutable_custom_def() = timebox_def.child(); if (me->start_time.seconds() > utils::pb::pb_now().seconds() && me->stop_time.seconds() > me->start_time.seconds()) { - me->child_builder = OrderBuilder(key(), child_def, services, 1); + me->child_builder = OrderBuilder(key(), child_def, services.order_factory, 1); transition(ORDER_STATUS_INACTIVE); } else { auto msg = fmt::format("Invalid time"); @@ -84,8 +85,8 @@ void TimeBoxOrder::on_init_recovered(api::orderman::OrderRecord const &rec, } } -void TimeBoxOrder::on_activate(Price p, Quantity q, OrderServices &services, - trace::CorID const &) { +OrderOpResult TimeBoxOrder::on_activate(Price p, Quantity q, + OrderServices &services) { bts_assert(!me->services); me->services = &services; me->child_builder.activate(services); @@ -121,9 +122,10 @@ void TimeBoxOrder::on_activate(Price p, Quantity q, OrderServices &services, break; } report_state(); + return OrderOpResult{}; } -void TimeBoxOrder::on_update(Price p, Quantity q, trace::CorID const &) { +OrderOpResult TimeBoxOrder::on_update(Price p, Quantity q) { LOG(OrderMan, Info, "Updating TimeBox Order {}", key().value()); switch (me->state.status()) { @@ -181,11 +183,14 @@ void TimeBoxOrder::on_update(Price p, Quantity q, trace::CorID const &) { break; } report_state(); + return OrderOpResult{}; } -void TimeBoxOrder::on_crack(trace::CorID const &) {} +OrderOpResult TimeBoxOrder::on_detach() { + return OrderOpResult{}; +} -void TimeBoxOrder::on_cancel(trace::CorID const &) { +OrderOpResult TimeBoxOrder::on_cancel() { LOG(OrderMan, Info, "Canceling TimeBox Order {}", key().value()); switch (me->state.status()) { @@ -240,6 +245,7 @@ void TimeBoxOrder::on_cancel(trace::CorID const &) { break; } report_state(); + return OrderOpResult{}; } void TimeBoxOrder::transition(api::orderman::OrderStatus new_status, diff --git a/src/lib/orderman/orders/TimeBoxOrder.h b/src/lib/orderman/orders/TimeBoxOrder.h index 9475a5a37..054c78b4c 100644 --- a/src/lib/orderman/orders/TimeBoxOrder.h +++ b/src/lib/orderman/orders/TimeBoxOrder.h @@ -14,15 +14,15 @@ class TimeBoxOrder : public Order public: TimeBoxOrder(); ~TimeBoxOrder(); - api::orderman::OrderDefinition const&definition() const override; + api::orderman::OrderDefinition const&definition() const ; void on_init_new(api::orderman::OrderDefinition const&, const PreActivationOrderServices&) override; void on_init_recovered(api::orderman::OrderRecord const&, const PreActivationOrderServices &) override; - void on_activate(Price,Quantity,OrderServices &, trace::CorID const&) override ; - void on_update(Price , Quantity,trace::CorID const&) override ; - void on_crack(trace::CorID const&) override ; - void on_cancel(trace::CorID const&) override ; + OrderOpResult on_activate(Price,Quantity,OrderServices &) override ; + OrderOpResult on_update(Price , Quantity) override ; + OrderOpResult on_detach() override ; + OrderOpResult on_cancel() override ; private: void report_state(); diff --git a/src/lib/orderman/orders/TriggerOrder.cpp b/src/lib/orderman/orders/TriggerOrder.cpp index 5b8f2cc5f..81741c7ce 100644 --- a/src/lib/orderman/orders/TriggerOrder.cpp +++ b/src/lib/orderman/orders/TriggerOrder.cpp @@ -6,6 +6,8 @@ #include "lib/orderman/orders/spreader_orders/spreader/SpreaderUtils.h" #include "lib/os/os.h" #include "lib/utils/PBUtils.h" +#include "lib/orderman/orders/PreActivationOrderServices.h" + #include #include @@ -100,8 +102,8 @@ void TriggerOrder::on_init_recovered(const api::orderman::OrderRecord &rec, break; } } -void TriggerOrder::on_activate(Price price, Quantity qty, - OrderServices &services, trace::CorID const &) { +OrderOpResult TriggerOrder::on_activate(Price price, Quantity qty, + OrderServices &services) { LOG(OrderMan, Info, "TriggerOrder::on_activate key:{} state:{} price:{} qty:{}", key(), _state, price, qty); @@ -116,9 +118,9 @@ void TriggerOrder::on_activate(Price price, Quantity qty, me->order_builder.activate(services); me->child_order = me->order_builder.build(); services.subscribe_to_child_updates( - [this](const OrderStateUpdateEvent &os) { - this->_on_child_order_update(os); - }); + [this](const OrderStateUpdateEvent &os) { + this->_on_child_order_update(os); + }); services.subscribe_to_book(SecurityKey(me->order_def.security_key()), [this](const BookUpdateEvent &bk_event) { this->_on_book_update(bk_event); @@ -138,9 +140,10 @@ void TriggerOrder::on_activate(Price price, Quantity qty, break; } } + return OrderOpResult{}; } // order price, qty change -void TriggerOrder::on_update(Price price, Quantity qty, trace::CorID const &) { +OrderOpResult TriggerOrder::on_update(Price price, Quantity qty) { LOG(OrderMan, Info, "TriggerOrder::on_update key:{} state:{} price:{} qty:{}", key(), _state, price, qty); @@ -165,11 +168,9 @@ void TriggerOrder::on_update(Price price, Quantity qty, trace::CorID const &) { case State::END: break; } + return OrderOpResult{}; } -void TriggerOrder::on_crack(trace::CorID const &) { - // not supported -} -void TriggerOrder::on_cancel(trace::CorID const &) { +OrderOpResult TriggerOrder::on_cancel() { LOG(OrderMan, Info, "TriggerOrder::on_cancel key:{} state:{}", key(), _state); me->cancel_mode = CancelMode::external; @@ -193,6 +194,7 @@ void TriggerOrder::on_cancel(trace::CorID const &) { case State::END: break; } + return OrderOpResult{}; } void TriggerOrder::_on_book_update(const BookUpdateEvent &b_event) { switch (_state) { @@ -314,7 +316,7 @@ bool TriggerOrder::_on_init_new(const api::orderman::OrderDefinition &order_def, child_order_def.set_security_key( trigger_order_def.trigger_action().security_id()); child_order_def.mutable_custom_def()->CopyFrom(trigger_order_def.child()); - me->order_builder = OrderBuilder(key(), child_order_def, pre_os); + me->order_builder = OrderBuilder(key(), child_order_def, pre_os.order_factory); const auto *sec_ptr = pre_os.sec_db.resolve(SecurityKey(order_def.security_key())); me->tick_size = std::min(sec_ptr->contract_spec().low_tick(), diff --git a/src/lib/orderman/orders/TriggerOrder.h b/src/lib/orderman/orders/TriggerOrder.h index a62c82cba..6c4de23ed 100644 --- a/src/lib/orderman/orders/TriggerOrder.h +++ b/src/lib/orderman/orders/TriggerOrder.h @@ -49,17 +49,15 @@ enum CancelMode{ public: TriggerOrder(); ~TriggerOrder(); - api::orderman::OrderDefinition const& definition() const override; + api::orderman::OrderDefinition const& definition() const ; void on_init_new(api::orderman::OrderDefinition const&, const PreActivationOrderServices&) override; void on_init_recovered(api::orderman::OrderRecord const&, const PreActivationOrderServices &) override; - void on_activate(Price, Quantity, - OrderServices&, - trace::CorID const&) override ; - void on_update(Price, Quantity, trace::CorID const&) override; - void on_crack(trace::CorID const&) override; - void on_cancel(trace::CorID const&) override; + OrderOpResult on_activate(Price, Quantity, + OrderServices&) override ; + OrderOpResult on_update(Price, Quantity) override; + OrderOpResult on_cancel() override; private: // callbacks from book and child order udpates void _on_book_update(const BookUpdateEvent&); diff --git a/src/lib/orderman/orders/algo/AlgoWrapperOrder.cpp b/src/lib/orderman/orders/algo/AlgoWrapperOrder.cpp new file mode 100644 index 000000000..b14e7c7ef --- /dev/null +++ b/src/lib/orderman/orders/algo/AlgoWrapperOrder.cpp @@ -0,0 +1,806 @@ +#include "lib/orderman/orders/algo/AlgoWrapperOrder.h" + +#include "lib/orderman/actors/order_manager/ChildOrder.h" +#include "lib/orderman/actors/order_manager/OrderBuilder.h" +#include "lib/orderman/actors/order_manager/OrderServices.h" +#include "lib/orderman/orderman_utils/orderman_utils.h" +#include "lib/orderman/orders/PreActivationOrderServices.h" +#include "lib/orderman/orders/algo/IAlgoOrder.h" +#include "lib/utils/bts_assert.h" + +#include +#include + +namespace bts { +namespace orderman { + +using namespace api::orderman; +template using Map = boost::container::flat_map; +enum class AlgoWrapperOrder::Status { INACTIVE, W_ATTACH, WORKING, COMPLETED }; + +class ChildTemplate { + public: + ChildTemplate() {} + + ChildTemplate(OrderKey parent_key, api::orderman::OrderDefinition const &def, + IOrderFactory *factory, size_t reserve_sz) + : builder(parent_key, def, *factory, reserve_sz) {} + + OrderBuilder builder; +}; + +struct AlgoWrapperOrder::ChildRecord { + ChildOrder order; + std::optional state; + bool is_subscribing = false; +}; + +struct AlgoWrapperOrder::PImpl { + using Edge = std::pair; + using Action = std::function; + + PImpl(std::unique_ptr &&algo) : algo(std::move(algo)) {} + + std::unique_ptr algo; + Status status = Status::INACTIVE; + OrderServices *services = nullptr; + OrderDefinition definition; + const api::Security *security; + OrderState const &state() const { return _state; } + + Map book_subs; + Map children; + bool has_timer_sub = false; + + bool is_state_dirty = false; + + Map transition_actions; + Map invariants; + securities::ISecurityDB const *security_db = nullptr; + IOrderFactory *order_factory = nullptr; + std::vector> child_templates; + OrderKey attach_target = null_order_key(); + + std::optional pending_update; + OrderStatus external_status() const { return _state.status(); } + + void set_external_status(OrderStatus s) { + is_state_dirty = true; + _state.set_status(s); + } + + void set_state(OrderState const &new_state) { + is_state_dirty = true; + _state = new_state; + } + + void set_last_msg(std::string const &msg) { + is_state_dirty = true; + _state.set_last_msg(msg); + } + + void set_price_quantity(Price p, Quantity q) { + is_state_dirty = true; + _state.set_price(p.value()); + _state.set_quantity(q.value()); + } + + void set_fill_quantities(Quantity total_fills, Price last_price, + Price avg_price) { + is_state_dirty = true; + _state.set_filled_quantity(total_fills.value()); + _state.set_last_price(last_price.value()); + _state.set_avg_price(avg_price.value()); + } + + private: + OrderState _state; +}; + +struct AlgoWrapperOrder::ReportStateGuard { + ReportStateGuard(AlgoWrapperOrder &owner) : owner(owner) {} + ~ReportStateGuard() { + if (owner.me->is_state_dirty) { + owner.me->is_state_dirty = false; + owner.me->services->report_state(owner.me->state()); + } + } + AlgoWrapperOrder &owner; +}; + +AlgoWrapperOrder::AlgoWrapperOrder(std::unique_ptr &&algo) + : me(new PImpl(std::move(algo))) { + setup_transitions(); +} +AlgoWrapperOrder::~AlgoWrapperOrder() {} + +// -------------------------------------------------------------------------------- +// Order +// -------------------------------------------------------------------------------- +void AlgoWrapperOrder::on_init_new(OrderDefinition const &def, + const PreActivationOrderServices &serv) { + bts_assert(def.has_custom_def()); + + // cache these so we can resolve securities and create order builders + me->security_db = &serv.sec_db; + me->order_factory = &serv.order_factory; + + // Save our order definition + me->definition = def; + + // If we are consuming the attachment we remove it from our definition so + // that derived orders can use our definition to create their children + // without triggering an attachment. + if (_is_attaching(me->definition)) { + if (can_consume_attachment(me->definition.custom_def().custom_case())) { + me->attach_target = OrderKey(me->definition.attach_target_order_key()); + me->definition.clear_attach_target_order_key(); + } + else { + terminate(ORDER_STATUS_REJECTED_BY_SPARK, "Algo does not support attachment"); + return; + } + } + + me->security = serv.sec_db.resolve(SecurityKey(def.security_key())); + if (me->security == nullptr) + terminate(ORDER_STATUS_REJECTED_BY_SPARK, "Unknown security"); + + auto result = me->algo->do_before_launch(*this); + if (result.fail()) + terminate(ORDER_STATUS_REJECTED_BY_SPARK, result.error_msg); +} + +void AlgoWrapperOrder::on_init_recovered( + OrderRecord const &rec, const PreActivationOrderServices &serv) { + auto const &def = rec.def(); + me->definition = def; + me->set_state(rec.state()); + me->security_db = &serv.sec_db; + me->order_factory = &serv.order_factory; + + // Infer internal status from persisted external status + switch (me->external_status()) { + + case ORDER_STATUS_WORKING: + case ORDER_STATUS_PENDING_WORKING: + terminate(ORDER_STATUS_ERROR, "System restarted with active algo order"); + return; + + // Terminal states + case ORDER_STATUS_ERROR: + case ORDER_STATUS_REJECTED_BY_SPARK: + case ORDER_STATUS_COMPLETED: + case ORDER_STATUS_CANCELED: + terminate(rec.state().status(), rec.state().last_msg()); + break; + + // It should not be possible to reach these + case ORDER_STATUS_DISCONNECTED: + case ORDER_STATUS_INACTIVE: + case OrderStatus_INT_MIN_SENTINEL_DO_NOT_USE_: + case OrderStatus_INT_MAX_SENTINEL_DO_NOT_USE_: + bts_assert(false); + break; + } +} + +OrderOpResult AlgoWrapperOrder::on_activate(Price p, Quantity q, + OrderServices &services) { + ReportStateGuard _(*this); + + bts_assert(!me->services); + me->services = &services; + me->security_db = &services.sec_db(); + me->order_factory = &services.order_factory(); + + switch (me->status) { + + case Status::INACTIVE: { + me->services->subscribe_to_child_updates([this](auto const &u) { + this->on_child_order_update(u.key, u.quick_rebuild_state()); + }); + me->set_external_status(ORDER_STATUS_WORKING); + me->set_price_quantity(p, q); + for (auto &ct : me->child_templates) + ct->builder.activate(*me->services); + if (q.value() == 0) + terminate(ORDER_STATUS_COMPLETED); + else if (is_attaching()) + transition(Status::W_ATTACH); + else + transition(Status::WORKING); + return {}; + } + case Status::COMPLETED: + return {}; + + case Status::W_ATTACH: + case Status::WORKING: + bts_assert(false); + } + + bts_assert(false); + return {}; +} + +OrderOpResult AlgoWrapperOrder::on_update(Update const &update) { + ReportStateGuard _(*this); + + switch (me->status) { + case Status::W_ATTACH: + me->pending_update = update; + return {}; + case Status::COMPLETED: + return {}; + case Status::WORKING: { + me->set_price_quantity(Price(update.price()), + Quantity(update.quantity())); + if (update.has_custom()) { + *me->definition.mutable_custom_def() = update.custom(); + me->services->report_definition(me->definition); + } + me->algo->do_update(update); + return {}; + } + case Status::INACTIVE: + bts_assert(false); + return {}; + } + bts_assert(false); + return {}; +} + +OrderOpResult AlgoWrapperOrder::on_update(Price p, Quantity q) { + ReportStateGuard _(*this); + + Update up; + up.set_price(p.value()); + up.set_quantity(q.value()); + return on_update(up); +} + +orderman::OrderOpResult AlgoWrapperOrder::on_detach() { + ReportStateGuard _(*this); + + LOG(OrderMan, Info, "AlgoOrder order with key {} received detach", + key().value()); + + switch (me->status) { + case Status::W_ATTACH: + case Status::WORKING: + for (auto &[_, c] : me->children) { + (void)_; + c.order.mark_detached_from_parent(); + } + me->children.clear(); + terminate(ORDER_STATUS_CANCELED); + break; + case Status::COMPLETED: + break; + case Status::INACTIVE: + bts_assert(false); + break; + } + return {}; +} + +orderman::OrderOpResult AlgoWrapperOrder::on_cancel() { + ReportStateGuard _(*this); + + switch (me->status) { + case Status::W_ATTACH: + case Status::WORKING: + terminate(ORDER_STATUS_CANCELED); + break; + case Status::COMPLETED: + break; + case Status::INACTIVE: + bts_assert(false); + break; + } + return {}; +} + +// -------------------------------------------------------------------------------- +// IBeforeLaunchAlgoServices +// -------------------------------------------------------------------------------- +api::orderman::OrderDefinition const &AlgoWrapperOrder::definition() const { + return *def(); +} + +api::Security const &AlgoWrapperOrder::security() const { + return *me->security; +} + +OrderKey AlgoWrapperOrder::order_key() const { return key(); } + +OrderKey AlgoWrapperOrder::parent_order_key() const { return parent_key(); } + +api::Security const *AlgoWrapperOrder::lookup_security(SecurityKey k) const { + return me->security_db->resolve(k); +} + +Price AlgoWrapperOrder::price() const { return Price(me->state().price()); } + +Quantity AlgoWrapperOrder::quantity() const { + return Quantity(me->state().quantity()); +} + +Quantity AlgoWrapperOrder::total_fills() const { + return Quantity(me->state().filled_quantity()); +} + +void AlgoWrapperOrder::subscribe_book(SecurityKey k) { + if (!is_working()) + return; + bts_assert(me->book_subs.find(k) == me->book_subs.end()); + + me->book_subs[k] = me->services->subscribe_to_book( + k, [this, k](auto const &ev) { me->algo->on_book(k, ev.book); }); +} + +void AlgoWrapperOrder::unsubscribe_book(SecurityKey k) { + if (!is_working()) + return; + bts_assert(me->book_subs.find(k) != me->book_subs.end()); + if (auto it = me->book_subs.find(k); it != me->book_subs.end()) + me->services->unsubscribe_from_book(it->second); +} + +void AlgoWrapperOrder::subscribe_child_change(OrderKey k) { + if (!is_working()) + return; + + auto it = me->children.find(k); + bts_assert(it != me->children.end()); + auto &child_record = it->second; + bts_assert(!child_record.is_subscribing); + child_record.is_subscribing = true; +} + +void AlgoWrapperOrder::unsubscribe_child_change(OrderKey k) { + if (!is_working()) + return; + + auto it = me->children.find(k); + bts_assert(it != me->children.end()); + auto &child_record = it->second; + bts_assert(child_record.is_subscribing); + child_record.is_subscribing = false; +} + +void AlgoWrapperOrder::subscribe_timer() { + if (!is_working()) + return; + bts_assert(!me->has_timer_sub); + me->has_timer_sub = true; + me->services->subscribe_to_time( + [this](auto const &) { me->algo->on_timer(); }); +} + +void AlgoWrapperOrder::unsubscribe_timer() { + if (!is_working()) + return; + bts_assert(me->has_timer_sub); + me->services->unsubscribe_from_time(); + me->has_timer_sub = false; +} + +bool AlgoWrapperOrder::is_attaching() const { + return me->attach_target != null_order_key(); +} + +ChildTemplate &AlgoWrapperOrder::make_child_template( + api::orderman::OrderDefinition const &child_def, size_t reserve) { + auto t = std::make_unique(key(), child_def, me->order_factory, + reserve); + if (me->services) + t->builder.activate(*me->services); + me->child_templates.emplace_back(std::move(t)); + return *(me->child_templates.back()); +} + +// -------------------------------------------------------------------------------- +// IAlgoServices +// -------------------------------------------------------------------------------- + +OrderKey AlgoWrapperOrder::launch_child(ChildTemplate &t, Price p, Quantity q, + bool subscribe_to_changes) { + if (!is_working()) + return null_order_key(); + return index_and_launch_child(t.builder.build(), p, q, subscribe_to_changes); +} + +OrderKey +AlgoWrapperOrder::launch_child(api::orderman::OrderDefinition const &def, + Price p, Quantity q, bool subscribe_to_changes) { + if (!is_working()) + return null_order_key(); + return index_and_launch_child(ChildOrder{def, *me->services}, p, q, + subscribe_to_changes); +} + +void AlgoWrapperOrder::update_child(OrderKey child, + api::orderman::Update const &update) { + if (!is_working()) + return; + + bts_assert(me->status == Status::WORKING); + if (auto it = me->children.find(child); it != me->children.end()) + it->second.order.update(update); + else + terminate_error(fmt::format("Algo {} tried to update unknown child: {}", + key().value(), child.value())); +} + +void AlgoWrapperOrder::cancel_child(OrderKey child) { + if (!is_working()) + return; + + bts_assert(me->status == Status::WORKING); + if (auto it = me->children.find(child); it != me->children.end()) + it->second.order.cancel(); + else + terminate_error(fmt::format("Algo {} tried to cancel unknown child: {}", + key().value(), child.value())); +} + +void AlgoWrapperOrder::detach_child(OrderKey child) { + if (!is_working()) + return; + + if (auto it = me->children.find(child); it != me->children.end()) { + it->second.order.mark_detached_from_parent(); + me->children.erase(it); + } else + terminate_error(fmt::format("Algo {} tried to cancel unknown child: {}", + key().value(), child.value())); +} + +void AlgoWrapperOrder::detach_all_children() { + if (!is_working()) + return; + for (auto &[_, c] : me->children) { + (void)_; + c.order.mark_detached_from_parent(); + } + me->children.clear(); +} + +void AlgoWrapperOrder::update_fill_state(Quantity q, Price p) { + if (!is_working()) + return; + + ReportStateGuard _(*this); + auto previous_qty = me->state().filled_quantity(); + if (previous_qty > q.value()) { + LOG(OrderMan, Error, + "AlgoOrder {} is reporting a decrease in fill quantity " + "from {} to {}. This should never happen. Canceling {}", + key().value(), previous_qty, q.value(), key().value()); + terminate_error("Internal algo error. Report fill size decreased"); + } else { + auto new_avg_price = Price(0); + if (q.value() > 0) + new_avg_price.value() = + (me->state().filled_quantity() * me->state().avg_price() + + (q.value() - previous_qty) * p.value()) / + q.value(); + me->set_fill_quantities(q, p, new_avg_price); + } +} + +void AlgoWrapperOrder::cancel(std::string const &msg) { + if (!is_working()) + return; + ReportStateGuard _(*this); + terminate(ORDER_STATUS_CANCELED, msg); +} + +void AlgoWrapperOrder::terminate_error(std::string const &msg) { + if (!is_working() && me->status != Status::W_ATTACH) + return; + ReportStateGuard _(*this); + // If we attached and an error was signaled we do not want to + // cancel our child because that child might be a long running + // order with a good queue position that we want to preserve + if (is_attaching()) + me->children.erase(me->attach_target); + terminate(ORDER_STATUS_ERROR, msg); +} + +void AlgoWrapperOrder::complete() { + if (!is_working()) + return; + ReportStateGuard _(*this); + terminate(ORDER_STATUS_COMPLETED); +} + +// -------------------------------------------------------------------------------- +// Private methods +// -------------------------------------------------------------------------------- +void AlgoWrapperOrder::on_attach_complete( + OrderOpResult r, ChildOrder const &child, + api::orderman::OrderDefinition const &, + api::orderman::OrderState const &state) { + ReportStateGuard _(*this); + + switch (me->status) { + case Status::W_ATTACH: + if (r.ok()) { + bts_assert(state.status() == ORDER_STATUS_WORKING); + + LOG(OrderMan, Info, + "AlgoOrder order with key {} successfully attached to {}", + key().value(), child.key().value()); + + // Store the order + auto &child_record = (me->children)[child.key()]; + child_record.is_subscribing = true; + child_record.order = child; + update_child_record(state, &child_record); + transition(Status::WORKING); + } else { + terminate_error(fmt::format( + "AlgoOrder order with key {} failed to attach to {}: {}", + key().value(), me->attach_target.value(), r.error_msg)); + } + break; + case Status::COMPLETED: + break; + case Status::INACTIVE: + case Status::WORKING: + bts_assert(false); + break; + } +} + +void AlgoWrapperOrder::on_child_order_update( + OrderKey child_key, api::orderman::OrderState const &new_child_state) { + ReportStateGuard _(*this); + + switch (me->status) { + case Status::WORKING: + case Status::W_ATTACH: + if (auto it = me->children.find(child_key); it != me->children.end()) { + auto &child_record = it->second; + switch (new_child_state.status()) { + case ORDER_STATUS_COMPLETED: + case ORDER_STATUS_WORKING: + case ORDER_STATUS_PENDING_WORKING: + case ORDER_STATUS_CANCELED: + if (child_record.state.has_value() && + child_record.state.value().total_fills.value() > + new_child_state.filled_quantity()) { + LOG(OrderMan, Error, + "AlgoOrder {} observed child {} decrease its total fills " + "from {} to {}. This should never happen. Canceling {}", + key().value(), child_key.value(), + child_record.state.value().total_fills.value(), + new_child_state.filled_quantity(), key().value()); + terminate_error("Child order filled quantity decreased"); + } else { + update_child_record(new_child_state, &child_record); + if (child_record.is_subscribing) + me->algo->on_child_change(child_key, + child_record.state.value()); + } + break; + + case ORDER_STATUS_DISCONNECTED: + case ORDER_STATUS_REJECTED_BY_SPARK: + case ORDER_STATUS_ERROR: + terminate_error("Unexpected child order state"); + break; + + case ORDER_STATUS_INACTIVE: + case OrderStatus_INT_MIN_SENTINEL_DO_NOT_USE_: + case OrderStatus_INT_MAX_SENTINEL_DO_NOT_USE_: + bts_assert(false); + break; + } + } else + terminate_error( + fmt::format("Unknown child order update: {}", child_key.value())); + return; + case Status::COMPLETED: + return; + case Status::INACTIVE: + bts_assert(false); + return; + } + bts_assert(false); +} + +void AlgoWrapperOrder::setup_transitions() { + // From INACTIVE + me->transition_actions[{Status::INACTIVE, Status::COMPLETED}] = [this]() { + _transition(Status::COMPLETED); + }; + me->transition_actions[{Status::INACTIVE, Status::W_ATTACH}] = [this]() { + me->services->attach(me->attach_target, [this](auto result, + auto const &child_order, + auto const &child_def, + auto const &child_state) { + this->on_attach_complete(result, child_order, child_def, child_state); + }); + _transition(Status::W_ATTACH); + }; + me->transition_actions[{Status::INACTIVE, Status::WORKING}] = [this]() { + _transition(Status::WORKING); + me->algo->do_launch(*this); + }; + + // From W_ATTACH + me->transition_actions[{Status::W_ATTACH, Status::COMPLETED}] = [this]() { + _transition(Status::COMPLETED); + }; + me->transition_actions[{Status::W_ATTACH, Status::WORKING}] = [this]() { + _transition(Status::WORKING); + auto &maybe_state = me->children[me->attach_target].state; + bts_assert(maybe_state.has_value()); + me->algo->do_launch_attached(*this, me->attach_target, + maybe_state.value()); + if (me->status == Status::WORKING && me->pending_update.has_value()) { + auto update = me->pending_update.value(); + me->pending_update.reset(); + me->algo->do_update(me->pending_update.value()); + } + }; + + // From WORKING + me->transition_actions[{Status::WORKING, Status::COMPLETED}] = [this]() { + cleanup(); + _transition(Status::COMPLETED); + }; +} + +void AlgoWrapperOrder::check_invariants() { + bts_assert(me->security_db); + bts_assert(me->order_factory); + + switch (me->status) { + case Status::INACTIVE: + bts_assert(false); + return; + + case Status::W_ATTACH: + bts_assert(me->services); + bts_assert(me->security); + bts_assert(is_attaching()); + bts_assert(me->external_status() == ORDER_STATUS_WORKING); + bts_assert(me->book_subs.empty()); + bts_assert(me->children.empty()); + bts_assert(!me->has_timer_sub); + break; + + case Status::WORKING: + bts_assert(me->services); + bts_assert(me->security); + bts_assert(me->external_status() == ORDER_STATUS_WORKING); + bts_assert(!me->pending_update.has_value()); + break; + + case Status::COMPLETED: + bts_assert(me->children.empty()); + bts_assert(me->external_status() == ORDER_STATUS_CANCELED || + me->external_status() == ORDER_STATUS_COMPLETED || + me->external_status() == ORDER_STATUS_ERROR || + me->external_status() == ORDER_STATUS_REJECTED_BY_SPARK); + bts_assert(me->book_subs.empty()); + bts_assert(!me->has_timer_sub); + bts_assert(!me->pending_update.has_value()); + break; + } +} + +void AlgoWrapperOrder::transition(Status new_status) { + if (auto it = me->transition_actions.find({me->status, new_status}); + it != me->transition_actions.end()) { + it->second(); + } else { + LOG(OrderMan, Fatal, "Illegal transition from {} to {}", + state_name(me->status), state_name(new_status)); + bts_assert(false); + } +} + +void AlgoWrapperOrder::_transition(Status st) { + LOG(OrderMan, Info, "Transitioninig AlgoOrder with key {} from {} to {}", + key().value(), state_name(me->status), state_name(st)); + me->status = st; + check_invariants(); +} + +void AlgoWrapperOrder::terminate(api::orderman::OrderStatus st, + std::string const &error) { + me->set_external_status(st); + if (error.size()) + me->set_last_msg(error); + transition(Status::COMPLETED); +} + +void AlgoWrapperOrder::cleanup() { + for (auto const &s : me->book_subs) { + me->services->unsubscribe_from_book(s.second); + me->book_subs.clear(); + } + for (auto &c : me->children) { + c.second.order.cancel(); + me->children.clear(); + } + if (me->has_timer_sub) + unsubscribe_timer(); + me->pending_update.reset(); +} + +void AlgoWrapperOrder::update_child_record( + api::orderman::OrderState const &new_state, ChildRecord *child_record) { + if (!child_record->state.has_value()) + child_record->state = ChildState{}; + auto &old_state = child_record->state.value(); + bts_assert(old_state.total_fills.value() <= new_state.filled_quantity()); + + child_record->state = ChildState{ + Price(new_state.price()), + Quantity(new_state.quantity()), + Quantity(new_state.filled_quantity()), + Price(new_state.avg_price()), + Quantity(new_state.filled_quantity() - old_state.total_fills.value()), + Price(new_state.last_price()), + map_child_status(new_state.status())}; +} + +OrderKey AlgoWrapperOrder::index_and_launch_child(ChildOrder &&child, Price p, + Quantity q, bool subscribe) { + child.activate(p, q); + auto k = child.key(); + auto &cr = me->children[k]; + cr = {std::move(child), {}, subscribe}; + return k; +} + +bool AlgoWrapperOrder::is_working() const { + return me->status == Status::WORKING; +} + +log::CharPtrWrapper AlgoWrapperOrder::state_name(Status st) { + switch (st) { + case Status::COMPLETED: + return {"COMPLETED"}; + case Status::W_ATTACH: + return {"W_ATTACH"}; + case Status::INACTIVE: + return {"INACTIVE"}; + case Status::WORKING: + return {"WORKING"}; + } + bts_assert(false); + return {""}; +} + +ChildStatus AlgoWrapperOrder::map_child_status(api::orderman::OrderStatus st) { + switch (st) { + case ORDER_STATUS_COMPLETED: + return ChildStatus::COMPLETED; + case ORDER_STATUS_WORKING: + case ORDER_STATUS_PENDING_WORKING: + return ChildStatus::WORKING; + case ORDER_STATUS_CANCELED: + return ChildStatus::CANCELED; + default: + bts_assert(false); + return ChildStatus::CANCELED; + } +} + +bool AlgoWrapperOrder::_is_attaching( + api::orderman::OrderDefinition const &def) const { + auto ak = OrderKey(def.attach_target_order_key()); + return (ak != null_order_key() && + !should_forward_attachment(def.custom_def())); +} + +} // namespace orderman +} // namespace bts diff --git a/src/lib/orderman/orders/algo/AlgoWrapperOrder.h b/src/lib/orderman/orders/algo/AlgoWrapperOrder.h new file mode 100644 index 000000000..ef36b638a --- /dev/null +++ b/src/lib/orderman/orders/algo/AlgoWrapperOrder.h @@ -0,0 +1,87 @@ +#pragma once + +#include "lib/orderman/orders/Order.h" +#include "lib/orderman/orders/algo/IAlgoServices.h" + +namespace bts { +namespace orderman { + +class IAlgoOrder; +enum class ChildStatus; + +class AlgoWrapperOrder : public Order, + private IAlgoServices { + public: + AlgoWrapperOrder(std::unique_ptr &&); + ~AlgoWrapperOrder(); + + // Order + void on_init_new(api::orderman::OrderDefinition const &, + const PreActivationOrderServices &) override; + void on_init_recovered(api::orderman::OrderRecord const &, + const PreActivationOrderServices &) override; + OrderOpResult on_activate(Price, Quantity, OrderServices &) override; + OrderOpResult on_update(api::orderman::Update const &) override; + OrderOpResult on_update(Price, Quantity) override; + OrderOpResult on_detach() override; + OrderOpResult on_cancel() override; + + private: + // IBeforeLaunchAlgoServices + api::orderman::OrderDefinition const &definition() const override; + api::Security const &security() const override; + OrderKey order_key() const override; + OrderKey parent_order_key() const override; + api::Security const *lookup_security(SecurityKey k) const override; + bool is_attaching() const override; + ChildTemplate &make_child_template(api::orderman::OrderDefinition const &, + size_t) override; + // IAlgoServices + Price price() const override; + Quantity quantity() const override; + Quantity total_fills() const override; + void subscribe_book(SecurityKey) override; + void unsubscribe_book(SecurityKey) override; + void subscribe_child_change(OrderKey) override; + void unsubscribe_child_change(OrderKey) override; + void subscribe_timer() override; + void unsubscribe_timer() override; + OrderKey launch_child(ChildTemplate &, Price, Quantity, + bool subscribe = true) override; + OrderKey launch_child(api::orderman::OrderDefinition const &, Price, + Quantity, bool subscribe = true) override; + void update_child(OrderKey child, api::orderman::Update const &) override; + void cancel_child(OrderKey child) override; + void detach_child(OrderKey child) override; + void detach_all_children() override; + void cancel(std::string const &msg = "") override; + void terminate_error(std::string const &msg) override; + void complete() override; + void update_fill_state(Quantity total_fills, Price last_price) override; + + // Private + struct ReportStateGuard; + struct ChildRecord; + enum class Status; + struct PImpl; + std::unique_ptr me; + void on_attach_complete(OrderOpResult, ChildOrder const &, + api::orderman::OrderDefinition const &, + api::orderman::OrderState const &); + void on_child_order_update(OrderKey, api::orderman::OrderState const &); + void setup_transitions(); + void check_invariants(); + void transition(Status); + void _transition(Status); + void terminate(api::orderman::OrderStatus, std::string const &error = ""); + void cleanup(); + void update_child_record(api::orderman::OrderState const &, ChildRecord *); + OrderKey index_and_launch_child(ChildOrder &&, Price, Quantity, bool); + bool is_working() const ; + log::CharPtrWrapper state_name(Status) ; + ChildStatus map_child_status(api::orderman::OrderStatus) ; + bool _is_attaching(api::orderman::OrderDefinition const &) const ; +}; + +} // namespace orderman +} // namespace bts diff --git a/src/lib/orderman/orders/algo/ChildTemplate.h b/src/lib/orderman/orders/algo/ChildTemplate.h new file mode 100644 index 000000000..bcb067f33 --- /dev/null +++ b/src/lib/orderman/orders/algo/ChildTemplate.h @@ -0,0 +1,19 @@ +#pragma once + +namespace bts { +namespace orderman { + +class OrderBuilder; + +class ChildTemplate { + public: + ChildTemplate(); + +private: + ChildTemplate(OrderKey parent_key, api::orderman::OrderDefinition const &def, + IOrderFactory *factory, size_t reserve_sz) + : builder(parent_key, def, *factory, reserve_sz) {} + OrderBuilder builder; +}; + +}} diff --git a/src/lib/orderman/orders/algo/IAlgoOrder.cpp b/src/lib/orderman/orders/algo/IAlgoOrder.cpp new file mode 100644 index 000000000..11240c91b --- /dev/null +++ b/src/lib/orderman/orders/algo/IAlgoOrder.cpp @@ -0,0 +1,17 @@ +#include "lib/orderman/orders/algo/IAlgoOrder.h" +#include "lib/orderman/orders/algo/IAlgoServices.h" + +namespace bts { +namespace orderman { +IAlgoOrder::~IAlgoOrder() {} + +OrderOpResult IAlgoOrder::do_before_launch(IBeforeLaunchAlgoServices &) { + return {}; +} + +void IAlgoOrder::do_launch_attached(IAlgoServices &serv, OrderKey, ChildState) { + serv.terminate_error("Algo does not implement attachment functionality"); +} + +} // namespace orderman +} // namespace bts diff --git a/src/lib/orderman/orders/algo/IAlgoOrder.h b/src/lib/orderman/orders/algo/IAlgoOrder.h new file mode 100644 index 000000000..55f5d7679 --- /dev/null +++ b/src/lib/orderman/orders/algo/IAlgoOrder.h @@ -0,0 +1,70 @@ +#pragma once + +#include "lib/orderman/orders/Order.h" +#include + +namespace bts { +namespace orderman { + +enum class ChildStatus { WORKING, COMPLETED, CANCELED }; + +struct ChildState { + Price price; + Quantity quantity; + Quantity total_fills; + Price avg_price; + Quantity last_fills; + Price last_price; + ChildStatus status; +}; + +class Book; +class IBeforeLaunchAlgoServices; +class IAlgoServices; + +class IAlgoOrder { + public: + virtual ~IAlgoOrder() ; + + // -------------------------------------------------------------- + // Events Handlers - These will be optionally invoked if subscribed to + // -------------------------------------------------------------- + + // The child order specified by the order key has changed + virtual void on_child_change(OrderKey, ChildState const &) {} + + // The book for the specified security has changed + virtual void on_book(SecurityKey, Book const &) {} + + // A period timer has run out + virtual void on_timer() {} + + // -------------------------------------------------------------- + // Hooks - These allow you to customize the behaviour of your algo + // in certain contexts + // -------------------------------------------------------------- + + // Override this to setup and validate an algo prior to it being + // launched. This call occurs outside of the latency sensitive path + // so it can be used for any expensive initialization + // operations. The implementation should return an error code if it + // detects an invalid parameter in the algo definition. + virtual OrderOpResult do_before_launch(IBeforeLaunchAlgoServices &) ; + + // Override this method to activate your algo + virtual void do_launch(IAlgoServices &) = 0; + + // Override this method to activate your algo using an existing + // working order as a child. Attached child orders are + // automatically subscribed to, so there is no need to subscribe to + // changes for the attached order. + virtual void do_launch_attached(IAlgoServices &, OrderKey child, ChildState) ; + + // Implement this method to respond to updates to your algo. The + // implementation should validate the update and either apply it, + // if valid or terminate with an error otherwise + virtual void do_update(api::orderman::Update const &) {} +}; + +} // namespace orderman +} // namespace bts diff --git a/src/lib/orderman/orders/algo/IAlgoServices.cpp b/src/lib/orderman/orders/algo/IAlgoServices.cpp new file mode 100644 index 000000000..787077bf7 --- /dev/null +++ b/src/lib/orderman/orders/algo/IAlgoServices.cpp @@ -0,0 +1 @@ +#include "lib/orderman/orders/algo/IAlgoServices.h" diff --git a/src/lib/orderman/orders/algo/IAlgoServices.h b/src/lib/orderman/orders/algo/IAlgoServices.h new file mode 100644 index 000000000..9d61c9282 --- /dev/null +++ b/src/lib/orderman/orders/algo/IAlgoServices.h @@ -0,0 +1,88 @@ +#pragma once + +#include "lib/orderman/orders/algo/IBeforeLaunchAlgoServices.h" + +namespace bts { +namespace orderman { + +class IAlgoServices : public IBeforeLaunchAlgoServices { + public: + // -------------------------------------------------------------- + // Queries + // -------------------------------------------------------------- + + // Returns the price for this algo + virtual Price price() const = 0; + + // Returns the quantity for this algo + virtual Quantity quantity() const = 0; + + // Returns the filled quantity for this algo + virtual Quantity total_fills() const = 0; + + // -------------------------------------------------------------- + // Event Subscriptions + // -------------------------------------------------------------- + + // Subscribe to book updates for the specified security + virtual void subscribe_book(SecurityKey) = 0; + virtual void unsubscribe_book(SecurityKey) = 0; + + // Subscribe to child order updates for the specified child + // order. This is rarely needed since launch_child() by default + // automatically subscribes to new orders. + virtual void subscribe_child_change(OrderKey) = 0; + virtual void unsubscribe_child_change(OrderKey) = 0; + + // Subscribe to a periodic timer + virtual void subscribe_timer() = 0; + virtual void unsubscribe_timer() = 0; + + // -------------------------------------------------------------- + // Child management + // -------------------------------------------------------------- + + // Launch a new child order, based on a previously created + // template, at the specified price and quantity. By default + // launching a child results in an automatic subscription to its + // state changes. + virtual OrderKey launch_child(ChildTemplate &, Price, Quantity, + bool subscribe = true) = 0; + + // Launch a new child order, using the speficied definition, price + // and quantity. By default launching a child results in an + // automatic subscription to its state changes. Order creation is + // relatively costly so in performance sensitive code it is better + // to create ChildTemplate before the algo is launched. + virtual OrderKey launch_child(api::orderman::OrderDefinition const &, Price, + Quantity, bool subscribe = true) = 0; + + // Child order maintenance + virtual void update_child(OrderKey child, api::orderman::Update const &) = 0; + virtual void cancel_child(OrderKey child) = 0; + virtual void detach_child(OrderKey child) = 0; + virtual void detach_all_children() = 0; + + // -------------------------------------------------------------- + // Algo Life Cycle Management + // -------------------------------------------------------------- + + // Cancel this algo, and all its children, optionally reporting an + // explanation. + virtual void cancel(std::string const &msg = "") = 0; + + // Terminate the algo, canceling all children the algo launched + // (but not a child the algo was attached to) and signaling an + // error condition. + virtual void terminate_error(std::string const &msg) = 0; + + // Signal that the algo completed successfully, canceling any + // active children. + virtual void complete() = 0; + + // Update this algos's filled quantity and last price + virtual void update_fill_state(Quantity total_fills, Price last_price) = 0; +}; + +} // namespace orderman +} // namespace bts diff --git a/src/lib/orderman/orders/algo/IBeforeLaunchAlgoServices.cpp b/src/lib/orderman/orders/algo/IBeforeLaunchAlgoServices.cpp new file mode 100644 index 000000000..87f753e91 --- /dev/null +++ b/src/lib/orderman/orders/algo/IBeforeLaunchAlgoServices.cpp @@ -0,0 +1 @@ +#include "lib/orderman/orders/algo/IBeforeLaunchAlgoServices.h" diff --git a/src/lib/orderman/orders/algo/IBeforeLaunchAlgoServices.h b/src/lib/orderman/orders/algo/IBeforeLaunchAlgoServices.h new file mode 100644 index 000000000..733f60d7c --- /dev/null +++ b/src/lib/orderman/orders/algo/IBeforeLaunchAlgoServices.h @@ -0,0 +1,48 @@ +#pragma once + +#include "lib/api/services/OrderService.pb.h" +#include "lib/domain_model/SecurityKey.h" +#include "lib/orderman/orderman_utils/orderman_common.h" + +namespace bts { +namespace orderman { + +class ChildTemplate; + +class IBeforeLaunchAlgoServices { + public: + virtual ~IBeforeLaunchAlgoServices() {} + + // The OrderDefinition for this algo + virtual api::orderman::OrderDefinition const &definition() const = 0; + + // The security this algo is paramterized with (also available from + // definition()) + virtual api::Security const &security() const = 0; + + // The order key for this algo + virtual OrderKey order_key() const = 0; + + // The parent key for this algo's parent (null_order_key() if the + // algo does not have a parent) + virtual OrderKey parent_order_key() const = 0; + + // The security identified by k or nullptr if no such security + // exists + virtual api::Security const *lookup_security(SecurityKey k) const = 0; + + // Wheter this algo is being attached to an existing order + virtual bool is_attaching() const = 0; + + // Build a child template that can later can be used to quickly + // launch child orders. The reserve parameter indicates how many + // orders should be created ahead of time, before they are + // launched. This is usefull to remove the relatively expensive + // order creation operation to a background thread. + virtual ChildTemplate & + make_child_template(api::orderman::OrderDefinition const &child_def, + size_t reserve = 1) = 0; +}; + +} // namespace orderman +} // namespace bts diff --git a/src/lib/orderman/orders/algo/algo_orders/CoverAlgo.cpp b/src/lib/orderman/orders/algo/algo_orders/CoverAlgo.cpp new file mode 100644 index 000000000..01dff07fb --- /dev/null +++ b/src/lib/orderman/orders/algo/algo_orders/CoverAlgo.cpp @@ -0,0 +1,218 @@ +#include "lib/orderman/orders/algo/algo_orders/CoverAlgo.h" + +#include "lib/domain_model/Security.h" +#include "lib/orderman/order_factory/IOrderFactory.h" +#include "lib/orderman/orders/algo/IAlgoServices.h" +#include "lib/utils/PBUtils.h" + +namespace bts { +namespace orderman { + +using namespace api::orderman; + +enum class CoverAlgo::Status { WORKING, WAITING_FOR_HEDGES, DONE }; +const char *CoverAlgo::status_name(Status st) { + switch (st) { + case Status::WORKING: + return "WORKING"; + case Status::WAITING_FOR_HEDGES: + return "WAITING_FOR_HEDGES"; + case Status::DONE: + return "Done"; + } + return nullptr; +} +struct CoverAlgo::PImpl { + IAlgoServices *algo; + OrderKey child_key = null_order_key(); + Price price_improvement_delta; + ChildTemplate *child_template = nullptr; + ChildTemplate *hedge_template = nullptr; + Quantity hedged_fills = Quantity(0); + Status status = Status::WORKING; + std::vector hedges; +}; + +CoverAlgo::CoverAlgo() : me(new PImpl()) {} +CoverAlgo::~CoverAlgo() {} +IAlgoServices &CoverAlgo::algo() const { return *me->algo; } + +OrderOpResult CoverAlgo::do_before_launch(IBeforeLaunchAlgoServices &serv) { + auto &def = serv.definition(); + bts_assert(def.has_custom_def()); + bts_assert(def.custom_def().has_cover()); + + // Validate the cover part of the definition + auto &cover = def.custom_def().cover(); + if (!cover.has_child() && + OrderKey(def.attach_target_order_key()) == null_order_key()) { + return OrderOpResult{ + ORDER_ERROR_INVALID_ORDER_DEFINITON, + "Cover order must have either a child order definition or an " + "order to attach to"}; + } + + if (!cover.has_hedge()) + return OrderOpResult{ORDER_ERROR_INVALID_ORDER_DEFINITON, + "Cover order must have a hedge order definition"}; + if (!serv.is_attaching()) { + // if we are not attaching create a child template so we can + // quickly launch our child when the time comes. + auto child_def = def; + *child_def.mutable_custom_def() = def.custom_def().cover().child(); + me->child_template = &(serv.make_child_template(child_def)); + } + + init_hedge_template(serv, cover.hedge()); + set_price_improvement_delta(serv, cover); + return {}; +} + +void CoverAlgo::do_launch(IAlgoServices &algo) { + me->algo = &algo; + LOG(OrderMan, Diag, "Starting CoverAlgo {}, {} {}@{}. Will cover {} ticks", + algo.order_key().value(), + securities::side_name(algo.definition().side()), algo.quantity().value(), + algo.price().value(), + algo.definition().custom_def().cover().hedge_ticks()); + + LOG(OrderMan, Diag, "CoverAlgo {} launching child", + algo.order_key().value()); + me->child_key = + algo.launch_child(*me->child_template, algo.price(), algo.quantity()); +} + +void CoverAlgo::do_launch_attached(IAlgoServices &algo, OrderKey k, + ChildState st) { + me->algo = &algo; + me->child_key = k; + me->hedged_fills = st.total_fills; + on_child_change(k, st); +} + +void CoverAlgo::on_child_change(OrderKey k, ChildState const &st) { + if (k == me->child_key) { + if (st.total_fills.value() > me->hedged_fills.value()) { + auto hedge_qty = + Quantity(st.total_fills.value() - me->hedged_fills.value()); + auto hedge_price = securities::improve_price( + algo().definition().side(), st.last_price, + me->price_improvement_delta); + + auto hedge = + algo().launch_child(*me->hedge_template, hedge_price, hedge_qty); + me->hedges.push_back(hedge); + + me->hedged_fills = + Quantity(hedge_qty.value() + me->hedged_fills.value()); + LOG(OrderMan, Diag, + "CoverAlgo {}, launched new hedge in response to child fill. " + "Hedge: " + "{} {}@{}", + algo().order_key().value(), + securities::side_name(algo().definition().side()), + hedge_qty.value(), hedge_price.value()); + } + algo().update_fill_state(st.total_fills, st.last_price); + switch (st.status) { + case ChildStatus::WORKING: + break; + case ChildStatus::COMPLETED: + LOG(OrderMan, Info, + "CoverAlgo {}. Child is completed, waiting for hedges ", + algo().order_key().value()); + me->status = Status::WAITING_FOR_HEDGES; + break; + case ChildStatus::CANCELED: + LOG(OrderMan, Info, "CoverAlgo {}. Child was canceled, terminating", + algo().order_key().value()); + me->status = Status::DONE; + algo().terminate_error("Unexpected child cancel"); + break; + } + } else { + switch (st.status) { + case ChildStatus::WORKING: + break; + case ChildStatus::COMPLETED: + if (auto it = std::find(me->hedges.begin(), me->hedges.end(), k); + it != me->hedges.end()) + me->hedges.erase(it); + break; + case ChildStatus::CANCELED: + LOG(OrderMan, Info, "CoverAlgo {}. Hedge was canceled, terminating", + algo().order_key().value()); + me->status = Status::DONE; + algo().terminate_error("Unexpected child cancel"); + break; + } + } + check_terminate(); +} + +void CoverAlgo::do_update(api::orderman::Update const &update) { + if (me->status == Status::WORKING) { + LOG(OrderMan, Diag, "CoverAlgo order {} receiving update: {}", + algo().order_key().value(), utils::pb::to_string(update)); + + if (update.has_custom() && !update.custom().has_cover()) { + algo().terminate_error("Invalid update"); + return; + } + + Update child_update; + child_update.set_price(update.price()); + child_update.set_quantity(update.quantity()); + + // process custom part of the udpate if any + if (update.has_custom()) { + auto &cover_update = update.custom().cover(); + set_price_improvement_delta(algo(), cover_update); + if (cover_update.has_child()) { + *child_update.mutable_custom() = cover_update.child(); + } + if (cover_update.has_hedge()) + init_hedge_template(algo(), cover_update.hedge()); + } + algo().update_child(me->child_key, child_update); + } else { + LOG(OrderMan, Info, + "CoverAlgo {}. Received update after child has completed. Ignoring " + "it.", + algo().order_key().value()); + } +} + +void orderman::CoverAlgo::init_hedge_template( + IBeforeLaunchAlgoServices &algo, + api::orderman::CustomOrderDefinition const &hedge_cdef) { + auto hedge_def = algo.definition(); + hedge_def.set_side(securities::other_side(algo.definition().side())); + hedge_def.set_sub_type(ORDER_SUB_TYPE_HEDGING_LEG); + hedge_def.clear_attach_target_order_key(); + *hedge_def.mutable_custom_def() = hedge_cdef; + me->hedge_template = &(algo.make_child_template(hedge_def)); +} + +void CoverAlgo::set_price_improvement_delta( + IBeforeLaunchAlgoServices &serv, + api::orderman::CoverOrderDefinition const &cover) { + me->price_improvement_delta = Price( + securities::tick_size(serv.security()).value() * cover.hedge_ticks()); +} + +void CoverAlgo::check_terminate() { + LOG(OrderMan, Diag, + "CoverAlgo {} check_terminate. State: {} Hedge count: {}", + algo().order_key(), log::CharPtrWrapper{status_name(me->status)}, + me->hedges.size()); + + if (me->status == Status::WAITING_FOR_HEDGES && me->hedges.empty()) { + LOG(OrderMan, Info, "CoverAlgo {}. Last hedge completed, terminating", + algo().order_key().value()); + algo().complete(); + } +} + +} // namespace orderman +} // namespace bts diff --git a/src/lib/orderman/orders/algo/algo_orders/CoverAlgo.h b/src/lib/orderman/orders/algo/algo_orders/CoverAlgo.h new file mode 100644 index 000000000..3bedb00e7 --- /dev/null +++ b/src/lib/orderman/orders/algo/algo_orders/CoverAlgo.h @@ -0,0 +1,37 @@ +#pragma once + +#include "lib/orderman/orders/algo/IAlgoOrder.h" + +namespace bts { +namespace orderman { + +// Cover initializes the child order as normal. Fills trigger hedge +// orders to the opposite side of the market, n ticks away. + +class CoverAlgo : public IAlgoOrder { +public: + CoverAlgo(); + ~CoverAlgo(); + + OrderOpResult do_before_launch(IBeforeLaunchAlgoServices &) override; + void do_launch(IAlgoServices &) override; + void do_launch_attached(IAlgoServices &, OrderKey, ChildState) override; + void do_update(api::orderman::Update const &) override; + void on_child_change(OrderKey, ChildState const &) override; + +private: + struct PImpl; + enum class Status; + std::unique_ptr me; + IAlgoServices &algo() const; + void + set_price_improvement_delta(IBeforeLaunchAlgoServices &, + api::orderman::CoverOrderDefinition const &); + void init_hedge_template(IBeforeLaunchAlgoServices &, + api::orderman::CustomOrderDefinition const &); + void check_terminate(); + const char *status_name(Status st); +}; + +} // namespace orderman +} // namespace bts diff --git a/src/lib/orderman/orders/algo/algo_orders/IcebergAlgo.cpp b/src/lib/orderman/orders/algo/algo_orders/IcebergAlgo.cpp new file mode 100644 index 000000000..f93231c57 --- /dev/null +++ b/src/lib/orderman/orders/algo/algo_orders/IcebergAlgo.cpp @@ -0,0 +1,193 @@ +#include "lib/orderman/orders/algo/algo_orders/IcebergAlgo.h" +#include "lib/orderman/orders/algo/IAlgoServices.h" + +#include "lib/domain_model/Security.h" +#include "lib/logging/logging.h" +#include "lib/orderman/order_factory/IOrderFactory.h" +#include "lib/utils/PBUtils.h" +#include "lib/utils/bts_chrono.h" + +namespace bts { +namespace orderman { + +using namespace api::orderman; + +enum class IcebergAlgo::Status { PAUSED, WORKING }; + +struct IcebergAlgo::PImpl { + IAlgoServices *algo; + OrderKey child_key = null_order_key(); + ChildTemplate *child_template = nullptr; + TimeStamp start_of_pause = TimeStamp(); + uint32_t pause_between_orders_ms = 0; + Quantity show_quantity = Quantity(0); + Status status = Status::PAUSED; +}; + +IcebergAlgo::IcebergAlgo() : me(new PImpl()) {} +IcebergAlgo::~IcebergAlgo() {} +IAlgoServices &IcebergAlgo::algo() const { return *me->algo; } + +OrderOpResult IcebergAlgo::do_before_launch(IBeforeLaunchAlgoServices &serv) { + auto &def = serv.definition(); + bts_assert(def.has_custom_def()); + bts_assert(def.custom_def().has_iceberg()); + + // Validate the iceberg part of the definition + auto &iceberg = def.custom_def().iceberg(); + if (!iceberg.has_child()) + return OrderOpResult{ORDER_ERROR_INVALID_ORDER_DEFINITON, + "Order must have either a child order definition "}; + + if (iceberg.show_quantity() <= 0) + return OrderOpResult{ORDER_ERROR_INVALID_ORDER_DEFINITON, + "Show quantity must be greater than 0"}; + + me->pause_between_orders_ms = iceberg.pause_between_orders_ms(); + me->show_quantity = Quantity((uint32_t)iceberg.show_quantity()); + + // Create a child template so we can quickly launch our child when + // the time comes. + init_child_template(serv, def.custom_def().iceberg().child()); + return {}; +} + +void IcebergAlgo::do_launch(IAlgoServices &algo) { + me->algo = &algo; + LOG(OrderMan, Diag, "Starting Iceberg Order {}. {} {}@{} Def: {}", + algo.order_key().value(), + securities::side_name(algo.definition().side()), algo.quantity().value(), + algo.price().value(), utils::pb::to_string(algo.definition())); + + if (me->pause_between_orders_ms > 0) + algo.subscribe_timer(); + me->status = Status::PAUSED; + on_timer(); +} + +void IcebergAlgo::do_launch_attached(IAlgoServices &algo, OrderKey k, + ChildState st) { + me->algo = &algo; + LOG(OrderMan, Diag, + "Starting Iceberg Order {} attached to child: {} {} {}@{} Def: {}", + algo.order_key().value(), k.value(), + securities::side_name(algo.definition().side()), algo.quantity().value(), + algo.price().value(), utils::pb::to_string(algo.definition())); + if (me->pause_between_orders_ms > 0) + algo.subscribe_timer(); + me->child_key = k; + me->status = Status::WORKING; + on_child_change(k, st); +} + +void IcebergAlgo::do_update(api::orderman::Update const &update) { + LOG(OrderMan, Diag, "IcebergAlgo order {} receiving update: {}", + algo().order_key().value(), utils::pb::to_string(update)); + + if (update.has_custom() && !update.custom().has_iceberg()) { + algo().terminate_error("Invalid update"); + return; + } + + if (update.quantity() < algo().total_fills().value()) { + algo().complete(); + return; + } + + Update child_update; + child_update.set_price(update.price()); + + // Process custom part of the udpate if any + if (update.has_custom()) { + + auto &iceberg_update = update.custom().iceberg(); + if (iceberg_update.show_quantity() == 0) { + algo().terminate_error("Invalid update"); + return; + } + + me->show_quantity = Quantity((uint32_t)iceberg_update.show_quantity()); + bool had_timer = me->pause_between_orders_ms > 0; + bool should_have_timer = iceberg_update.pause_between_orders_ms() > 0; + + if (had_timer && !should_have_timer) + algo().unsubscribe_timer(); + else if (!had_timer && should_have_timer) + algo().subscribe_timer(); + + if (iceberg_update.has_child()) { + *child_update.mutable_custom() = iceberg_update.child(); + init_child_template(algo(), iceberg_update.child()); + } + } + child_update.set_quantity(remaining_quantity().value()); + if (me->status == Status::WORKING) + algo().update_child(me->child_key, child_update); +} + +void IcebergAlgo::on_child_change(OrderKey k, ChildState const &st) { + if (k == me->child_key) { + algo().update_fill_state( + Quantity(algo().total_fills().value() + st.last_fills.value()), + st.last_price); + + if (algo().total_fills().value() >= algo().quantity().value()) { + algo().complete(); + return; + } + switch (st.status) { + case ChildStatus::WORKING: + return; + case ChildStatus::COMPLETED: + me->start_of_pause = Timer::now(); + me->child_key = null_order_key(); + me->status = Status::PAUSED; + on_timer(); + return; + case ChildStatus::CANCELED: + algo().terminate_error("Unexpected child cancel"); + return; + } + } +} + +void IcebergAlgo::on_timer() { + if (me->status == Status::PAUSED && + ms_diff(Timer::now(), me->start_of_pause) >= + me->pause_between_orders_ms) { + me->status = Status::WORKING; + send_next_order(); + } +} + +void IcebergAlgo::send_next_order() { + bts_assert(me->status == Status::WORKING); + bts_assert(algo().quantity().value() > algo().total_fills().value()); + + me->child_key = + algo().launch_child(*me->child_template, algo().price(), remaining_quantity()); + + LOG(OrderMan, Info, + "Iceberg order {} creating new child order {} with size " + "{} price {}. Filled {} so far out of {}", + algo().order_key().value(), me->child_key.value(), + remaining_quantity().value(), algo().price().value(), algo().total_fills().value(), + algo().quantity().value()); +} + +void orderman::IcebergAlgo::init_child_template( + IBeforeLaunchAlgoServices &serv, + api::orderman::CustomOrderDefinition const &iceberg_def) { + auto child_def = serv.definition(); + *child_def.mutable_custom_def() = iceberg_def; + me->child_template = &(serv.make_child_template(child_def)); +} + +Quantity IcebergAlgo::remaining_quantity() const { + bts_assert(algo().quantity().value() > algo().total_fills().value()); + auto remaining = algo().quantity().value() - algo().total_fills().value(); + return Quantity(std::min(remaining, me->show_quantity.value())); +} + +} // namespace orderman +} // namespace bts diff --git a/src/lib/orderman/orders/algo/algo_orders/IcebergAlgo.h b/src/lib/orderman/orders/algo/algo_orders/IcebergAlgo.h new file mode 100644 index 000000000..423a09da5 --- /dev/null +++ b/src/lib/orderman/orders/algo/algo_orders/IcebergAlgo.h @@ -0,0 +1,36 @@ +#pragma once + +#include "lib/orderman/orders/algo/IAlgoOrder.h" + +namespace bts { +namespace orderman { + +// Iceberg splits a large order into small pieces typically to avoid +// moving the market or reduce risk. + +class IcebergAlgo : public IAlgoOrder { + public: + IcebergAlgo(); + ~IcebergAlgo(); + + OrderOpResult do_before_launch(IBeforeLaunchAlgoServices &) override; + void do_launch(IAlgoServices &) override; + void do_launch_attached(IAlgoServices &, OrderKey, ChildState) override; + void do_update(api::orderman::Update const &) override; + void on_child_change(OrderKey, ChildState const &) override; + void on_timer() override; + + private: + enum class Status; + struct PImpl; + std::unique_ptr me; + + IAlgoServices &algo() const; + void init_child_template(IBeforeLaunchAlgoServices&, + api::orderman::CustomOrderDefinition const &); + void send_next_order(); + Quantity remaining_quantity() const; +}; + +} // namespace orderman +} // namespace bts diff --git a/src/lib/orderman/orders/algo/algo_orders/JoinAlgo.cpp b/src/lib/orderman/orders/algo/algo_orders/JoinAlgo.cpp new file mode 100644 index 000000000..e85a07f6e --- /dev/null +++ b/src/lib/orderman/orders/algo/algo_orders/JoinAlgo.cpp @@ -0,0 +1,203 @@ +#include "lib/orderman/orders/algo/algo_orders/JoinAlgo.h" +#include "lib/orderman/orders/algo/IAlgoServices.h" + +#include "lib/orderman/order_factory/IOrderFactory.h" +#include "lib/orderman/orders/spreader_orders/spreader/SpreaderUtils.h" +#include "lib/os/os.h" +#include "lib/utils/PBUtils.h" + +namespace bts { +namespace orderman { + +using namespace api::orderman; + +enum class JoinAlgo::Status { WAITING_FOR_MD, WAITING_TO_JOIN, JOINED }; + +struct JoinAlgo::PImpl { + IAlgoServices *algo; + Quantity min_quantity_to_join; + Status status = Status::WAITING_FOR_MD; + OrderKey child_key = null_order_key(); + ChildTemplate *child_template = nullptr; + Book book_at_inception; + Book last_book; + Price joined_price=Price(os::nan()); +}; + +JoinAlgo::JoinAlgo() : me(new PImpl()) {} +JoinAlgo::~JoinAlgo() {} +IAlgoServices &JoinAlgo::algo() const { return *me->algo; } + +OrderOpResult JoinAlgo::do_before_launch(IBeforeLaunchAlgoServices &serv) { + auto &def = serv.definition(); + bts_assert(def.has_custom_def()); + bts_assert(def.custom_def().has_join()); + + // Validate the join part of the definition + auto &join = def.custom_def().join(); + if (!join.has_child() && + OrderKey(def.attach_target_order_key()) == null_order_key()) { + return OrderOpResult{ + ORDER_ERROR_INVALID_ORDER_DEFINITON, + "Join order must have either a child order definition or an " + "order to attach to"}; + } + + if (!serv.is_attaching()) { + // if we are not attaching create a child template so we can + // quickly launch our child when the time comes. + auto child_def = def; + *child_def.mutable_custom_def() = def.custom_def().join().child(); + me->child_template = &(serv.make_child_template(child_def)); + } + + return {}; +} + +void JoinAlgo::do_launch(IAlgoServices &algo) { + me->algo = &algo; + update_join_threshold(); + bts_assert(me->child_template); + me->child_key = + algo.launch_child(*me->child_template, algo.price(), algo.quantity()); + algo.subscribe_book(SecurityKey(algo.security().id())); +} + +void JoinAlgo::do_launch_attached(IAlgoServices &algo, OrderKey k, + ChildState st) { + me->algo = &algo; + update_join_threshold(); + me->child_key = k; + algo.subscribe_book(SecurityKey(algo.security().id())); + on_child_change(k, st); +} + +void JoinAlgo::do_update(api::orderman::Update const &update) { + LOG(OrderMan, Diag, "JoinOrder order {} receiving update: {}", + algo().order_key().value(), utils::pb::to_string(update)); + + if (update.has_custom() && !update.custom().has_join()) { + algo().terminate_error("Invalid update"); + return; + } + + Update child_update; + Price price_to_pass = get_price_to_pass(Price(update.price())); + child_update.set_price(price_to_pass.value()); + child_update.set_quantity(update.quantity()); + if (update.has_custom()) { + update_join_threshold(); + auto &join_update = update.custom().join(); + *child_update.mutable_custom() = join_update.child(); + } + algo().update_child(me->child_key, child_update); + + // If we were not yet joined it is possible we now can, since we + // could have changed the min_quantity_to_join + if (me->status == Status::WAITING_TO_JOIN) + try_to_join(); +} + +void JoinAlgo::on_book(SecurityKey, Book const &b) { + me->last_book = b; + + LOG(OrderMan, Diag, "JoinOrder order {} on book. BID: {}@{} ASK: {}@{}", + algo().order_key().value(), b.side(api::SIDE_BUY)[0].size(), + b.side(api::SIDE_BUY)[0].price(), b.side(api::SIDE_SELL)[0].size(), + b.side(api::SIDE_SELL)[0].price()); + + switch (me->status) { + case Status::WAITING_FOR_MD: { + auto other_side = securities::other_side(algo().definition().side()); + auto &other_side_top = me->last_book.side(other_side)[0]; + + if (other_side_top.size() > 0) { + me->status = Status::WAITING_TO_JOIN; + me->book_at_inception = b; + LOG(OrderMan, Diag, + "JoinOrder order {} receiving first book: {} Target: {}", + algo().order_key().value(), me->min_quantity_to_join.value(), + other_side_top.price()); + try_to_join(); + } + } break; + case Status::JOINED: + break; + case Status::WAITING_TO_JOIN: + try_to_join(); + break; + } +} + +void JoinAlgo::try_to_join() { + bts_assert(me->status == Status::WAITING_TO_JOIN); + + auto my_side = algo().definition().side(); + auto other_side = securities::other_side(my_side); + auto &my_side_psz = me->last_book.side(my_side)[0]; + auto &opposite_at_inception_psz = me->book_at_inception.side(other_side)[0]; + + if (my_side_psz.size() && + my_side_psz.size() >= me->min_quantity_to_join.value() && + securities::is_equal_or_better( + my_side, Price(my_side_psz.price()), + Price(opposite_at_inception_psz.price()))) { + + LOG(OrderMan, Diag, "JoinOrder order {} joining: {}@{}", + algo().order_key().value(), algo().quantity().value(), + my_side_psz.price()); + + // Time to join + Update child_update; + me->joined_price = Price(my_side_psz.price()); + child_update.set_price(my_side_psz.price()); + child_update.set_quantity(algo().quantity().value()); + algo().update_child(me->child_key, child_update); + me->status = Status::JOINED; + } else { + LOG(OrderMan, Diag, + "JoinOrder order {} still waiting to join. Order: {}@{} Top of the " + "book: {}@{}" + " Target: {}@{}", + algo().order_key().value(), algo().quantity().value(), algo().price().value(), + my_side_psz.size(), my_side_psz.price(), + me->min_quantity_to_join.value(), opposite_at_inception_psz.price()); + } +} + +Price JoinAlgo::get_price_to_pass (Price price) const{ + Price rv; + switch (me->status) { + case Status::WAITING_FOR_MD: + case Status::WAITING_TO_JOIN: + rv = price; + break; + case Status::JOINED: + rv = me->joined_price; + break; + } + return rv; +} + +void JoinAlgo::update_join_threshold() { + me->min_quantity_to_join = SpreaderUtils::_quantity_threshold( + algo().definition().custom_def().join().join_threshold(), algo().quantity()); +} + +void JoinAlgo::on_child_change(OrderKey, ChildState const &st) { + algo().update_fill_state(st.total_fills, st.last_price); + + switch (st.status) { + case ChildStatus::WORKING: + return; + case ChildStatus::COMPLETED: + algo().complete(); + return; + case ChildStatus::CANCELED: + algo().cancel("Unexpected child cancel"); + return; + } +} + +} // namespace orderman +} // namespace bts diff --git a/src/lib/orderman/orders/algo/algo_orders/JoinAlgo.h b/src/lib/orderman/orders/algo/algo_orders/JoinAlgo.h new file mode 100644 index 000000000..e77aa382b --- /dev/null +++ b/src/lib/orderman/orders/algo/algo_orders/JoinAlgo.h @@ -0,0 +1,37 @@ +#pragma once + +#include "lib/orderman/orders/algo/IAlgoOrder.h" + +namespace bts { +namespace orderman { + +// Join starts working N ticks away from the market (usually) and then +// watches for the opposite inside to become same side inside market; +// if there is then enough size on that market, it will join. + +class JoinAlgo : public IAlgoOrder +{ +public: + JoinAlgo(); + ~JoinAlgo(); + + OrderOpResult do_before_launch(IBeforeLaunchAlgoServices&) override; + void do_launch(IAlgoServices &) override; + void do_launch_attached(IAlgoServices&,OrderKey, ChildState) override; + void do_update(api::orderman::Update const &) override; + void on_book(SecurityKey, Book const &) override; + void on_child_change(OrderKey, ChildState const &) override; + +private: + enum class Status; + struct PImpl; + std::unique_ptr me; + + IAlgoServices &algo() const ; + void update_join_threshold(); + bool has_running_child() const; + void try_to_join(); + Price get_price_to_pass (Price price) const; +}; + +}} diff --git a/src/lib/orderman/orders/algo/algo_orders/LeanAlgo.cpp b/src/lib/orderman/orders/algo/algo_orders/LeanAlgo.cpp new file mode 100644 index 000000000..c1cd50f61 --- /dev/null +++ b/src/lib/orderman/orders/algo/algo_orders/LeanAlgo.cpp @@ -0,0 +1,325 @@ +#include "lib/orderman/orders/algo/algo_orders/LeanAlgo.h" + +#include "lib/domain_model/Security.h" +#include "lib/orderman/order_factory/IOrderFactory.h" +#include "lib/orderman/orderman_utils/Book.h" +#include "lib/orderman/orderman_utils/orderman_utils.h" +#include "lib/orderman/orders/algo/IAlgoServices.h" +#include "lib/orderman/orders/spreader_orders/spreader/SpreaderUtils.h" +#include "lib/os/os.h" +#include "lib/utils/PBUtils.h" + +namespace bts { +namespace orderman { + +using namespace api::orderman; + +enum class LeanAlgo::Status { WAITING_FOR_MD, WORKING, DONE }; + +struct LeanAlgo::PImpl { + IAlgoServices* algo_services; + double tick_size = os::nan(); + Status status = Status::WAITING_FOR_MD; + Price initial_observed_price = Price(os::nan()); + Price observed_price = Price(os::nan()); + OrderKey child_key = null_order_key(); + ChildTemplate *child_template = nullptr; + md::PriceSize last_opp_inside = md::PriceSize(); + Book curr_book; + Price out_price = Price(os::nan()); + Quantity out_qty = Quantity(0); + Price cross_price = Price(os::nan()); +}; + +LeanAlgo::LeanAlgo() : me(new PImpl()) {} +LeanAlgo::~LeanAlgo() {} +IAlgoServices &LeanAlgo::algo() const { return *me->algo_services; } + +// initialization ///////////////////////////////////////////////////////////// +/////////////////////////////////////////////////////////////////////////////// +OrderOpResult LeanAlgo::do_before_launch(IBeforeLaunchAlgoServices &serv) { + auto &def = serv.definition(); + me->tick_size = serv.security().contract_spec().low_tick(); + bts_assert(def.has_custom_def()); + bts_assert(def.custom_def().has_lean()); + if (serv.is_attaching()) { + } + else { + auto child_def = def; + *child_def.mutable_custom_def() = + def.custom_def().lean().child(); + me->child_template = &(serv.make_child_template(child_def)); + } + return {}; +} +void LeanAlgo::do_launch(IAlgoServices& algo) { + me->algo_services = &algo; + bts_assert(me->child_template); + _udpate_out_price_qty(algo.price(),algo.quantity()); + me->child_key = algo.launch_child(*me->child_template, algo.price(), algo.quantity()); + LOG(OrderMan, Info, + "LeanAlgo::do_launch key:{} child_key:{} price:{} qty:{}", + algo.order_key().value(),me->child_key, + algo.price(),algo.quantity()); + algo.subscribe_book(SecurityKey(algo.definition().security_key())); +} +void LeanAlgo::do_launch_attached(IAlgoServices&algo, OrderKey k, ChildState st) { + me->algo_services = &algo; + me->child_key = k; + algo.subscribe_book(SecurityKey(algo.definition().security_key())); + on_child_change(k, st); +} +// updates //////////////////////////////////////////////////////////////////// +/////////////////////////////////////////////////////////////////////////////// +void LeanAlgo::do_update(const api::orderman::Update &update) { + LOG(OrderMan, Diag, "LeanOrder order {} receiving update: {}", + algo().order_key().value(), utils::pb::to_string(update)); + + if (update.has_custom() && !update.custom().has_lean()) { + algo().terminate_error("Invalid update"); + return; + } + Update child_update; + Price price_to_pass = _get_price_to_pass(Price(update.price())); + child_update.set_price(price_to_pass.value()); + child_update.set_quantity(update.quantity()); + if (update.has_custom()) { + auto &lean_update = update.custom().lean(); + *child_update.mutable_custom() = lean_update.child(); + } + _udpate_out_price_qty(Price(update.price()),Quantity(update.quantity())); + algo().update_child(me->child_key, child_update); + switch (me->status) { + case LeanAlgo::Status::WAITING_FOR_MD: + break; + case LeanAlgo::Status::WORKING: + _analyze_and_act(); + break; + case LeanAlgo::Status::DONE: + break; + } +} +// callbacks ////////////////////////////////////////////////////////////////// +/////////////////////////////////////////////////////////////////////////////// +void LeanAlgo::on_book(SecurityKey, const Book &book) { + me->curr_book = book; + switch (me->status) { + case LeanAlgo::Status::WAITING_FOR_MD: + if (_opp_inside_market().size() != 0) { + me->initial_observed_price = Price(_opp_inside_market().price()); + me->observed_price = me->initial_observed_price; + me->status = LeanAlgo::Status::WORKING; + _analyze_and_act(); + } + break; + case LeanAlgo::Status::WORKING: + _analyze_and_act(); + break; + case LeanAlgo::Status::DONE: + break; + } +} +void LeanAlgo::on_child_change(OrderKey key, const ChildState &st) { + LOG(OrderMan, Info, + "LeanAlgo::on_child_change key:{} child_key:{} status:{} total_fills:{} " + "last_price:{}", + algo().order_key().value(),key, + static_cast(st.status),st.total_fills,st.last_price); + algo().update_fill_state(st.total_fills, st.last_price); + switch (st.status) { + case ChildStatus::WORKING: + // if this update had fills and qty threshold is + // ratio, should it re-evaluate ? + return; + case ChildStatus::COMPLETED: + me->status = LeanAlgo::Status::DONE; + algo().complete(); + return; + case ChildStatus::CANCELED: + me->status = LeanAlgo::Status::DONE; + algo().cancel("Unexpected child cancel"); + return; + } +} +// accessor helpers /////////////////////////////////////////////////////////// +/////////////////////////////////////////////////////////////////////////////// +Quantity LeanAlgo::_cross_threshold() const{ + auto qty_measure=algo().definition().custom_def().lean().cross_threshold(); + return SpreaderUtils::_quantity_threshold( + qty_measure, Quantity(algo().quantity())); +} +uint32_t LeanAlgo::_max_chase_ticks() const { + return algo().definition().custom_def().lean().max_chase_ticks(); +} +api::orderman::LeanOrderDefinition::OnToward +LeanAlgo::_on_toward_behaviour() const { + return algo().definition().custom_def().lean().trade_toward_behavior(); +} +bool LeanAlgo::_book_moved_toward() const { + return securities::is_better(_opp_side(), + Price(_opp_inside_market().price()), + Price(me->last_opp_inside.price())); +} +bool LeanAlgo::_book_moved_away() const { + return securities::is_better(_opp_side(), + Price(me->last_opp_inside.price()), + Price(_opp_inside_market().price())); +} +md::PriceSize LeanAlgo::_opp_inside_market() const { + return me->curr_book.side(_opp_side())[0]; +} +api::Side LeanAlgo::_opp_side() const { + return securities::other_side(algo().definition().side()); +} +bool LeanAlgo::_within_chase_band(Price price) const{ + return securities::is_better(algo().definition().side(), + me->initial_observed_price, + price) || + static_cast(std::abs( + securities::price_diff_to_ticks(price.value(), + me->initial_observed_price.value(), + me->tick_size))) <= _max_chase_ticks(); +} +Price LeanAlgo::_chase_limit() const{ + double offset=me->tick_size*_max_chase_ticks(); + return securities::improve_price(algo().definition().side(), + me->initial_observed_price, + Price(offset)); +} +LeanAlgo::MarketChange LeanAlgo::_market_change() const{ + md::PriceSize opp_inside=_opp_inside_market(); + if(opp_inside.size()==0) + return MarketChange::NO_MARKET; + else if (_book_moved_away()) + return MarketChange::AWAY; + else if (_book_moved_toward()) + return MarketChange::TOWARD; + else + return MarketChange::SIZE_CHANGE; +} +Price LeanAlgo::_get_price_to_pass (Price price) const{ + // if it has crossed once, then the + // child order is always passed that price + if(!os::is_nan(me->cross_price.value())) + return me->cross_price; + return price; +} +// actions //////////////////////////////////////////////////////////////////// +/////////////////////////////////////////////////////////////////////////////// +void LeanAlgo::_analyze_and_act() { + bts_assert(me->status == LeanAlgo::Status::WORKING); + auto market_change=_market_change(); + me->last_opp_inside=_opp_inside_market(); + switch(market_change){ + case MarketChange::NO_MARKET: + _go_furthest_possible(); + break; + case MarketChange::SIZE_CHANGE: + _try_cross(me->observed_price); + break; + case MarketChange::AWAY: + me->observed_price = Price(_opp_inside_market().price()); + _go_furthest_possible(); + break; + case MarketChange::TOWARD: + _on_toward_me(); + break; + } +} +void LeanAlgo::_on_toward_me() { + switch (_on_toward_behaviour()) { + case LeanOrderDefinition_OnToward_CANCEL: + LOG(OrderMan, Info, + "Canceling LeanAlgo {} because opposite moved towards order", + algo().order_key().value()); + algo().cancel("Opposite inside market moved towards order"); + break; + case LeanOrderDefinition_OnToward_DETACH: + LOG(OrderMan, Info, + "LeanAlgo {} is done because opposite moved towards order", + algo().order_key().value()); + algo().detach_child(me->child_key); + algo().cancel("Opposite inside market moved towards order(detaching)"); + break; + case LeanOrderDefinition_OnToward_REPRICE: + LOG(OrderMan, Diag, + "LeanAlgo {} changing its target to {} because opposite moved " + "towards order", + algo().order_key().value(), _opp_inside_market().price()); + me->observed_price = Price(_opp_inside_market().price()); + _try_cross(me->observed_price); + break; + case LeanOrderDefinition_OnToward_NO_CHANGE: + LOG(OrderMan, Diag, "LeanAlgo {} ignoring opposite move towards order", + algo().order_key().value()); + _try_cross(me->observed_price); + break; + default: + bts_assert(false); + break; + } +} +// this assumes the opposite side is there +// and will always try to cross into the other side +// IF the qty threshold AND chase band condition is met. +// it returns true if it successfully crossed. +bool LeanAlgo::_try_cross(Price price) { + if(_within_chase_band(price)){ + Quantity cumm_qty; + SpreaderUtils::find_qty_upto_price_level(me->curr_book, + _opp_side(), + price, + me->tick_size, + cumm_qty); + Quantity trigger_quantity = _cross_threshold(); + if(cumm_qty.value()observed_price)){ + if(!_try_cross(_chase_limit())){ + // this will only be false if chase_limit is + // on the opposite side and the qty > threshold + // (if it was on the same side, cum_qty==0) + auto opp_inside=_opp_inside_market(); + if(opp_inside.size()>0){ + auto inside = securities::worsen_price(algo().definition().side(), + Price(opp_inside.price()), + Price(me->tick_size)); + _try_cross(inside); + } + else{ + auto inside = me->curr_book.side(algo().definition().side())[0]; + if(inside.size()>0) + _try_cross(Price(inside.price())); + } + } + } +} +void LeanAlgo::_udpate_out_price_qty(Price price, Quantity qty){ + me->out_price=price; + me->out_qty=qty; +} +bool LeanAlgo::_modify_price_price_qty(Price price, Quantity qty){ + if(me->out_price.value()!=price.value() || + me->out_qty.value()!=qty.value()){ + _udpate_out_price_qty(price,qty); + me->cross_price = price; + Update child_update; + child_update.set_price(price.value()), + child_update.set_quantity(qty.value()); + LOG(OrderMan, Info, "LeanAlgo::_try_cross updating child " + "key:{} child_key:{} price:{} qty:{}", + algo().order_key().value(),me->child_key, + child_update.price(),child_update.quantity()); + algo().update_child(me->child_key, child_update); + return true; + } + return false; +} +} // namespace orderman +} // namespace bts diff --git a/src/lib/orderman/orders/algo/algo_orders/LeanAlgo.h b/src/lib/orderman/orders/algo/algo_orders/LeanAlgo.h new file mode 100644 index 000000000..09aea41ba --- /dev/null +++ b/src/lib/orderman/orders/algo/algo_orders/LeanAlgo.h @@ -0,0 +1,51 @@ +#pragma once + +#include "lib/domain_model/Security.pb.h" +#include "lib/md/PriceSize.h" +#include "lib/orderman/orders/algo/IAlgoOrder.h" + +namespace bts { +namespace orderman { + +class LeanAlgo : public IAlgoOrder { + public: + LeanAlgo(); + ~LeanAlgo(); + + public: + OrderOpResult do_before_launch(IBeforeLaunchAlgoServices &) override; + void do_launch(IAlgoServices &) override; + void do_launch_attached(IAlgoServices &, OrderKey, ChildState) override; + void do_update(api::orderman::Update const &) override; + void on_book(SecurityKey, Book const &) override; + void on_child_change(OrderKey, ChildState const &) override; + + private: + enum class MarketChange {NO_MARKET,SIZE_CHANGE,AWAY,TOWARD}; + struct PImpl; + enum class Status; + IAlgoServices &algo() const ; + Quantity _cross_threshold() const; + uint32_t _max_chase_ticks() const; + api::orderman::LeanOrderDefinition::OnToward _on_toward_behaviour() const; + bool _book_moved_toward() const; + bool _book_moved_away() const; + md::PriceSize _opp_inside_market() const; + api::Side _opp_side() const; + bool _within_chase_band(Price price) const; + Price _chase_limit() const; + MarketChange _market_change() const; + Price _get_price_to_pass (Price price) const; + void _analyze_and_act(); + bool _try_cross(Price); + void _go_furthest_possible(); + void _on_toward_me(); + void _udpate_out_price_qty(Price price, Quantity qty); + bool _modify_price_price_qty(Price price, Quantity qty); + + private: + std::unique_ptr me; +}; + +} // namespace orderman +} // namespace bts diff --git a/src/lib/orderman/orders/algo/algo_orders/TopAlgo.cpp b/src/lib/orderman/orders/algo/algo_orders/TopAlgo.cpp new file mode 100644 index 000000000..e16aaa5d8 --- /dev/null +++ b/src/lib/orderman/orders/algo/algo_orders/TopAlgo.cpp @@ -0,0 +1,180 @@ +#include "lib/orderman/orders/algo/algo_orders/TopAlgo.h" + +#include "lib/domain_model/Security.h" +#include "lib/logging/logging.h" +#include "lib/orderman/order_factory/IOrderFactory.h" +#include "lib/orderman/orderman_utils/Book.h" +#include "lib/orderman/orders/algo/IAlgoServices.h" +#include "lib/orderman/orders/spreader_orders/spreader/SpreaderUtils.h" +#include "lib/utils/PBUtils.h" + +namespace bts { +namespace orderman { + +using namespace api::orderman; + +struct TopAlgo::PImpl { + IAlgoServices *algo; + spark::QuantityMeasure top_threshold_measure; + OrderKey child_key = null_order_key(); + ChildTemplate *child_template = nullptr; + Book last_book; +}; + +TopAlgo::TopAlgo() : me(new PImpl()) {} +TopAlgo::~TopAlgo() {} +IAlgoServices &TopAlgo::algo() const { return *me->algo; } + +OrderOpResult TopAlgo::do_before_launch(IBeforeLaunchAlgoServices &serv) { + auto &def = serv.definition(); + bts_assert(def.has_custom_def()); + bts_assert(def.custom_def().has_top()); + + // Validate the top part of the definition + auto &top = def.custom_def().top(); + if (!top.has_child() && + OrderKey(def.attach_target_order_key()) == null_order_key()) { + return OrderOpResult{ + ORDER_ERROR_INVALID_ORDER_DEFINITON, + "Top order must have either a child order definition or an " + "order to attach to"}; + } + + me->top_threshold_measure = top.top_threshold(); + + if (!serv.is_attaching()) { + // if we are not attaching create a child template so we can + // quickly launch our child when the time comes. + auto child_def = def; + *child_def.mutable_custom_def() = def.custom_def().top().child(); + me->child_template = &(serv.make_child_template(child_def)); + } + + return {}; +} + +void TopAlgo::do_launch(IAlgoServices &algo) { + me->algo = &algo; + algo.subscribe_book(SecurityKey(algo.security().id())); + bts_assert(me->child_template); + me->child_key = + algo.launch_child(*me->child_template, algo.price(), algo.quantity()); +} + +void TopAlgo::do_launch_attached(IAlgoServices &algo, OrderKey k, + ChildState st) { + me->algo = &algo; + me->child_key = k; + algo.subscribe_book(SecurityKey(algo.security().id())); + on_child_change(k, st); +} + +void TopAlgo::do_update(api::orderman::Update const &update) { + LOG(OrderMan, Diag, "Top order {} receiving update: {}", + algo().order_key().value(), utils::pb::to_string(update)); + + if (update.has_custom() && !update.custom().has_top()) { + algo().terminate_error("Invalid update"); + return; + } + + Update child_update; + child_update.set_price(update.price()); + child_update.set_quantity(update.quantity()); + + if (update.has_custom()) { + // process custom part of the udpate if any + auto &top_update = update.custom().top(); + *child_update.mutable_custom() = top_update.child(); + me->top_threshold_measure = top_update.top_threshold(); + } + algo().update_child(me->child_key, child_update); +} + +void TopAlgo::on_book(SecurityKey, Book const &b) { + me->last_book = b; + ensure_min_quantity(); +} + +void TopAlgo::on_child_change(OrderKey, ChildState const &st) { + algo().update_fill_state(st.total_fills, st.last_price); + + switch (st.status) { + case ChildStatus::WORKING: + return; + case ChildStatus::COMPLETED: + algo().complete(); + return; + case ChildStatus::CANCELED: + algo().cancel("Unexpected child cancel"); + return; + } +} + +bool TopAlgo::ensure_min_quantity() { + LOG(OrderMan, Diag, + "Top order {} received book update. Current top of book: {}@{}", + algo().order_key().value(), top_of_book_quantity().value(), + top_of_book_price().value()); + + if (better_than_top()) { + LOG(OrderMan, Diag, + "Top order {} became better than the top of the book, canceling", + algo().order_key().value()); + algo().cancel("Order would become BBO"); + return false; + } + + if (at_top_of_book()) { + auto total_min_quantity = + algo().quantity().value() + min_quantity_at_top().value(); + LOG(OrderMan, Diag, + "Top order {} is now at the top of the book, min quantity for book " + "is: {}" + " book quantity is: {}", + algo().order_key().value(), total_min_quantity, + top_of_book_quantity().value()); + if (top_of_book_quantity() < Quantity(total_min_quantity)) { + LOG(OrderMan, Diag, + "Top order {} is canceling because min quantiy is not met", + algo().order_key().value()); + algo().cancel("Top of book is below threshold"); + return false; + } + } else + LOG(OrderMan, Diag, + "Top order {} is not at the top of the book. Order: {} Book: {}", + algo().order_key().value(), algo().price().value(), + top_of_book_price().value()); + + return true; +} + +bool TopAlgo::at_top_of_book() const { + return securities::is_same(algo().price(), top_of_book_price()); +} + +bool TopAlgo::better_than_top() const { + auto my_side = algo().definition().side(); + return securities::is_better(my_side, algo().price(), top_of_book_price()); +} + +Quantity TopAlgo::min_quantity_at_top() const { + return SpreaderUtils::_quantity_threshold(me->top_threshold_measure, + algo().quantity()); +} + +Price TopAlgo::top_of_book_price() const { + auto my_side = algo().definition().side(); + auto &my_side_psz = me->last_book.side(my_side)[0]; + return Price(my_side_psz.price()); +} + +Quantity TopAlgo::top_of_book_quantity() const { + auto my_side = algo().definition().side(); + auto &my_side_psz = me->last_book.side(my_side)[0]; + return Quantity(my_side_psz.size()); +} + +} // namespace orderman +} // namespace bts diff --git a/src/lib/orderman/orders/algo/algo_orders/TopAlgo.h b/src/lib/orderman/orders/algo/algo_orders/TopAlgo.h new file mode 100644 index 000000000..3648dc50c --- /dev/null +++ b/src/lib/orderman/orders/algo/algo_orders/TopAlgo.h @@ -0,0 +1,38 @@ +#pragma once + +#include "lib/orderman/orders/algo/IAlgoOrder.h" + +namespace bts { +namespace orderman { + +// If Top becomes the top of book, it cancels if there is less than +// some threshold of size joined with it. + +class TopAlgo : public IAlgoOrder { + public: + TopAlgo(); + ~TopAlgo(); + + OrderOpResult do_before_launch(IBeforeLaunchAlgoServices&) override; + void do_launch(IAlgoServices &) override; + void do_launch_attached(IAlgoServices&,OrderKey, ChildState) override; + void do_update(api::orderman::Update const &) override; + void on_book(SecurityKey, Book const &) override; + void on_child_change(OrderKey, ChildState const &) override; + + private: + struct PImpl; + std::unique_ptr me; + + bool at_top_of_book() const; + bool better_than_top() const; + Quantity min_quantity_at_top() const; + bool ensure_min_quantity(); + bool has_running_child() const; + Price top_of_book_price() const; + Quantity top_of_book_quantity() const; + IAlgoServices& algo() const; +}; + +} // namespace orderman +} // namespace bts diff --git a/src/lib/orderman/orders/book_algos/BookAlgo.cpp b/src/lib/orderman/orders/book_algos/BookAlgo.cpp index 4c8874cda..d16d9e59b 100644 --- a/src/lib/orderman/orders/book_algos/BookAlgo.cpp +++ b/src/lib/orderman/orders/book_algos/BookAlgo.cpp @@ -3,6 +3,7 @@ #include "lib/utils/helper_macros.h" #include "lib/orderman/actors/order_manager/OrderBuilder.h" #include +#include "lib/orderman/orders/PreActivationOrderServices.h" namespace bts { namespace orderman { @@ -137,12 +138,12 @@ void BookAlgo::on_init_new(const api::orderman::OrderDefinition& def, me->child_state.set_status(ORDER_STATUS_INACTIVE); OrderDefinition child_def = def; setup_child(def, services, me->child_state, &child_def); - me->child_builder = OrderBuilder(key(), child_def, services, 1); + me->child_builder = OrderBuilder(key(), child_def, services.order_factory, 1); OrderDefinition hedge_def = def; me->supports_hedge = setup_hedge(def, services, &hedge_def); if(me->supports_hedge) - me->hedge_builder = OrderBuilder(key(), hedge_def, services, 4); + me->hedge_builder = OrderBuilder(key(), hedge_def, services.order_factory, 4); const bts::api::Security* sec = services.sec_db.resolve(SecurityKey(def.security_key())); if(sec) @@ -191,8 +192,7 @@ void BookAlgo::on_init_recovered(const api::orderman::OrderRecord& rec, } } -void BookAlgo::on_activate(Price p, Quantity q, OrderServices& services, trace::CorID const&) -{ +OrderOpResult BookAlgo::on_activate(Price p, Quantity q, OrderServices &services) { bts_assert(!me->services); me->services = &services; switch (this_state().status()) @@ -231,10 +231,10 @@ void BookAlgo::on_activate(Price p, Quantity q, OrderServices& services, trace:: break; } report_state(); + return OrderOpResult{}; } -void BookAlgo::on_update(Price p, Quantity q, trace::CorID const&) -{ +OrderOpResult BookAlgo::on_update(Price p, Quantity q) { LOG(OrderMan, Info, "Updating BookAlgo {}", key().value()); switch (this_state().status()) { @@ -288,12 +288,10 @@ void BookAlgo::on_update(Price p, Quantity q, trace::CorID const&) break; } report_state(); + return OrderOpResult{}; } -void BookAlgo::on_crack(trace::CorID const&) {} - -void BookAlgo::on_cancel(trace::CorID const&) -{ +OrderOpResult BookAlgo::on_cancel() { LOG(OrderMan, Info, "Canceling BookAlgo Order {}", key().value()); switch (this_state().status()) @@ -308,7 +306,7 @@ void BookAlgo::on_cancel(trace::CorID const&) if(!me->is_detached) me->child.cancel(); for(auto& i : me->hedges) - i.second.crack(); + i.second.detach(); transition(ORDER_STATUS_CANCELED); break; case ORDER_STATUS_PENDING_WORKING: @@ -345,6 +343,7 @@ void BookAlgo::on_cancel(trace::CorID const&) break; } report_state(); + return OrderOpResult{}; } void BookAlgo::transition(api::orderman::OrderStatus new_status, std::string msg) @@ -491,8 +490,7 @@ void BookAlgo::paydown(const md::PriceSize& opposite, const bts::orderman::BookU void BookAlgo::detach(bts::api::orderman::OrderStatus status_after_detach) { - me->is_detached = true; - me->child.crack(); + me->child.detach(); transition(status_after_detach); report_state(); } diff --git a/src/lib/orderman/orders/book_algos/BookAlgo.h b/src/lib/orderman/orders/book_algos/BookAlgo.h index 312f81ff7..396fdcb8d 100644 --- a/src/lib/orderman/orders/book_algos/BookAlgo.h +++ b/src/lib/orderman/orders/book_algos/BookAlgo.h @@ -19,15 +19,14 @@ class BookAlgo : public Order public: BookAlgo(); virtual ~BookAlgo(); - const api::orderman::OrderDefinition& definition() const override; + const api::orderman::OrderDefinition& definition() const ; void on_init_new(const api::orderman::OrderDefinition&, const PreActivationOrderServices&) override; void on_init_recovered(const api::orderman::OrderRecord&, const PreActivationOrderServices &) override; - void on_activate(Price,Quantity,OrderServices &, trace::CorID const&) override ; - void on_update(Price , Quantity,trace::CorID const&) override ; - void on_crack(trace::CorID const&) override ; - void on_cancel(trace::CorID const&) override ; + OrderOpResult on_activate(Price,Quantity,OrderServices &) override ; + OrderOpResult on_update(Price , Quantity) override ; + OrderOpResult on_cancel() override ; protected: virtual void setup_child(const api::orderman::OrderDefinition& parent, const PreActivationOrderServices&, diff --git a/src/lib/orderman/orders/book_algos/BookOrderBase.cpp b/src/lib/orderman/orders/book_algos/BookOrderBase.cpp new file mode 100644 index 000000000..b26938f65 --- /dev/null +++ b/src/lib/orderman/orders/book_algos/BookOrderBase.cpp @@ -0,0 +1,750 @@ +#include "BookOrderBase.h" +#include "lib/domain_model/Security.h" +#include "lib/orderman/actors/order_manager/ChildOrder.h" +#include "lib/orderman/orderman_utils/orderman_utils.h" +#include "lib/orderman/orders/PreActivationOrderServices.h" +#include "lib/utils/PBUtils.h" +#include "lib/utils/bts_assert.h" +#include "lib/utils/type_name.h" + +namespace bts { +namespace orderman { + +using namespace api::orderman; + +enum class BookOrderBase::InternalStatus { + INACTIVE, + W_ATTACH, + W_MD, + WORKING, + INERT, + COMPLETED +}; + +struct BookOrderBase::PImpl { + InternalStatus internal_status = InternalStatus::INACTIVE; + ChildOrder child; + OrderServices *services = nullptr; + OrderDefinition definition; + const api::Security *security; + OrderState state; + Book book_at_inception; + Book last_book; + OrderState child_state; + OrderServices::BookSubID book_sid; + std::unique_ptr pending_update; + + std::string type_name; + OrderStatus external_status() { return state.status(); } + void set_external_status(OrderStatus s) { state.set_status(s); } +}; + +BookOrderBase::BookOrderBase() : me(new PImpl()) { + me->type_name = utils::type_name(typeid(*this)); +} +BookOrderBase::~BookOrderBase() {} + +void BookOrderBase::on_init_new(OrderDefinition const &def, + const PreActivationOrderServices &serv) { + bts_assert(def.has_custom_def()); + + // Save our order definition + me->definition = def; + me->security = serv.sec_db.resolve(SecurityKey(def.security_key())); + if (me->security == nullptr) { + terminate(ORDER_STATUS_REJECTED_BY_SPARK, "Unknown security"); + transition(InternalStatus::COMPLETED); + } + + auto result = do_on_init_new(serv); + if (result.fail()) { + terminate(ORDER_STATUS_REJECTED_BY_SPARK, result.error_msg); + transition(InternalStatus::COMPLETED); + } +} + +void BookOrderBase::on_init_recovered(OrderRecord const &rec, + const PreActivationOrderServices &) { + auto const &def = rec.def(); + me->definition = def; + me->state = rec.state(); + + // Infer internal status from persisted external status + switch (me->external_status()) { + + case ORDER_STATUS_WORKING: + case ORDER_STATUS_PENDING_WORKING: + terminate(ORDER_STATUS_REJECTED_BY_SPARK, + "System restarted with active algo order"); + return; + + // terminal states + case ORDER_STATUS_ERROR: + case ORDER_STATUS_REJECTED_BY_SPARK: + case ORDER_STATUS_COMPLETED: + case ORDER_STATUS_CANCELED: + terminate(rec.state().status(), rec.state().last_msg()); + break; + + case ORDER_STATUS_DISCONNECTED: + case ORDER_STATUS_INACTIVE: + case OrderStatus_INT_MIN_SENTINEL_DO_NOT_USE_: + case OrderStatus_INT_MAX_SENTINEL_DO_NOT_USE_: + bts_assert(false); + break; + } +} + +OrderOpResult BookOrderBase::on_activate(Price p, Quantity q, + OrderServices &services) { + bts_assert(!me->services); + me->services = &services; + + switch (me->internal_status) { + + case InternalStatus::INACTIVE: { + me->state.set_price(p.value()); + me->state.set_quantity(q.value()); + + if (q.value() == 0) + terminate(ORDER_STATUS_COMPLETED); + else + transition(InternalStatus::W_MD); + return report_and_return(); + } + case InternalStatus::COMPLETED: + return report_and_return(); + + case InternalStatus::W_ATTACH: + + case InternalStatus::WORKING: + case InternalStatus::W_MD: + case InternalStatus::INERT: + bts_assert(false); + break; + } + + bts_assert(false); + return report_and_return(); +} + +OrderOpResult BookOrderBase::on_update(Update const &update) { + switch (me->internal_status) { + + case InternalStatus::W_MD: + case InternalStatus::W_ATTACH: + me->pending_update = std::make_unique(update); + return OrderOpResult{}; + + case InternalStatus::COMPLETED: + return OrderOpResult(ORDER_ERROR_INVALID_OP, + "Order is already completed"); + + case InternalStatus::INERT: + case InternalStatus::WORKING: { + auto r = do_on_update(update); + if (r.ok()) { + // Copy the new custom parameters if any + if (update.has_custom()) { + *me->definition.mutable_custom_def() = update.custom(); + me->services->report_definition(me->definition); + } + } + return report_and_return(r); + } + case InternalStatus::INACTIVE: + break; + } + + bts_assert(false); + return OrderOpResult{}; +} + +OrderOpResult BookOrderBase::on_update(Price p, Quantity q) { + Update up; + up.set_price(p.value()); + up.set_quantity(q.value()); + return on_update(up); +} + +orderman::OrderOpResult BookOrderBase::on_detach() { + LOG(OrderMan, Info, "{} order with key {} received detach", me->type_name, + key().value()); + + switch (me->internal_status) { + + case InternalStatus::W_MD: + case InternalStatus::W_ATTACH: + case InternalStatus::WORKING: + case InternalStatus::INERT: + me->child = ChildOrder{}; + terminate(ORDER_STATUS_CANCELED); + break; + + case InternalStatus::COMPLETED: + break; + + case InternalStatus::INACTIVE: + bts_assert(false); + break; + } + return report_and_return(); +} + +orderman::OrderOpResult BookOrderBase::on_cancel() { + switch (me->internal_status) { + case InternalStatus::W_MD: + case InternalStatus::W_ATTACH: + case InternalStatus::WORKING: + case InternalStatus::INERT: + terminate(ORDER_STATUS_CANCELED); + return report_and_return(); + + case InternalStatus::COMPLETED: + return report_and_return(); + + case InternalStatus::INACTIVE: + break; + } + + // compiler + bts_assert(false); + return OrderOpResult{}; +} + +bool BookOrderBase::is_attaching() const { + auto ak = OrderKey(me->definition.attach_target_order_key()); + return (ak != null_order_key() && + !should_forward_attachment(me->definition.custom_def())); +} + +void BookOrderBase::on_book_update(const BookUpdateEvent &ev) { + + switch (me->internal_status) { + + case InternalStatus::W_MD: { + if (ev.book.side(api::SIDE_SELL)[0].size() && + ev.book.side(api::SIDE_BUY)[0].size()) { + + me->book_at_inception = ev.book; + me->last_book = ev.book; + + if (is_attaching()) + transition(InternalStatus::W_ATTACH); + else + transition(InternalStatus::WORKING); + report_and_return(); + } + return; + } + + case InternalStatus::WORKING: + me->last_book = ev.book; + do_on_book(ev.book); + return; + + case InternalStatus::W_ATTACH: + case InternalStatus::COMPLETED: + case InternalStatus::INERT: + return; + + case InternalStatus::INACTIVE: + bts_assert(false); + break; + } + bts_assert(false); +} + +void BookOrderBase::unsubscribe_from_book() { + if (!me->book_sid.empty()) { + me->services->unsubscribe_from_book(me->book_sid); + me->book_sid.clear(); + } +} + +void BookOrderBase::on_attach_complete(OrderOpResult r, ChildOrder const &child, + api::orderman::OrderDefinition const &, + api::orderman::OrderState const &state) { + + switch (me->internal_status) { + + case InternalStatus::W_ATTACH: + if (r.ok()) { + + LOG(OrderMan, Info, "{} order with key {} successfully attached to {}", + me->type_name, key().value(), child.key().value()); + + // Cache the attached order and its state + me->child = child; + me->child_state = state; + + // transition + transition(InternalStatus::WORKING); + } else { + terminate_error(fmt::format( + "{} order with key {} failed to attach to {}: {}", me->type_name, + key().value(), me->definition.attach_target_order_key(), + r.error_msg)); + } + break; + + case InternalStatus::COMPLETED: + break; + + case InternalStatus::INACTIVE: + case InternalStatus::W_MD: + case InternalStatus::WORKING: + case InternalStatus::INERT: + bts_assert(false); + break; + } + report_and_return(); +} + +void BookOrderBase::on_child_order_update(OrderStateUpdateEvent const &ev) { + on_child_order_update(ev.key, ev.rebuild_state()); +} + +void BookOrderBase::on_child_order_update( + OrderKey child_key, api::orderman::OrderState const &child_state) { + switch (me->internal_status) { + case InternalStatus::INERT: + case InternalStatus::WORKING: + if (child_key == me->child.key()) { + switch (child_state.status()) { + + case ORDER_STATUS_WORKING: + case ORDER_STATUS_PENDING_WORKING: + me->child_state = child_state; + do_on_child_order_update(child_key, child_state); + report_and_return(); + return; + + case ORDER_STATUS_COMPLETED: + me->child_state = child_state; + do_on_child_order_update(child_key, child_state); + if (me->internal_status != InternalStatus::COMPLETED) + terminate(ORDER_STATUS_COMPLETED); + report_and_return(); + return; + + case ORDER_STATUS_CANCELED: + case ORDER_STATUS_DISCONNECTED: + case ORDER_STATUS_REJECTED_BY_SPARK: + case ORDER_STATUS_ERROR: + terminate_error("Unexpected child order state"); + return; + + case ORDER_STATUS_INACTIVE: + case OrderStatus_INT_MIN_SENTINEL_DO_NOT_USE_: + case OrderStatus_INT_MAX_SENTINEL_DO_NOT_USE_: + bts_assert(false); + return; + } + } else { + // This is not the child we manage. All we care about is + // catching errors + switch (child_state.status()) { + + case ORDER_STATUS_DISCONNECTED: + case ORDER_STATUS_CANCELED: + case ORDER_STATUS_COMPLETED: + case ORDER_STATUS_WORKING: + case ORDER_STATUS_PENDING_WORKING: + return; + + case ORDER_STATUS_REJECTED_BY_SPARK: + case ORDER_STATUS_ERROR: + terminate_error("Unexpected child order state"); + return; + + case ORDER_STATUS_INACTIVE: + case OrderStatus_INT_MIN_SENTINEL_DO_NOT_USE_: + case OrderStatus_INT_MAX_SENTINEL_DO_NOT_USE_: + bts_assert(false); + return; + } + } + return; + case InternalStatus::COMPLETED: + break; + case InternalStatus::INACTIVE: + case InternalStatus::W_ATTACH: + case InternalStatus::W_MD: + bts_assert(false); + break; + } +} + +void BookOrderBase::update_child(api::orderman::Update &u) { + bts_assert(me->internal_status == InternalStatus::WORKING); + bts_assert(!me->child.empty()); + me->child.update(u, [this](auto const &r) { on_child_update_completed(r); }); +} + +void BookOrderBase::update_child(Price p, Quantity q) { + Update up; + up.set_price(p.value()); + up.set_quantity(q.value()); + update_child(up); +} + +void BookOrderBase::on_child_update_completed(OrderOpResult r) { + + if (r.error == ORDER_ERROR_OK) + return; + + switch (me->internal_status) { + case InternalStatus::WORKING: + on_detach(); + return; + + case InternalStatus::INERT: + case InternalStatus::COMPLETED: + case InternalStatus::W_MD: + case InternalStatus::W_ATTACH: + case InternalStatus::INACTIVE: + break; + } + bts_assert(false); +} + +OrderOpResult BookOrderBase::report_and_return(api::orderman::OrderError e, + std::string const &msg) { + return report_and_return({e, msg}); +} + +OrderOpResult BookOrderBase::report_and_return(OrderOpResult r) { + me->state.set_filled_quantity(me->child_state.filled_quantity()); + me->state.set_last_price(me->child_state.last_price()); + me->state.set_avg_price(me->child_state.avg_price()); + me->services->report_state(me->state); + return r; +} + +void BookOrderBase::terminate_error(std::string const &error) { + me->set_external_status(ORDER_STATUS_ERROR); + if (error.size()) + me->state.set_last_msg(error); + + // If we attached we do not want to cancel our child + if (is_attaching()) + me->child = ChildOrder{}; + + transition(InternalStatus::COMPLETED); +} + +void BookOrderBase::terminate(api::orderman::OrderStatus st, + std::string const &error) { + me->set_external_status(st); + if (error.size()) + me->state.set_last_msg(error); + transition(InternalStatus::COMPLETED); +} + +void BookOrderBase::transition(InternalStatus new_state) { + + // From INACTIVE + if (me->internal_status == InternalStatus::INACTIVE) { + + // To WAITING_FOR_MD + if (new_state == InternalStatus::W_MD) { + me->book_sid = me->services->subscribe_to_book( + SecurityKey(me->definition.security_key()), + [this](auto const &ev) { this->on_book_update(ev); }); + me->services->subscribe_to_child_updates( + [this](auto const &u) { this->on_child_order_update(u); }); + me->set_external_status(ORDER_STATUS_WORKING); + _transition(new_state); + return; + } + + // To COMPLETED + if (new_state == InternalStatus::COMPLETED) { + _transition(new_state); + return; + } + } + + // From WAITING_FOR_MD + if (me->internal_status == InternalStatus::W_MD) { + + // To PENDING_ATTACH + if (new_state == InternalStatus::W_ATTACH) { + me->services->attach( + OrderKey(me->definition.attach_target_order_key()), + [this](auto result, auto const &child_order, auto const &child_def, + auto const &child_state) { + this->on_attach_complete(result, child_order, child_def, + child_state); + }); + _transition(new_state); + return; + } + + // To WORKING + if (new_state == InternalStatus::WORKING) { + _transition(new_state); + do_on_ready(*me->services, false); + return; + } + + // To COMPLETED + if (new_state == InternalStatus::COMPLETED) { + unsubscribe_from_book(); + _transition(new_state); + return; + } + } + + // From PENDING_ATTACH + if (me->internal_status == InternalStatus::W_ATTACH) { + + // To WORKING + if (new_state == InternalStatus::WORKING) { + _transition(new_state); + do_on_ready(*me->services, true); + + // If we are still in the working state, and if we need to + // check because the do_on_ready() call could have + // transitioned us, and we have an external update pending, + // we send it along now. + if (me->internal_status == InternalStatus::WORKING && + me->pending_update) { + auto r = do_on_update(*me->pending_update); + + if (r.ok()) { + // Copy the new custom parameters if any + if (me->pending_update->has_custom()) { + *me->definition.mutable_custom_def() = me->pending_update->custom(); + me->services->report_definition(me->definition); + } + } else if (me->internal_status == InternalStatus::WORKING) { + // The buffered update we received failed. We cannot + // reply to the original sender because that call stack + // is gone (this is when a continuation based response + // would be usefull) so we force a detach() and report + // the error + me->child = ChildOrder{}; + me->pending_update.reset(); + terminate_error( + fmt::format("Buffered update failed: {}", r.error_msg)); + } + return; + } + + // If we are still in the working state here (and we might + // not be since we transfered control above) we now propagate + // the state we received at attach time as if we received it + // as a regular child state update. This makes the code + // easier since we do not have to distinguish the attach case + // from the regular one. + if (me->internal_status == InternalStatus::WORKING) { + on_child_order_update(me->child.key(), me->child_state); + } + return; + } + + // To COMPLETED + if (new_state == InternalStatus::COMPLETED) { + me->pending_update.reset(); + unsubscribe_from_book(); + _transition(new_state); + return; + } + } + + // From WORKING + if (me->internal_status == InternalStatus::WORKING) { + + // To COMPLETED + if (new_state == InternalStatus::COMPLETED) { + if (!me->child.empty()) { + me->child.cancel(); + me->child = ChildOrder{}; + } + me->pending_update.reset(); + unsubscribe_from_book(); + _transition(new_state); + return; + } + + // To INERT + if (new_state == InternalStatus::INERT) { + me->pending_update.reset(); + unsubscribe_from_book(); + _transition(new_state); + return; + } + } + + // From INERT + if (me->internal_status == InternalStatus::INERT) { + if (new_state == InternalStatus::COMPLETED) { + if (!me->child.empty()) { + me->child.cancel(); + me->child = ChildOrder{}; + } + _transition(new_state); + return; + } + } + + // Everything else is verbotten + LOG(OrderMan, Fatal, "Illegal transition from {} to {}", + state_name(me->internal_status), state_name(new_state)); + bts_assert(false); +} + +void BookOrderBase::check_invariants() { + switch (me->internal_status) { + + case InternalStatus::INACTIVE: + bts_assert(false); + return; + + case InternalStatus::W_MD: + bts_assert(me->security); + bts_assert(me->child.empty()); + bts_assert(me->external_status() == ORDER_STATUS_WORKING); + bts_assert(me->child_state.status() == ORDER_STATUS_INACTIVE); + bts_assert(!me->book_sid.empty()); + bts_assert(never_saw_md()); + break; + + case InternalStatus::W_ATTACH: + bts_assert(me->security); + bts_assert(me->child.empty()); + bts_assert(me->external_status() == ORDER_STATUS_WORKING); + bts_assert(me->child_state.status() == ORDER_STATUS_INACTIVE); + bts_assert(!me->book_sid.empty()); + bts_assert(!never_saw_md()); + break; + + case InternalStatus::WORKING: + bts_assert(me->security); + bts_assert(me->external_status() == ORDER_STATUS_WORKING); + bts_assert(!never_saw_md()); + break; + + case InternalStatus::INERT: + bts_assert(!me->child.empty()); + bts_assert(me->external_status() == ORDER_STATUS_WORKING); + bts_assert(!never_saw_md()); + bts_assert(me->book_sid.empty()); + bts_assert(!me->pending_update); + break; + + case InternalStatus::COMPLETED: + bts_assert(me->child.empty()); + bts_assert(me->external_status() == ORDER_STATUS_CANCELED || + me->external_status() == ORDER_STATUS_COMPLETED || + me->external_status() == ORDER_STATUS_ERROR || + me->external_status() == ORDER_STATUS_REJECTED_BY_SPARK); + bts_assert(me->book_sid.empty()); + bts_assert(!me->pending_update); + break; + } +} + +bool BookOrderBase::never_saw_md() { + return me->book_at_inception.ask()[0].size() == 0 && + me->book_at_inception.bid()[0].size() == 0 && + me->last_book.ask()[0].size() == 0 && + me->last_book.bid()[0].size() == 0; +} + +void BookOrderBase::_transition(InternalStatus st) { + LOG(OrderMan, Info, "Transitioninig {} with key {} from {} to {}", + me->type_name, key().value(), state_name(me->internal_status), + state_name(st)); + me->internal_status = st; + check_invariants(); +} + +api::orderman::OrderDefinition const &BookOrderBase::definition() const { + return me->definition; +} + +api::orderman::OrderState &BookOrderBase::state() { return me->state; } +api::orderman::OrderState const &BookOrderBase::state() const { + return me->state; +} + +void BookOrderBase::cancel(std::string const &msg) { + bts_assert(me->internal_status == InternalStatus::WORKING); + terminate(ORDER_STATUS_CANCELED, msg); + report_and_return(); +} + +void BookOrderBase::detach(std::string const &msg) { + bts_assert(me->internal_status == InternalStatus::WORKING); + bts_assert(!me->child.empty()); + + if (parent_key() == null_order_key()) { + if (msg.size()) + me->state.set_last_msg(msg); + me->child = ChildOrder{}; + terminate(ORDER_STATUS_CANCELED); + } else + transition(InternalStatus::INERT); + + report_and_return(); +} + +OrderKey BookOrderBase::child_key() const { return me->child.key(); } + +Book const &BookOrderBase::last_book() const { return me->last_book; } + +Book const &BookOrderBase::book_at_inception() const { + return me->book_at_inception; +} + +Price BookOrderBase::tick_size() const { + bts_assert(me->internal_status == InternalStatus::WORKING); + return Price(me->security->contract_spec().low_tick()); +} + +md::PriceSize BookOrderBase::other_side_top_of_book() const { + return last_book().side(other_side())[0]; +} + +md::PriceSize BookOrderBase::my_side_top_of_book() const { + return last_book().side(my_side())[0]; +} + +api::Side BookOrderBase::my_side() const { return definition().side(); } + +api::Side BookOrderBase::other_side() const { + return securities::other_side(my_side()); +} + +void BookOrderBase::launch_child( + api::orderman::OrderDefinition const &child_def) { + bts_assert(me->internal_status == InternalStatus::WORKING); + bts_assert(me->child.empty()); + me->child = ChildOrder{child_def, *me->services}; + me->child.activate(Price(me->state.price()), Quantity(me->state.quantity())); +} + +log::CharPtrWrapper BookOrderBase::state_name(InternalStatus st) { + switch (st) { + case InternalStatus::W_MD: + return {"W_MD"}; + case InternalStatus::COMPLETED: + return {"COMPLETED"}; + case InternalStatus::W_ATTACH: + return {"W_ATTACH"}; + case InternalStatus::INACTIVE: + return {"INACTIVE"}; + case InternalStatus::WORKING: + return {"WORKING"}; + case InternalStatus::INERT: + return {"INERT"}; + } + bts_assert(false); + return {""}; +} + +} // namespace orderman +} // namespace bts diff --git a/src/lib/orderman/orders/book_algos/BookOrderBase.h b/src/lib/orderman/orders/book_algos/BookOrderBase.h new file mode 100644 index 000000000..9336466b9 --- /dev/null +++ b/src/lib/orderman/orders/book_algos/BookOrderBase.h @@ -0,0 +1,89 @@ +#pragma once + +#include "lib/api/services/OrderService.server.pb.h" +#include "lib/logging/logging.h" +#include "lib/md/PriceSize.h" +#include "lib/orderman/orders/Order.h" + +#include + +namespace bts { +namespace orderman { + +class OrderStateUpdateEvent; +class BookUpdateEvent; +class Book; + +class IOrderFactory; + +class BookOrderBase : public Order { + public: + BookOrderBase(); + ~BookOrderBase(); + void on_init_new(api::orderman::OrderDefinition const &, + const PreActivationOrderServices &) override; + void on_init_recovered(api::orderman::OrderRecord const &, + const PreActivationOrderServices &) override; + OrderOpResult on_activate(Price, Quantity, OrderServices &) override; + OrderOpResult on_update(api::orderman::Update const &) override; + OrderOpResult on_update(Price, Quantity) override; + OrderOpResult on_cancel() override; + OrderOpResult on_detach() override; + + protected: + virtual OrderOpResult do_on_init_new(const PreActivationOrderServices &) = 0; + virtual void do_on_book(Book const &) {}; + virtual void do_on_ready(OrderServices &,bool is_attached) = 0; + virtual void do_on_child_order_update(OrderKey, + api::orderman::OrderState const &) {} + virtual OrderOpResult do_on_update(api::orderman::Update const &) = 0; + + void cancel(std::string const &msg = ""); + void detach(std::string const &msg = ""); + void unsubscribe_from_book(); + api::orderman::OrderDefinition const &definition() const; + api::orderman::OrderState &state(); + api::orderman::OrderState const &state() const; + void launch_child(api::orderman::OrderDefinition const &child_def); + void update_child(Price p, Quantity q); + void update_child(api::orderman::Update &); + OrderKey child_key() const; + Book const &last_book() const; + Book const &book_at_inception() const; + Price tick_size() const; + api::Side my_side() const; + api::Side other_side() const; + md::PriceSize other_side_top_of_book() const; + md::PriceSize my_side_top_of_book() const; + + private: + enum class InternalStatus; + struct PImpl; + std::unique_ptr me; + + OrderOpResult + report_and_return(api::orderman::OrderError = api::orderman::ORDER_ERROR_OK, + std::string const & = ""); + + OrderOpResult report_and_return(OrderOpResult); + void on_book_update(const BookUpdateEvent &); + void on_child_order_update(const OrderStateUpdateEvent &); + void on_child_order_update(OrderKey child_key, + api::orderman::OrderState const &); + void transition(InternalStatus); + void _transition(InternalStatus); + OrderOpResult on_activate_attach(); + void on_attach_complete(OrderOpResult, ChildOrder const &, + api::orderman::OrderDefinition const &, + api::orderman::OrderState const &); + log::CharPtrWrapper state_name(InternalStatus); + void terminate_error(std::string const&msg); + void terminate(api::orderman::OrderStatus, std::string const &error = ""); + void check_invariants(); + bool never_saw_md(); + void on_child_update_completed(OrderOpResult r); + bool is_attaching() const ; +}; + +} // namespace orderman +} // namespace bts diff --git a/src/lib/orderman/orders/book_algos/CoverOrder.cpp b/src/lib/orderman/orders/book_algos/CoverOrder.cpp deleted file mode 100644 index fcb5d76af..000000000 --- a/src/lib/orderman/orders/book_algos/CoverOrder.cpp +++ /dev/null @@ -1,121 +0,0 @@ -#include "CoverOrder.h" - -#include "lib/orderman/actors/order_manager/OrderBuilder.h" -#include "lib/orderman/orders/spreader_orders/spreader/SpreaderUtils.h" -#include "lib/utils/PBUtils.h" -#include - -namespace bts { -namespace orderman { - -using namespace api::orderman; - -struct CoverOrder::PImpl -{ - PImpl() {} - - int hedge_ticks; - OrderDefinition hedge_def; -}; - - -CoverOrder::CoverOrder() : me(new PImpl()) {} - -CoverOrder::~CoverOrder() {} - -void CoverOrder::setup_child(const api::orderman::OrderDefinition& this_def, const PreActivationOrderServices&, - api::orderman::OrderState& initial_state, api::orderman::OrderDefinition* out_child) -{ - initial_state.mutable_cover(); - auto const &cover_def = this_def.custom_def().cover(); - *out_child->mutable_custom_def() = cover_def.child(); - - me->hedge_ticks = cover_def.hedge_ticks(); -} - -bool CoverOrder::setup_hedge(const api::orderman::OrderDefinition& this_def, const PreActivationOrderServices&, - api::orderman::OrderDefinition* out_hedge) -{ - auto const &cover_def = this_def.custom_def().cover(); - if(cover_def.has_hedge()) - { - *out_hedge->mutable_custom_def() = cover_def.hedge(); - if(definition().side() == api::SIDE_BUY) - out_hedge->set_side(api::SIDE_SELL); - else - out_hedge->set_side(api::SIDE_BUY); - return true; - } - else - return false; -} - -void CoverOrder::process_child_state_change(const api::orderman::OrderState& orig_state, const OrderStateUpdateEvent& new_state) -{ - uint32_t qty = new_state.filled_quantity - orig_state.filled_quantity(); - if(qty > 0) - { - double prx = new_state.last_price; - if(definition().side() == api::SIDE_BUY) //if this is a buy, I'm going to sell my hedge, nticks higher than the fill price - prx = prx + tick_size() * me->hedge_ticks; - else - prx = prx - tick_size() * me->hedge_ticks; - - build_and_send_hedge(Price(prx), Quantity(qty)); - } -} - -void CoverOrder::on_book_update(const bts::orderman::BookUpdateEvent& ) -{ - switch (this_state().status()) - { - case ORDER_STATUS_WORKING: - switch (child_state().status()) - { - case ORDER_STATUS_INACTIVE: - { - activate_child(Price(this_state().price()), Quantity(this_state().quantity())); - transition(ORDER_STATUS_WORKING); - report_state(); - } - break; - case ORDER_STATUS_WORKING: - { - } - break; - - case ORDER_STATUS_PENDING_WORKING: - break; - - // child cannot be in any of these states if we are in the working state - case ORDER_STATUS_DISCONNECTED: - case ORDER_STATUS_ERROR: - case ORDER_STATUS_REJECTED_BY_SPARK: - case ORDER_STATUS_COMPLETED: - case ORDER_STATUS_CANCELED: - case OrderStatus_INT_MIN_SENTINEL_DO_NOT_USE_: - case OrderStatus_INT_MAX_SENTINEL_DO_NOT_USE_: - bts_assert(false); - break; - } - break; - - case ORDER_STATUS_COMPLETED: - case ORDER_STATUS_CANCELED: - case ORDER_STATUS_ERROR: - break; - - case ORDER_STATUS_INACTIVE: - case ORDER_STATUS_REJECTED_BY_SPARK: - case ORDER_STATUS_PENDING_WORKING: - case ORDER_STATUS_DISCONNECTED: - case OrderStatus_INT_MIN_SENTINEL_DO_NOT_USE_: - case OrderStatus_INT_MAX_SENTINEL_DO_NOT_USE_: - bts_assert(false); - break; - } -} - -} -} - diff --git a/src/lib/orderman/orders/book_algos/CoverOrder.h b/src/lib/orderman/orders/book_algos/CoverOrder.h deleted file mode 100644 index 9bf81494e..000000000 --- a/src/lib/orderman/orders/book_algos/CoverOrder.h +++ /dev/null @@ -1,33 +0,0 @@ -#pragma once - -#include "lib/orderman/orders/book_algos/BookAlgo.h" - -namespace bts { -namespace orderman { - -class OrderStateUpdateEvent; -class BookUpdateEvent; - -//CoverOrder initializes the child order as normal -//Fills trigger hedge orders to the opposite side of the market, n ticks away. - -class CoverOrder : public BookAlgo -{ -public: - CoverOrder(); - virtual ~CoverOrder(); - -protected: - void setup_child(const api::orderman::OrderDefinition&, const PreActivationOrderServices&, - api::orderman::OrderState&, api::orderman::OrderDefinition*) override; - bool setup_hedge(const api::orderman::OrderDefinition& parent, const PreActivationOrderServices&, - api::orderman::OrderDefinition*) override; - void process_child_state_change(const api::orderman::OrderState&, const OrderStateUpdateEvent&) override; - void on_book_update(const bts::orderman::BookUpdateEvent&) override; - -private: - struct PImpl; - std::unique_ptr me; -}; - -}} diff --git a/src/lib/orderman/orders/book_algos/JoinOrder.cpp b/src/lib/orderman/orders/book_algos/JoinOrder.cpp deleted file mode 100644 index 1bf352523..000000000 --- a/src/lib/orderman/orders/book_algos/JoinOrder.cpp +++ /dev/null @@ -1,116 +0,0 @@ -#include "JoinOrder.h" - -#include "lib/orderman/actors/order_manager/OrderBuilder.h" -#include "lib/orderman/orders/spreader_orders/spreader/SpreaderUtils.h" -#include "lib/utils/PBUtils.h" -#include - -namespace bts { -namespace orderman { - -using namespace api::orderman; - -struct JoinOrder::PImpl { - PImpl() {} - - spark::QuantityMeasure join_threshold; - - md::PriceSize opposite_at_inception; - bool did_join; -}; - -JoinOrder::JoinOrder() : me(new PImpl()) {} - -JoinOrder::~JoinOrder() {} - -void JoinOrder::setup_child(const api::orderman::OrderDefinition &this_def, - const PreActivationOrderServices &, - api::orderman::OrderState &initial_state, - api::orderman::OrderDefinition *out_child) { - initial_state.mutable_join(); - auto const &join_def = this_def.custom_def().join(); - *out_child->mutable_custom_def() = join_def.child(); - - me->join_threshold = join_def.join_threshold(); - me->did_join = false; -} - -void JoinOrder::on_book_update(const bts::orderman::BookUpdateEvent &book) { - switch (this_state().status()) { - case ORDER_STATUS_WORKING: - switch (child_state().status()) { - case ORDER_STATUS_INACTIVE: { - if (definition().side() == api::SIDE_BUY) { - me->opposite_at_inception = book.book.side(api::Side::SIDE_SELL)[0]; - activate_child(Price(this_state().price()), - Quantity(this_state().quantity())); - transition(ORDER_STATUS_WORKING); - } else { - me->opposite_at_inception = book.book.side(api::Side::SIDE_BUY)[0]; - activate_child(Price(this_state().price()), - Quantity(this_state().quantity())); - transition(ORDER_STATUS_WORKING); - } - report_state(); - } break; - case ORDER_STATUS_WORKING: { - Quantity thresh = SpreaderUtils::_quantity_threshold( - me->join_threshold, Quantity(this_state().quantity())); - if (definition().side() == api::SIDE_BUY) { - const auto &same = book.book.side(api::Side::SIDE_BUY)[0]; - if (me->opposite_at_inception.price() > same.price()) { - } - // we join exactly once, but we can't detach because we have to hang - // around and look for hedges - else if (!me->did_join && same.size() >= thresh.value()) { - me->did_join = true; - update_child(Price(same.price()), - Quantity(this_state().quantity())); - report_state(); - } - } else { - const auto &same = book.book.side(api::Side::SIDE_SELL)[0]; - if (me->opposite_at_inception.price() < same.price()) { - } else if (!me->did_join && same.size() >= thresh.value()) { - me->did_join = true; - update_child(Price(same.price()), - Quantity(this_state().quantity())); - report_state(); - } - } - } break; - - case ORDER_STATUS_PENDING_WORKING: - break; - - // child cannot be in any of these states if we are in the working state - case ORDER_STATUS_DISCONNECTED: - case ORDER_STATUS_ERROR: - case ORDER_STATUS_REJECTED_BY_SPARK: - case ORDER_STATUS_COMPLETED: - case ORDER_STATUS_CANCELED: - case OrderStatus_INT_MIN_SENTINEL_DO_NOT_USE_: - case OrderStatus_INT_MAX_SENTINEL_DO_NOT_USE_: - bts_assert(false); - break; - } - break; - - case ORDER_STATUS_COMPLETED: - case ORDER_STATUS_CANCELED: - case ORDER_STATUS_ERROR: - break; - - case ORDER_STATUS_INACTIVE: - case ORDER_STATUS_REJECTED_BY_SPARK: - case ORDER_STATUS_PENDING_WORKING: - case ORDER_STATUS_DISCONNECTED: - case OrderStatus_INT_MIN_SENTINEL_DO_NOT_USE_: - case OrderStatus_INT_MAX_SENTINEL_DO_NOT_USE_: - bts_assert(false); - break; - } -} - -} // namespace orderman -} // namespace bts diff --git a/src/lib/orderman/orders/book_algos/JoinOrder.h b/src/lib/orderman/orders/book_algos/JoinOrder.h deleted file mode 100644 index ce97278bd..000000000 --- a/src/lib/orderman/orders/book_algos/JoinOrder.h +++ /dev/null @@ -1,31 +0,0 @@ -#pragma once - -#include "lib/orderman/orders/book_algos/BookAlgo.h" - -namespace bts { -namespace orderman { - -class OrderStateUpdateEvent; -class BookUpdateEvent; - -//JoinOrder starts working N ticks away from the market (usually) and then watches for -//the opposite inside to become same side inside market; if there is then enough size on that market, it will join. -//Fills optionally trigger hedge orders to the opposite side of the market, n ticks away. - -class JoinOrder : public BookAlgo -{ -public: - JoinOrder(); - virtual ~JoinOrder(); - -protected: - void setup_child(const api::orderman::OrderDefinition&, const PreActivationOrderServices&, - api::orderman::OrderState&, api::orderman::OrderDefinition*) override; - void on_book_update(const bts::orderman::BookUpdateEvent&) override; - -private: - struct PImpl; - std::unique_ptr me; -}; - -}} diff --git a/src/lib/orderman/orders/book_algos/LeanOrder.cpp b/src/lib/orderman/orders/book_algos/LeanOrder.cpp deleted file mode 100644 index f538a8b2e..000000000 --- a/src/lib/orderman/orders/book_algos/LeanOrder.cpp +++ /dev/null @@ -1,196 +0,0 @@ -#include "LeanOrder.h" - -#include "lib/orderman/actors/order_manager/OrderBuilder.h" -#include "lib/orderman/orders/spreader_orders/spreader/SpreaderUtils.h" -#include "lib/utils/PBUtils.h" -#include - -namespace bts { -namespace orderman { - -using namespace api::orderman; - -struct LeanOrder::PImpl { - PImpl() - : cross_threshold(), max_chase_ticks(0), - trade_toward_behavior(LeanOrderDefinition_OnToward_NO_CHANGE), - opposite_at_inception(), num_chases(0) {} - - spark::QuantityMeasure cross_threshold; - uint32_t max_chase_ticks; - LeanOrderDefinition_OnToward trade_toward_behavior; - - md::PriceSize opposite_at_inception; - uint32_t num_chases; -}; - -LeanOrder::LeanOrder() : me(new PImpl()) {} - -LeanOrder::~LeanOrder() {} - -void LeanOrder::setup_child(const api::orderman::OrderDefinition &this_def, - const PreActivationOrderServices &, - api::orderman::OrderState &initial_state, - api::orderman::OrderDefinition *out_child) { - initial_state.mutable_lean(); - auto const &lean_def = this_def.custom_def().lean(); - *out_child->mutable_custom_def() = lean_def.child(); - - me->cross_threshold = lean_def.cross_threshold(); - me->max_chase_ticks = lean_def.max_chase_ticks(); - me->trade_toward_behavior = lean_def.trade_toward_behavior(); -} - -void LeanOrder::payup(const md::PriceSize &, - const bts::orderman::BookUpdateEvent &book, - uint32_t cross_ticks /*= 0*/) { - double new_price = - me->opposite_at_inception.price() + tick_size() * cross_ticks; - double limit = - me->opposite_at_inception.price() + tick_size() * me->max_chase_ticks; - if (new_price <= limit) - update_child(Price(new_price), Quantity(this_state().quantity())); - else { - update_child(Price(limit), Quantity(this_state().quantity())); - detach(); - return; - } - - const bts::orderman::BookSide &sellbook = - book.book.side(api::Side::SIDE_SELL); - for (const auto &i : sellbook) { - me->opposite_at_inception = i; - if (me->opposite_at_inception.price() > new_price) - break; - } - if (me->opposite_at_inception.price() <= new_price) - detach(); - me->num_chases += cross_ticks + 1; - if (me->num_chases >= me->max_chase_ticks) - detach(); - report_state(); -} - -void LeanOrder::paydown(const md::PriceSize &, - const bts::orderman::BookUpdateEvent &book, - uint32_t cross_ticks /*= 0*/) { - double new_price = - me->opposite_at_inception.price() - tick_size() * cross_ticks; - double limit = - me->opposite_at_inception.price() - tick_size() * me->max_chase_ticks; - if (new_price >= limit) - update_child(Price(new_price), Quantity(this_state().quantity())); - else { - update_child(Price(limit), Quantity(this_state().quantity())); - detach(); - return; - } - - const bts::orderman::BookSide &buybook = book.book.side(api::Side::SIDE_BUY); - for (const auto &i : buybook) { - me->opposite_at_inception = i; - if (me->opposite_at_inception.price() < new_price) - break; - } - if (me->opposite_at_inception.price() >= new_price) - detach(); - me->num_chases += cross_ticks + 1; - if (me->num_chases >= me->max_chase_ticks) - detach(); - report_state(); -} - -void LeanOrder::choose_trade_toward_behavior(const md::PriceSize &opposite) { - switch (me->trade_toward_behavior) { - case LeanOrderDefinition_OnToward_CANCEL: { - cancel_child(); - transition(ORDER_STATUS_CANCELED); - report_state(); - } break; - case LeanOrderDefinition_OnToward_DETACH: { - detach(); - } break; - case LeanOrderDefinition_OnToward_REPRICE: { - me->opposite_at_inception = opposite; - } break; - case LeanOrderDefinition_OnToward_NO_CHANGE: - default: - break; - } -} - -void LeanOrder::on_book_update(const bts::orderman::BookUpdateEvent &book) { - switch (this_state().status()) { - case ORDER_STATUS_WORKING: - switch (child_state().status()) { - case ORDER_STATUS_INACTIVE: { - if (definition().side() == api::SIDE_BUY) - me->opposite_at_inception = book.book.side(api::Side::SIDE_SELL)[0]; - else - me->opposite_at_inception = book.book.side(api::Side::SIDE_BUY)[0]; - - activate_child(Price(this_state().price()), - Quantity(this_state().quantity())); - transition(ORDER_STATUS_WORKING); - report_state(); - } break; - case ORDER_STATUS_WORKING: { - Quantity thresh = SpreaderUtils::_quantity_threshold( - me->cross_threshold, Quantity(this_state().quantity())); - if (definition().side() == api::SIDE_BUY) { - const auto &opposite = book.book.side(api::Side::SIDE_SELL)[0]; - if (opposite.price() < me->opposite_at_inception.price()) - choose_trade_toward_behavior(opposite); - else if (opposite.price() > me->opposite_at_inception.price()) - payup(opposite, book); // you missed, payup/join - else { - if (opposite.size() <= thresh.value()) - payup(opposite, book); - } - } else { - const auto &opposite = book.book.side(api::Side::SIDE_BUY)[0]; - if (opposite.price() > me->opposite_at_inception.price()) - choose_trade_toward_behavior(opposite); - else if (opposite.price() < me->opposite_at_inception.price()) - paydown(opposite, book); - else { - if (opposite.size() <= thresh.value()) - paydown(opposite, book); - } - } - } break; - - case ORDER_STATUS_PENDING_WORKING: - break; - - // child cannot be in any of these states if we are in the working state - case ORDER_STATUS_DISCONNECTED: - case ORDER_STATUS_ERROR: - case ORDER_STATUS_REJECTED_BY_SPARK: - case ORDER_STATUS_COMPLETED: - case ORDER_STATUS_CANCELED: - case OrderStatus_INT_MIN_SENTINEL_DO_NOT_USE_: - case OrderStatus_INT_MAX_SENTINEL_DO_NOT_USE_: - bts_assert(false); - break; - } - break; - - case ORDER_STATUS_COMPLETED: - case ORDER_STATUS_CANCELED: - case ORDER_STATUS_ERROR: - break; - - case ORDER_STATUS_INACTIVE: - case ORDER_STATUS_REJECTED_BY_SPARK: - case ORDER_STATUS_PENDING_WORKING: - case ORDER_STATUS_DISCONNECTED: - case OrderStatus_INT_MIN_SENTINEL_DO_NOT_USE_: - case OrderStatus_INT_MAX_SENTINEL_DO_NOT_USE_: - bts_assert(false); - break; - } -} - -} // namespace orderman -} // namespace bts diff --git a/src/lib/orderman/orders/book_algos/LeanOrder.h b/src/lib/orderman/orders/book_algos/LeanOrder.h deleted file mode 100644 index bf9ff062c..000000000 --- a/src/lib/orderman/orders/book_algos/LeanOrder.h +++ /dev/null @@ -1,36 +0,0 @@ -#pragma once - -#include "lib/orderman/orders/book_algos/BookAlgo.h" - -namespace bts { -namespace orderman { - -class OrderStateUpdateEvent; -class BookUpdateEvent; - -//LeanOrder watches for the opposite inside to trade below a certain size. -//If size goes below a threshold or the market moves away, LeanOrder Pays up once. -//The process repeats until the algo has paid up a max of N ticks from the original opposite inside order. -//If the market moves toward, the algo starts watching the new inside market and keeps going - -class LeanOrder : public BookAlgo -{ -public: - LeanOrder(); - virtual ~LeanOrder(); - -protected: - void setup_child(const api::orderman::OrderDefinition&, const PreActivationOrderServices&, - api::orderman::OrderState&, api::orderman::OrderDefinition*) override; - void on_book_update(const bts::orderman::BookUpdateEvent&) override; -private: - void payup(const md::PriceSize& opposite, const bts::orderman::BookUpdateEvent&, uint32_t cross_ticks = 0) override; - void paydown(const md::PriceSize& opposite, const bts::orderman::BookUpdateEvent&, uint32_t cross_ticks = 0) override; - void choose_trade_toward_behavior(const md::PriceSize& opposite); - -private: - struct PImpl; - std::unique_ptr me; -}; - -}} diff --git a/src/lib/orderman/orders/book_algos/OCOOrder.cpp b/src/lib/orderman/orders/book_algos/OCOOrder.cpp index b77ff61d8..fa8836fa7 100644 --- a/src/lib/orderman/orders/book_algos/OCOOrder.cpp +++ b/src/lib/orderman/orders/book_algos/OCOOrder.cpp @@ -194,7 +194,7 @@ void OCOOrder::on_book_update(const bts::orderman::BookUpdateEvent& ) } } -void OCOOrder::on_cancel(trace::CorID const&) +OrderOpResult OCOOrder::on_cancel() { LOG(OrderMan, Info, "Canceling OCOOrder Order {}", key().value()); @@ -249,6 +249,7 @@ void OCOOrder::on_cancel(trace::CorID const&) break; } report_state(); + return OrderOpResult{}; } } diff --git a/src/lib/orderman/orders/book_algos/OCOOrder.h b/src/lib/orderman/orders/book_algos/OCOOrder.h index 5fd0e8789..f8c5f7e58 100644 --- a/src/lib/orderman/orders/book_algos/OCOOrder.h +++ b/src/lib/orderman/orders/book_algos/OCOOrder.h @@ -18,7 +18,7 @@ public: OCOOrder(); virtual ~OCOOrder(); - void on_cancel(trace::CorID const&) override ; + OrderOpResult on_cancel() override ; protected: void setup_child(const api::orderman::OrderDefinition&, const PreActivationOrderServices&, api::orderman::OrderState&, api::orderman::OrderDefinition*) override; diff --git a/src/lib/orderman/orders/book_algos/TopOrder.cpp b/src/lib/orderman/orders/book_algos/TopOrder.cpp deleted file mode 100644 index 8fded05b5..000000000 --- a/src/lib/orderman/orders/book_algos/TopOrder.cpp +++ /dev/null @@ -1,129 +0,0 @@ -#include "TopOrder.h" - -#include "lib/domain_model/Security.h" -#include "lib/orderman/actors/order_manager/OrderBuilder.h" -#include "lib/orderman/orders/spreader_orders/spreader/SpreaderUtils.h" -#include "lib/utils/PBUtils.h" -#include - -namespace bts { -namespace orderman { - -using namespace api::orderman; - -struct TopOrder::PImpl { - PImpl() {} - - uint32_t watch_level_tick_offset; - spark::QuantityMeasure top_threshold; -}; - -TopOrder::TopOrder() : me(new PImpl()) {} - -TopOrder::~TopOrder() {} - -void TopOrder::setup_child(const api::orderman::OrderDefinition &this_def, - const PreActivationOrderServices &, - api::orderman::OrderState &initial_state, - api::orderman::OrderDefinition *out_child) { - initial_state.mutable_top(); - auto const &top_def = this_def.custom_def().top(); - *out_child->mutable_custom_def() = top_def.child(); - - me->watch_level_tick_offset = top_def.watch_level_tick_offset(); - me->top_threshold = top_def.top_threshold(); -} - -void TopOrder::on_book_update(const bts::orderman::BookUpdateEvent &book) { - switch (this_state().status()) { - case ORDER_STATUS_WORKING: - switch (child_state().status()) { - case ORDER_STATUS_INACTIVE: { - Quantity thresh = SpreaderUtils::_quantity_threshold( - me->top_threshold, Quantity(this_state().quantity())); - if (definition().side() == api::SIDE_BUY) { - const auto &same = book.book.side(api::Side::SIDE_BUY)[0]; - if (securities::test_price_equality(this_state().price(), - same.price(), tick_size())) { - if (same.size() <= thresh.value()) { - transition(ORDER_STATUS_CANCELED); - report_state(); - return; - } - } - } else { - const auto &same = book.book.side(api::Side::SIDE_SELL)[0]; - if (securities::test_price_equality(this_state().price(), - same.price(), tick_size())) { - if (same.size() <= thresh.value()) { - transition(ORDER_STATUS_CANCELED); - report_state(); - return; - } - } - } - activate_child(Price(this_state().price()), - Quantity(this_state().quantity())); - transition(ORDER_STATUS_WORKING); - report_state(); - } break; - case ORDER_STATUS_WORKING: { - Quantity thresh = SpreaderUtils::_quantity_threshold( - me->top_threshold, Quantity(this_state().quantity())); - if (definition().side() == api::SIDE_BUY) { - const auto &same = book.book.side(api::Side::SIDE_BUY)[0]; - if (securities::test_price_equality(this_state().price(), - same.price(), tick_size())) { - if (same.size() <= thresh.value()) { - cancel_child(); - transition(ORDER_STATUS_CANCELED); - report_state(); - } - } - } else { - const auto &same = book.book.side(api::Side::SIDE_SELL)[0]; - if (securities::test_price_equality(this_state().price(), - same.price(), tick_size())) { - if (same.size() <= thresh.value()) { - cancel_child(); - transition(ORDER_STATUS_CANCELED); - report_state(); - } - } - } - } break; - - case ORDER_STATUS_PENDING_WORKING: - break; - - // child cannot be in any of these states if we are in the working state - case ORDER_STATUS_DISCONNECTED: - case ORDER_STATUS_ERROR: - case ORDER_STATUS_REJECTED_BY_SPARK: - case ORDER_STATUS_COMPLETED: - case ORDER_STATUS_CANCELED: - case OrderStatus_INT_MIN_SENTINEL_DO_NOT_USE_: - case OrderStatus_INT_MAX_SENTINEL_DO_NOT_USE_: - bts_assert(false); - break; - } - break; - - case ORDER_STATUS_COMPLETED: - case ORDER_STATUS_CANCELED: - case ORDER_STATUS_ERROR: - break; - - case ORDER_STATUS_INACTIVE: - case ORDER_STATUS_REJECTED_BY_SPARK: - case ORDER_STATUS_PENDING_WORKING: - case ORDER_STATUS_DISCONNECTED: - case OrderStatus_INT_MIN_SENTINEL_DO_NOT_USE_: - case OrderStatus_INT_MAX_SENTINEL_DO_NOT_USE_: - bts_assert(false); - break; - } -} - -} // namespace orderman -} // namespace bts diff --git a/src/lib/orderman/orders/book_algos/TopOrder.h b/src/lib/orderman/orders/book_algos/TopOrder.h deleted file mode 100644 index 4736def75..000000000 --- a/src/lib/orderman/orders/book_algos/TopOrder.h +++ /dev/null @@ -1,30 +0,0 @@ -#pragma once - -#include "lib/orderman/orders/book_algos/BookAlgo.h" - -namespace bts { -namespace orderman { - -class OrderStateUpdateEvent; -class BookUpdateEvent; - -//If TopOrder becomes the top of book, it cancels if there is less than some threshold of size joined with it. -//Fills optionally trigger hedge orders to the opposite side of the market, n ticks away. - -class TopOrder : public BookAlgo -{ -public: - TopOrder(); - virtual ~TopOrder(); - -protected: - void setup_child(const api::orderman::OrderDefinition& this_def, const PreActivationOrderServices&, - api::orderman::OrderState&, api::orderman::OrderDefinition*) override; - void on_book_update(const bts::orderman::BookUpdateEvent&) override; - -private: - struct PImpl; - std::unique_ptr me; -}; - -}} diff --git a/src/lib/orderman/orders/queue_holder/IQueueHolderOrderStateWorker.h b/src/lib/orderman/orders/queue_holder/IQueueHolderOrderStateWorker.h new file mode 100644 index 000000000..1c3be64f9 --- /dev/null +++ b/src/lib/orderman/orders/queue_holder/IQueueHolderOrderStateWorker.h @@ -0,0 +1,45 @@ +#pragma once +#include "lib/utils/bts_chrono.h" +#include "lib/orderman/orderman_utils/orderman_common.h" +#include "lib/orderman/orders/queue_holder/QueueHolderOrderState.h" + +namespace bts { +namespace trace {struct CorID;} +namespace api {namespace orderman {class OrderDefinition;class OrderRecord;}} +namespace orderman {class PreActivationOrderServices; class OrderServices;} +namespace orderman {class OrderStateUpdateEvent;} +namespace orderman { +class SpreaderOrder; +class Book; + +// All the QueueHolderOrder state machine workers +// implement this +class IQueueHolderOrderStateWorker{ +public: + virtual QueueHolderOrderState state() const = 0; + // 0. when the state machine transits to a new state + virtual void on_transition() = 0; + // 1. called once before the other calls. state should be + // constructed here + virtual void on_init_new(const api::orderman::OrderDefinition&, + const PreActivationOrderServices&) = 0; + // 2. when constructed on recovery (with partial state) + virtual void on_init_recovered(const bts::api::orderman::OrderRecord&, + const PreActivationOrderServices&) = 0; + // 3. this is the end of the construction cycle. should happen + // after on_init_new and before all other calls. market data subs + // and quoter order creation happens here + virtual void on_activate(Price, Quantity, OrderServices&) = 0; + // 4. new a price, qty change + virtual void on_update(Price, Quantity) = 0; + // 5. called when the user cancels an order + virtual void on_cancel() = 0; + // 6. order callback + virtual void on_child_order_update(const OrderStateUpdateEvent&) = 0; + // 7. on market data update (support late joiners) + virtual void on_book(const Book&, + const trace::CorID&) = 0; + // 8. time event called by the infrastructure + virtual void on_time(const TimeStamp&) = 0; +}; +}} diff --git a/src/lib/orderman/orders/queue_holder/QHOOrderManager.h b/src/lib/orderman/orders/queue_holder/QHOOrderManager.h new file mode 100644 index 000000000..88f6319b0 --- /dev/null +++ b/src/lib/orderman/orders/queue_holder/QHOOrderManager.h @@ -0,0 +1,319 @@ +#pragma once + +#include "lib/os/os.h" +#include "lib/orderman/orders/spreader_orders/spreader/SpreaderChildOrderState.h" +#include "lib/domain_model/Security.h" + +namespace bts { +namespace orderman { + +// submit, modifies and cancels all orders +// that constitute the QHO. +// i. places, modifies and cancels orders +// ii. helper functons to get the accumulated +// state of the orders +// all the order interactions are done explicitely +// through function calls +class QHOOrderManager{ +private: + bool _inited; + bool _orders_placed_once; + OrderBuilder* _order_builder; + api::Side _side; + double _tick_size; + uint16_t _n_eff_orders; + // the order of this does is not asc/desc wrt + // price (modify of price will make it unordered) + std::vector _orders; + Price _target_price; + Quantity _target_qty; +public: + QHOOrderManager() + : + _inited(false), + _orders_placed_once(false), + _order_builder(nullptr), + _side(api::Side::SIDE_BUY), + _tick_size(os::nan()), + _n_eff_orders(1), + _orders(), + _target_price(os::nan()), + _target_qty(0){ + } + // public interface ////////////////////////////// + ////////////////////////////////////////////////// + + // We could have done away with init and + // moved it in the cons. The problem is that + // the QueueHolderOrder does not have the data + // at its construction time to construct + // QHOOrderManager. (It could alternatively + // have used a pointer to QueueHolderOrder + // but for contigous memory allocations it + // did not) + void init(OrderBuilder& order_builder, + SecurityKey key, + api::Side side, + double tick_size, + uint16_t n_orders, + Price price, + Quantity qty){ + _inited=true; + _order_builder=&order_builder; + _side=side; + _tick_size=tick_size; + // 1 trailing order means 2 total orders and so forth + _n_eff_orders=n_orders+1; + _orders.reserve(_n_eff_orders); + for(uint16_t i=0;i<_n_eff_orders;i++) + _orders.emplace_back(key,true,true); + _target_price=price; + _target_qty=qty; + } + // this can be called only once + void place_order(){ + bts_assert(_inited); + bts_assert(!_orders_placed_once); + _orders_placed_once=true; + Quantity target_qty=_remaining(); + bts_assert(target_qty.value()>0); + double price_i=_target_price.value(), + move_inc=_top_down_tick_inc(_tick_size,_side); + for(SpreaderChildOrderState& o : _orders){ + bts_assert(o.out_quantity().value()==0); + ChildOrder child_order=_order_builder->build(); + o.re_init(child_order); + o.place_order(Price(price_i), + target_qty, + bts::Timer::now()); + price_i+=move_inc; + } + } + // sends orders (for the remaining qty) + // for all terminal orders + void reenter_filled_orders(){ + bts_assert(_inited); + bts_assert(_orders_placed_once); + Quantity target_qty=_remaining(); + bts_assert(target_qty.value()>0); + for(SpreaderChildOrderState& o : _orders){ + if(o.terminal_status()){ + Price price=o.out_price();//re-init resets the price + ChildOrder child_order=_order_builder->build(); + o.re_init(child_order); + o.place_order(price, + target_qty, + bts::Timer::now()); + } + else + _prune_qty(o); + } + } + // can only modifiy if all acked and working + void modify_order(Price price, Quantity qty){ + bts_assert(_inited); + bts_assert(_orders_placed_once); + Price prev_price=_target_price; + Quantity prev_qty=_target_qty; + // all acked and working + bts_assert(all_orders_acked() && !has_terminal_order()); + _target_price=price; + _target_qty=qty; + bts_assert(_remaining().value()>0); + _modify_order(prev_price,prev_qty); + } + // cancels all the orders (and is smart + // enough to about working orders only) + void cancel(){ + bts_assert(_inited); + bts_assert(_orders_placed_once); + for (auto& o : _orders){ + // is_cancelled() is checked so as not to keep + // sending cancel requests + if(!o.is_cancelled()&&o.acknowledged()&&!o.terminal_status()) + o.cancel_order(); + } + } + // finds the orders and subsumes the update. + // returns false if it cant locate the order key + bool on_order_update(const OrderStateUpdateEvent& ev){ + bts_assert(_inited); + bts_assert(_orders_placed_once); + for (auto& o : _orders) + if(o.order_key()==ev.key){ + o.on_order_update(ev); + return true; + } + return false; + } + // decreases qty in case of fills. + // can only modifiy if all acked and working + void prune_quantities(){ + bts_assert(_inited); + bts_assert(_orders_placed_once); + bts_assert(all_orders_acked() && !has_terminal_order()); + for (auto& o : _orders) + _prune_qty(o); + } + /////////////////////////////////////////////// + inline Quantity filled_qty() const{ + uint32_t rv=0; + for (const auto& o : _orders) + rv+=o.total_fills().value(); + return Quantity(rv); + } + inline void filled_price(double& filled_price, uint32_t& filled_qty) const{ + double tot_price=0.0; + uint32_t tot_qty=0; + for (const auto& o : _orders){ + Price so_price; Quantity so_qty; + o.total_fills(so_qty,so_price); + if(so_qty.value()>0){ + tot_qty+=so_qty.value(); + tot_price+=so_price.value()*so_qty.value(); + } + } + if(tot_qty>0) + tot_price/=tot_qty; + filled_price=tot_price; + filled_qty=tot_qty; + } + inline bool last_update_has_fills() const{ + for (const auto& o : _orders) + if(o.last_update_filled_quantity().value()>0) + return true; + return false; + } + inline bool has_cancelled_order() const{ + for (const auto& o : _orders) + if(o.cancelled()) + return true; + return false; + } + inline bool has_completed_order() const{ + for (const auto& o : _orders) + if(o.completed()) + return true; + return false; + } + inline bool has_errored_order() const{ + for (const auto& o : _orders) + if(o.errored()) + return true; + return false; + } + inline bool has_terminal_order() const{ + for (const auto& o : _orders) + if(o.terminal_status()) + return true; + return false; + } + inline bool all_orders_terminal() const{ + for (const auto& o : _orders) + if(!o.terminal_status()) + return false; + return true; + } + inline bool all_orders_acked() const{ + for (const auto& o : _orders) + if(!o.acknowledged()) + return false; + return true; + } +private: + void _modify_order(Price prev_price, Quantity){ + double move_inc=_top_down_tick_inc(_tick_size,_side); + int tick_diff=bts::securities::price_diff_to_ticks( + prev_price.value(), + _target_price.value(), + _tick_size); + Quantity remaining_target=_remaining(); + bool moving_up=tick_diff>0; + double price_i=_target_price.value(); + for(uint16_t i=0;i<_n_eff_orders;i++){ + SpreaderChildOrderState* order_i=_find_working_order_at_price(price_i); + if(order_i==nullptr){ + SpreaderChildOrderState& to_move= + moving_up?_lowest_price_order():_highest_price_order(); + uint32_t new_ord_qty=_adjusted_qty(to_move.current_fills().value(), + to_move.out_quantity().value(), + remaining_target.value(), + true); // qty inc since its + // changing price levels + to_move.modify_order(Price(price_i),Quantity(new_ord_qty)); + } + else + _prune_qty(*order_i); + price_i+=move_inc; + } + } + // decreases qty if the order at any level can overfill + // the total, ie for an order out_qty-filled > total_rem + // if rem=5, and this order is 3/9 this will make it 3/8 + void _prune_qty(SpreaderChildOrderState& o){ + uint32_t new_ord_qty=_adjusted_qty(o.current_fills().value(), + o.out_quantity().value(), + _remaining().value(), + false); // dont inc the qty + bts_assert(new_ord_qty>0); + o.modify_order(o.out_price(),Quantity(new_ord_qty)); + } + Quantity _remaining() const{ + if(filled_qty().value()>=_target_qty.value()) + return Quantity(0); + else + return Quantity(_target_qty.value()-filled_qty().value()); + } + // finds the order who's out_price matches + // the arg + SpreaderChildOrderState* _find_working_order_at_price(double price){ + for(auto& o : _orders) + if(bts::securities::test_price_equality( + o.out_price().value(), + price, + _tick_size) && + !o.terminal_status()) + return &o; + return nullptr; + } + SpreaderChildOrderState& _highest_price_order(){ + SpreaderChildOrderState* rv=&_orders[0]; + for(auto& o : _orders) + if(o.out_price().value()>rv->out_price().value()) + rv=&o; + return *rv; + } + SpreaderChildOrderState& _lowest_price_order(){ + SpreaderChildOrderState* rv=&_orders[0]; + for(auto& o : _orders) + if(o.out_price().value()out_price().value()) + rv=&o; + return *rv; + } + // given an order's filled and order qty, and the + // target left on the total qho, finds the adjusted + // qty of the order + static uint32_t _adjusted_qty (uint32_t filled_qty, + uint32_t order_qty, + uint32_t rem_target, + bool allow_inc){ + bts_assert(filled_qty<=order_qty); + uint32_t rem_fill=order_qty-filled_qty; + if(rem_fill>rem_target){ + uint32_t dec=rem_fill-rem_target; + return order_qty-dec; + } + else if(rem_fill +#include +#include "lib/os/os.h" + +namespace bts { +namespace orderman { + +QueueHolderOrder::QueueHolderOrder() +: +_is_succ_inited(false), +_is_recovered(false), +_termination_reason(TerminationReason::NONE), +_order_def(), +_tick_size(bts::os::nan()), +_order_builder(), +_order_manager(), +_services(nullptr), +_reported_state(), +_book(), +_state_worker(nullptr), +_start_state_worker(this), +_waiting_for_ack_state_worker(this), +_working_state_worker(this), +_waiting_for_cancel_all_state_worker(this), +_end_state_worker(this){ + _switch_state(QueueHolderOrderState::START); +} +QueueHolderOrder::~QueueHolderOrder() {} +const api::orderman::OrderDefinition& QueueHolderOrder::definition() const { + return _order_def; +} +void QueueHolderOrder::on_init_new(const api::orderman::OrderDefinition& order_def, + const PreActivationOrderServices& pre_os) { + LOG(OrderMan, Info, "QueueHolderOrder::on_init_new key:{} state:{}", + key(), _state_int()); + _state_worker->on_init_new(order_def,pre_os); +} +void QueueHolderOrder::on_init_recovered( + const api::orderman::OrderRecord& rec, + const PreActivationOrderServices& pre_os) { + LOG(OrderMan, Info, "QueueHolderOrder::on_init_recovered key:{} state:{}", + key(), _state_int()); + _state_worker->on_init_recovered(rec,pre_os); +} +OrderOpResult QueueHolderOrder::on_activate(Price price, + Quantity qty, + OrderServices& services) { + LOG(OrderMan, Info, + "QueueHolderOrder::on_activate key:{} state:{} price:{} qty:{}", + key(), _state_int(), price, qty); + _state_worker->on_activate(price,qty,services); + _report_state(); + return OrderOpResult {}; +} +// order price, qty change +OrderOpResult QueueHolderOrder::on_update(Price price, + Quantity qty) { + _state_worker->on_update(price,qty); + _report_state(); + return OrderOpResult {}; +} +OrderOpResult QueueHolderOrder::on_cancel() { + _state_worker->on_cancel(); + _report_state(); + return OrderOpResult {}; +} +OrderOpResult QueueHolderOrder::on_detach() { + return OrderOpResult {}; +} +void QueueHolderOrder::_on_book_update(const BookUpdateEvent& b) { + _state_worker->on_book(b.book,b.trace); +} +void QueueHolderOrder::_on_child_order_update( + const OrderStateUpdateEvent& c) { + _state_worker->on_child_order_update(c); + _report_state(); +} +void QueueHolderOrder::_on_time(const bts::mercury::TimerEvent& te) { + _state_worker->on_time(te.ts); +} +void QueueHolderOrder::_switch_state(QueueHolderOrderState new_state) { + int s0=_state_int(); + switch (new_state){ + case QueueHolderOrderState::START: + bts_assert(_state_worker==nullptr); + _state_worker=&_start_state_worker; + break; + case QueueHolderOrderState::WAITING_FOR_FIRST_ACK: + bts_assert(_state_worker->state()==QueueHolderOrderState::START || + _state_worker->state()==QueueHolderOrderState::WORKING); + _state_worker=&_waiting_for_ack_state_worker; + break; + case QueueHolderOrderState::WORKING: + bts_assert(_state_worker->state()== + QueueHolderOrderState::WAITING_FOR_FIRST_ACK); + _state_worker=&_working_state_worker; + break; + case QueueHolderOrderState::WAITING_FOR_CANCEL_ALL: + bts_assert(_state_worker->state()== + QueueHolderOrderState::WAITING_FOR_FIRST_ACK || + _state_worker->state()== + QueueHolderOrderState::WORKING); + _state_worker=&_waiting_for_cancel_all_state_worker; + break; + case QueueHolderOrderState::END: + bts_assert(_state_worker->state()!=QueueHolderOrderState::END); + _state_worker=&_end_state_worker; + break; + } + _state_worker->on_transition(); + _report_state(); + LOG(OrderMan, Info, "QueueHolderOrder::_switch_state key:{} {}->{}", + key(), s0,_state_int()); +} +api::orderman::OrderStatus QueueHolderOrder::status(std::string& message) const{ + QueueHolderOrderState curr_state= + _state_worker==nullptr?QueueHolderOrderState::START:_state(); + switch (curr_state){ + case QueueHolderOrderState::START: + case QueueHolderOrderState::WAITING_FOR_FIRST_ACK: + case QueueHolderOrderState::WORKING: + case QueueHolderOrderState::WAITING_FOR_CANCEL_ALL: + return api::orderman::OrderStatus::ORDER_STATUS_WORKING; + case QueueHolderOrderState::END: + switch(_termination_reason){ + case TerminationReason::NONE:{ + // this will happen if the order is + // recovered or the init failed + bts_assert(!_is_succ_inited||_is_recovered); + if(!_is_succ_inited){ + message="Could not initialize order"; + return api::orderman::OrderStatus::ORDER_STATUS_REJECTED_BY_SPARK; + } + else{ + message="Recovered order"; + // we could have done better here by [reserving ] + return api::orderman::OrderStatus::ORDER_STATUS_COMPLETED; + } + } + case TerminationReason::EXTERNAL_CANCEL: + return api::orderman::OrderStatus::ORDER_STATUS_CANCELED; + case TerminationReason::FILLED: + return api::orderman::OrderStatus::ORDER_STATUS_COMPLETED; + case TerminationReason::UNEXPECTED_CHILD_CANCEL: + message="Child order cancelled"; + return api::orderman::OrderStatus::ORDER_STATUS_CANCELED; + case TerminationReason::CHILD_ERROR: + message="Child order error"; + return api::orderman::OrderStatus::ORDER_STATUS_CANCELED; + } + } + return api::orderman::OrderStatus::ORDER_STATUS_WORKING; + } +} // namespace orderman +} // namespace bts \ No newline at end of file diff --git a/src/lib/orderman/orders/queue_holder/QueueHolderOrder.h b/src/lib/orderman/orders/queue_holder/QueueHolderOrder.h new file mode 100644 index 000000000..1a36c9dc1 --- /dev/null +++ b/src/lib/orderman/orders/queue_holder/QueueHolderOrder.h @@ -0,0 +1,151 @@ +#pragma once + +#include +#include "lib/orderman/orders/Order.h" +#include "lib/api/services/OrderService.server.pb.h" +#include "lib/orderman/orders/queue_holder/IQueueHolderOrderStateWorker.h" +#include "lib/orderman/orders/queue_holder/state_workers/QHOStartStateWorker.h" +#include "lib/orderman/orders/queue_holder/state_workers/QHOWaitingForAckStateWorker.h" +#include "lib/orderman/orders/queue_holder/state_workers/QHOWorkingStateWorker.h" +#include "lib/orderman/orders/queue_holder/state_workers/QHOWaitingForCancelAllStateWorker.h" +#include "lib/orderman/orders/queue_holder/state_workers/QHOEndStateWorker.h" +#include "lib/orderman/orders/queue_holder/QHOOrderManager.h" +#include "lib/orderman/orders/OrderOpResult.h" + +namespace bts { +namespace api {namespace orderman {class OrderDefinition;}} +namespace mercury {class TimerEvent;} +namespace md {class PriceSize;} +namespace orderman { + +class OrderStateUpdateEvent; +class BookUpdateEvent; +class PreActivationOrderServices; + +class QueueHolderOrder : public Order +{ +friend QHOStartStateWorker; +friend QHOWaitingForAckStateWorker; +friend QHOWorkingStateWorker; +friend QHOWaitingForCancelAllStateWorker; +friend QHOEndStateWorker; +public: + QueueHolderOrder(); + QueueHolderOrder(const QueueHolderOrder&)=delete; + QueueHolderOrder(QueueHolderOrder&&)=delete; + QueueHolderOrder& operator=(const QueueHolderOrder&)=delete; + QueueHolderOrder& operator=(QueueHolderOrder&&)=delete; + virtual ~QueueHolderOrder(); + api::orderman::OrderDefinition const& definition() const; + void on_init_new(api::orderman::OrderDefinition const&, + const PreActivationOrderServices&) override; + void on_init_recovered(api::orderman::OrderRecord const&, + const PreActivationOrderServices &) override; + OrderOpResult on_activate(Price, Quantity, + OrderServices&) override; + OrderOpResult on_update(Price, Quantity) override; + OrderOpResult on_cancel() override; + OrderOpResult on_detach() override; +private: + enum class TerminationReason + { + // initial value at the time of the first cancel + NONE, + EXTERNAL_CANCEL, + // order got filled (since there are multiple + // orders we need to cancel the rest) + FILLED, + // one or more child orders got cancelled + UNEXPECTED_CHILD_CANCEL, + // child order errored out + CHILD_ERROR + }; +private: + // callbacks from book and child order udpates + void _on_book_update(const BookUpdateEvent&); + void _on_child_order_update(OrderStateUpdateEvent const&); + void _on_time (const bts::mercury::TimerEvent&); +private: + QueueHolderOrderState _state() const{ + return _state_worker->state(); + } + int _state_int() const{ + if (_state_worker==nullptr) + return -1; + return static_cast(_state_worker->state()); + } + bool _activated() const{ + return _services!=nullptr; + } + void _cancel_order(TerminationReason termination_reason){ + bts_assert(termination_reason!=TerminationReason::NONE); + bts_assert(_termination_reason==TerminationReason::NONE); + _termination_reason=termination_reason; + _switch_state(QueueHolderOrderState::WAITING_FOR_CANCEL_ALL); + } + api::orderman::OrderStatus status(std::string& message) const; + // sends orders for the first time + void _report_state(){ + if(_activated()){ + std::string err_msg; + _reported_state.set_status(status(err_msg)); + double filled_price; + uint32_t filled_qty; + _order_manager.filled_price(filled_price,filled_qty); + if(filled_qty>_reported_state.filled_quantity()){ + // this means there was a fill reported bw last report + // and this, hence last_price needs to be set + uint32_t last_trade_qty=filled_qty- + _reported_state.filled_quantity(); + double last_trade_price=filled_price*filled_qty- + _reported_state.avg_price()*_reported_state.filled_quantity(); + last_trade_price/=last_trade_qty; + _reported_state.set_last_price(last_trade_price); + } + _reported_state.set_avg_price(filled_price); + _reported_state.set_filled_quantity(filled_qty); + _reported_state.set_last_msg(err_msg); + _services->report_state(_reported_state); + } + } + void _set_state_price_qty(Price price, Quantity qty){ + _reported_state.set_price(price.value()); + _reported_state.set_quantity(qty.value()); + } + bool _filled() const{ + return _order_manager.filled_qty().value()>= + _reported_state.quantity(); + } + + void _switch_state(QueueHolderOrderState new_state); + + void _assert_false(const std::string& str) const{ + std::ostringstream oss; + oss << str << " key:" << key(); + bts_assert_msg(false, oss.str()); + } +private: + // if the init call succeeded which means + // i. order is properly built + // ii. security was successfully resolved + bool _is_succ_inited; + // tells if the order is a recovered order + // (as opposed to a new order) + bool _is_recovered; + TerminationReason _termination_reason; + api::orderman::OrderDefinition _order_def; + double _tick_size; + OrderBuilder _order_builder; + QHOOrderManager _order_manager; + OrderServices *_services; + api::orderman::OrderState _reported_state; + Book _book; + IQueueHolderOrderStateWorker* _state_worker; + QHOStartStateWorker _start_state_worker; + QHOWaitingForAckStateWorker _waiting_for_ack_state_worker; + QHOWorkingStateWorker _working_state_worker; + QHOWaitingForCancelAllStateWorker _waiting_for_cancel_all_state_worker; + QHOEndStateWorker _end_state_worker; +}; + +}} \ No newline at end of file diff --git a/src/lib/orderman/orders/queue_holder/QueueHolderOrderState.h b/src/lib/orderman/orders/queue_holder/QueueHolderOrderState.h new file mode 100644 index 000000000..c315b2cc4 --- /dev/null +++ b/src/lib/orderman/orders/queue_holder/QueueHolderOrderState.h @@ -0,0 +1,21 @@ +#pragma once + +namespace bts{ +namespace orderman{ +enum class QueueHolderOrderState{ + // remains here till on_activate is called + START=0, + // once the order is submitted it gets into + // this state until it gets an ack on all + // the sub orders + WAITING_FOR_FIRST_ACK=1, + // all orders are ack'ed, free to accept + // updates + WORKING=2, + // cancel has been sent, wait for all + // sub orders to be in final state + WAITING_FOR_CANCEL_ALL=3, + // final state, no going back + END=4 +}; +}} \ No newline at end of file diff --git a/src/lib/orderman/orders/queue_holder/state_workers/QHOEndStateWorker.cpp b/src/lib/orderman/orders/queue_holder/state_workers/QHOEndStateWorker.cpp new file mode 100644 index 000000000..6c376706a --- /dev/null +++ b/src/lib/orderman/orders/queue_holder/state_workers/QHOEndStateWorker.cpp @@ -0,0 +1,58 @@ +#include "lib/orderman/orders/queue_holder/state_workers/QHOEndStateWorker.h" +#include "lib/orderman/orders/queue_holder/QueueHolderOrder.h" +#include "lib/domain_model/Security.h" +#include "lib/logging/logging.h" +#include "lib/orderman/actors/order_manager/OrderBuilder.h" +#include "lib/orderman/events/BookUpdateEvent.h" +#include "lib/orderman/orders/spreader_orders/spreader/SpreaderUtils.h" +#include "lib/os/os.h" +#include "lib/utils/PBUtils.h" +#include +#include +#include "lib/os/os.h" + +namespace bts{ +namespace orderman{ + +QHOEndStateWorker::QHOEndStateWorker(QueueHolderOrder* parent) +: +_porder(parent) +{} + +void QHOEndStateWorker::on_transition (){ +} + +void QHOEndStateWorker::on_init_new( + const api::orderman::OrderDefinition&, + const PreActivationOrderServices&){ + _porder->_assert_false("QHOEndStateWorker::on_init_new"); +} +void QHOEndStateWorker::on_init_recovered( + const bts::api::orderman::OrderRecord&, + const PreActivationOrderServices&){ + _porder->_assert_false("QHOEndStateWorker::on_init_recovered"); +} +void QHOEndStateWorker::on_activate(Price, + Quantity, + OrderServices&){ + _porder->_assert_false("QHOEndStateWorker::on_activate"); +} +void QHOEndStateWorker::on_update(Price, + Quantity){ + LOG(OrderMan, Warn, "QHOEndStateWorker::on_update " + "key:{} rejected",_porder->key()); +} +void QHOEndStateWorker::on_cancel(){ + LOG(OrderMan, Warn, "QHOEndStateWorker::on_cancel " + "key:{} already in termminal state",_porder->key()); +} +void QHOEndStateWorker::on_child_order_update(const OrderStateUpdateEvent& ev){ + LOG(OrderMan, Error, "QHOEndStateWorker::on_child_order_update " + "key:{} order_key:{}",_porder->key(),ev.key); +} +void QHOEndStateWorker::on_book(const Book&, + const trace::CorID&){ +} +void QHOEndStateWorker::on_time(const TimeStamp&){ +} +}} \ No newline at end of file diff --git a/src/lib/orderman/orders/queue_holder/state_workers/QHOEndStateWorker.h b/src/lib/orderman/orders/queue_holder/state_workers/QHOEndStateWorker.h new file mode 100644 index 000000000..a12a29af2 --- /dev/null +++ b/src/lib/orderman/orders/queue_holder/state_workers/QHOEndStateWorker.h @@ -0,0 +1,34 @@ +#pragma once + +#include "lib/orderman/orders/queue_holder/IQueueHolderOrderStateWorker.h" + +namespace bts{ +namespace orderman{ + +class QueueHolderOrder; +// this is the starting node. since the hedger +// can be reused, the end state can lead back to this +class QHOEndStateWorker : public IQueueHolderOrderStateWorker +{ +private: + QueueHolderOrder* const _porder; +public: + QHOEndStateWorker(QueueHolderOrder* parent); + QueueHolderOrderState state () const override { + return QueueHolderOrderState::END; + } + void on_transition () override; + void on_init_new(const api::orderman::OrderDefinition&, + const PreActivationOrderServices&) override; + void on_init_recovered(const bts::api::orderman::OrderRecord&, + const PreActivationOrderServices&) override; + void on_activate(Price, Quantity, OrderServices&) override; + void on_update(Price, Quantity) override; + void on_cancel() override; + void on_child_order_update(const OrderStateUpdateEvent&) override; + void on_book(const Book&, + const trace::CorID&) override; + void on_time(const TimeStamp&) override; +}; + +}} \ No newline at end of file diff --git a/src/lib/orderman/orders/queue_holder/state_workers/QHOStartStateWorker.cpp b/src/lib/orderman/orders/queue_holder/state_workers/QHOStartStateWorker.cpp new file mode 100644 index 000000000..a5d2e47db --- /dev/null +++ b/src/lib/orderman/orders/queue_holder/state_workers/QHOStartStateWorker.cpp @@ -0,0 +1,128 @@ +#include "lib/orderman/orders/queue_holder/state_workers/QHOStartStateWorker.h" +#include "lib/orderman/orders/queue_holder/QueueHolderOrder.h" +#include "lib/domain_model/Security.h" +#include "lib/logging/logging.h" +#include "lib/orderman/actors/order_manager/OrderBuilder.h" +#include "lib/orderman/events/BookUpdateEvent.h" +#include "lib/orderman/orders/spreader_orders/spreader/SpreaderUtils.h" +#include "lib/orderman/orders/PreActivationOrderServices.h" +#include "lib/os/os.h" +#include "lib/utils/PBUtils.h" +#include +#include +#include "lib/os/os.h" + +namespace bts{ +namespace orderman{ + +QHOStartStateWorker::QHOStartStateWorker(QueueHolderOrder* parent) +: +_porder(parent) +{} + +void QHOStartStateWorker::on_transition (){ +} + +void QHOStartStateWorker::on_init_new( + const api::orderman::OrderDefinition& order_def, + const PreActivationOrderServices& pre_os){ + _porder->_is_succ_inited=_on_init_new(order_def, pre_os); +} +void QHOStartStateWorker::on_init_recovered( + const bts::api::orderman::OrderRecord& rec, + const PreActivationOrderServices& pre_os){ + _porder->_is_succ_inited=_on_init_new(rec.def(), pre_os); + _porder->_is_recovered=true; +} +void QHOStartStateWorker::on_activate(Price price, + Quantity qty, + OrderServices& services){ + api::orderman::OrderState& state=_porder->_reported_state; + // reference is kept even for orders that are not initialized + // properly or when constructed from the disk + _porder->_services = &services; + state.set_price(price.value()); + state.set_quantity(qty.value()); + // failed to init or recovered orders are sent directly + // to end (recovered have to be dealt with later) + if (_porder->_is_recovered || !_porder->_is_succ_inited) + _porder->_switch_state(QueueHolderOrderState::END); + else { + _porder->_order_builder.activate(services); + _porder->_order_manager.init( + _porder->_order_builder, + SecurityKey(_porder->_order_def.security_key()), + _porder->_order_def.side(), + _porder->_tick_size, + _porder->_order_def.custom_def().queue_holder().n_queue_orders(), + price, + qty); + services.subscribe_to_child_updates( + [this](const OrderStateUpdateEvent &os) { + _porder->_on_child_order_update(os); + }); + services.subscribe_to_book( + SecurityKey(_porder->_order_def.security_key()), + [this](const BookUpdateEvent &bk_event) { + _porder->_on_book_update(bk_event); + }); + services.subscribe_to_time([this](const bts::mercury::TimerEvent &te) { + _porder->_on_time(te); + }); + _porder->_switch_state(QueueHolderOrderState::WAITING_FOR_FIRST_ACK); + } +} +void QHOStartStateWorker::on_update(Price, + Quantity){ + _porder->_assert_false("QHOStartStateWorker::on_update"); +} +void QHOStartStateWorker::on_cancel(){ + _porder->_assert_false("QHOStartStateWorker::on_cancel"); +} +void QHOStartStateWorker::on_child_order_update( + const OrderStateUpdateEvent&){ + _porder->_assert_false("QHOStartStateWorker::on_child_order_update"); +} +void QHOStartStateWorker::on_book(const Book&, + const trace::CorID&){ + _porder->_assert_false("QHOStartStateWorker::on_book"); +} +void QHOStartStateWorker::on_time(const TimeStamp&){ + _porder->_assert_false("QHOStartStateWorker::on_time"); +} +bool QHOStartStateWorker::_on_init_new( + const api::orderman::OrderDefinition& order_def, + const PreActivationOrderServices& pre_os) { + _porder->_order_def=order_def; + if (!order_def.has_custom_def() || + !order_def.custom_def().has_queue_holder()) { + LOG(OrderMan, Error, + "QHOStartStateWorker::_on_init_new key:{} " + "OrderDefinition does not have QueueHolderDefinition", + _porder->key()); + return false; + } + const bts::api::Security* sec_ptr = + pre_os.sec_db.resolve(SecurityKey(order_def.security_key())); + if (sec_ptr==nullptr) { + LOG(OrderMan, Error, + "QHOStartStateWorker::_on_init_new key:{} " + "Could not resolve sec_key:{}", + _porder->key(), order_def.security_key()); + return false; + } + _porder->_tick_size=sec_ptr->contract_spec().low_tick(); + const api::orderman::QueueHolderDefinition& qho_def= + order_def.custom_def().queue_holder(); + api::orderman::OrderDefinition child_order_def = order_def; + child_order_def.mutable_custom_def()->CopyFrom(qho_def.child()); + _porder->_order_builder = OrderBuilder(_porder->key(), + child_order_def, + pre_os.order_factory, + qho_def.n_queue_orders()+1); + LOG(OrderMan, Info, + "QHOStartStateWorker::_on_init_new key:{} ", + _porder->key()); + return true; +} +}} \ No newline at end of file diff --git a/src/lib/orderman/orders/queue_holder/state_workers/QHOStartStateWorker.h b/src/lib/orderman/orders/queue_holder/state_workers/QHOStartStateWorker.h new file mode 100644 index 000000000..8f81036be --- /dev/null +++ b/src/lib/orderman/orders/queue_holder/state_workers/QHOStartStateWorker.h @@ -0,0 +1,40 @@ +#pragma once + +#include "lib/orderman/orders/queue_holder/IQueueHolderOrderStateWorker.h" + +namespace bts{ +namespace orderman{ + +class QueueHolderOrder; +// this is the starting state where the int_new/recover +// and activation is done. upon activation +// if everything is good, it places suborders and moves +// transitions to WAITING_FOR_FIRST_ACK +// else transitions to END +class QHOStartStateWorker : public IQueueHolderOrderStateWorker +{ +private: + QueueHolderOrder* const _porder; +public: + QHOStartStateWorker(QueueHolderOrder* parent); + QueueHolderOrderState state () const override { + return QueueHolderOrderState::START; + } + void on_transition () override; + void on_init_new(const api::orderman::OrderDefinition&, + const PreActivationOrderServices&) override; + void on_init_recovered(const bts::api::orderman::OrderRecord&, + const PreActivationOrderServices&) override; + void on_activate(Price, Quantity, OrderServices&) override; + void on_update(Price, Quantity) override; + void on_cancel() override; + void on_child_order_update(const OrderStateUpdateEvent&) override; + void on_book(const Book&, + const trace::CorID&) override; + void on_time(const TimeStamp&) override; +private: + bool _on_init_new(const api::orderman::OrderDefinition& order_def, + const PreActivationOrderServices& pre_os); +}; + +}} \ No newline at end of file diff --git a/src/lib/orderman/orders/queue_holder/state_workers/QHOWaitingForAckStateWorker.cpp b/src/lib/orderman/orders/queue_holder/state_workers/QHOWaitingForAckStateWorker.cpp new file mode 100644 index 000000000..e869d10a2 --- /dev/null +++ b/src/lib/orderman/orders/queue_holder/state_workers/QHOWaitingForAckStateWorker.cpp @@ -0,0 +1,81 @@ +#include "lib/orderman/orders/queue_holder/state_workers/QHOWaitingForAckStateWorker.h" +#include "lib/orderman/orders/queue_holder/QueueHolderOrder.h" +#include "lib/domain_model/Security.h" +#include "lib/logging/logging.h" +#include "lib/orderman/actors/order_manager/OrderBuilder.h" +#include "lib/orderman/events/BookUpdateEvent.h" +#include "lib/orderman/orders/spreader_orders/spreader/SpreaderUtils.h" +#include "lib/os/os.h" +#include "lib/utils/PBUtils.h" +#include +#include +#include "lib/os/os.h" + +namespace bts{ +namespace orderman{ + +QHOWaitingForAckStateWorker::QHOWaitingForAckStateWorker( + QueueHolderOrder* parent) +: +_porder(parent), +_orders_placed_once(false) +{} + +void QHOWaitingForAckStateWorker::on_transition (){ + // this is the only place where orders + // are placed + if(!_orders_placed_once){ + _porder->_order_manager.place_order(); + _orders_placed_once=true; + } + else + _porder->_order_manager.reenter_filled_orders(); +} + +void QHOWaitingForAckStateWorker::on_init_new( + const api::orderman::OrderDefinition&, + const PreActivationOrderServices&){ + _porder->_assert_false("QHOWaitingForAckStateWorker::on_init_new"); +} +void QHOWaitingForAckStateWorker::on_init_recovered( + const bts::api::orderman::OrderRecord&, + const PreActivationOrderServices&){ + _porder->_assert_false("QHOWaitingForAckStateWorker::on_init_recovered"); +} +void QHOWaitingForAckStateWorker::on_activate(Price, + Quantity, + OrderServices&){ + _porder->_assert_false("QHOWaitingForAckStateWorker::on_activate"); +} +void QHOWaitingForAckStateWorker::on_update(Price price, + Quantity quantity){ + // cache it here, and update order when + // transferring to WORKING + _porder->_set_state_price_qty(price,quantity); + if(_porder->_filled()) + _porder->_cancel_order(QueueHolderOrder::TerminationReason::FILLED); +} +void QHOWaitingForAckStateWorker::on_cancel(){ + _porder->_cancel_order(QueueHolderOrder::TerminationReason::EXTERNAL_CANCEL); +} +void QHOWaitingForAckStateWorker::on_child_order_update( + const OrderStateUpdateEvent& ev){ + QHOOrderManager& order_man=_porder->_order_manager; + if(order_man.on_order_update(ev)){ + if (_porder->_filled()) + _porder->_cancel_order(QueueHolderOrder::TerminationReason::FILLED); + else if(order_man.all_orders_acked()) + _porder->_switch_state(QueueHolderOrderState::WORKING); + } + else + LOG(OrderMan, Error, + "QHOWaitingForAckStateWorker::on_child_order_update " + "key:{} order:{} could not be found", + _porder->key(),ev.key); +} +void QHOWaitingForAckStateWorker::on_book(const Book&, + const trace::CorID&){ +} +void QHOWaitingForAckStateWorker::on_time(const TimeStamp&){ +} +}} \ No newline at end of file diff --git a/src/lib/orderman/orders/queue_holder/state_workers/QHOWaitingForAckStateWorker.h b/src/lib/orderman/orders/queue_holder/state_workers/QHOWaitingForAckStateWorker.h new file mode 100644 index 000000000..5a4f560f8 --- /dev/null +++ b/src/lib/orderman/orders/queue_holder/state_workers/QHOWaitingForAckStateWorker.h @@ -0,0 +1,42 @@ +#pragma once + +#include "lib/orderman/orders/queue_holder/IQueueHolderOrderStateWorker.h" + +namespace bts{ +namespace orderman{ + +class QueueHolderOrder; +// orders are placed on the transition to this state. it +// leaves the state when +// order is cxled -> WAITING_FOR_CANCEL_ALL +// order is overfilled -> WAITING_FOR_CANCEL_ALL +// all orders acked -> WORKING +// updates are passed over to the state and +// maybe used in deiciding if filled or not +// (since we are gong to to do away with this state +// most of the logic is moved out) +class QHOWaitingForAckStateWorker : public IQueueHolderOrderStateWorker +{ +private: + QueueHolderOrder* const _porder; + bool _orders_placed_once; +public: + QHOWaitingForAckStateWorker(QueueHolderOrder* parent); + QueueHolderOrderState state () const override { + return QueueHolderOrderState::WAITING_FOR_FIRST_ACK; + } + void on_transition () override; + void on_init_new(const api::orderman::OrderDefinition&, + const PreActivationOrderServices&) override; + void on_init_recovered(const bts::api::orderman::OrderRecord&, + const PreActivationOrderServices&) override; + void on_activate(Price, Quantity, OrderServices&) override; + void on_update(Price, Quantity) override; + void on_cancel() override; + void on_child_order_update(const OrderStateUpdateEvent&) override; + void on_book(const Book&, + const trace::CorID&) override; + void on_time(const TimeStamp&) override; +}; + +}} \ No newline at end of file diff --git a/src/lib/orderman/orders/queue_holder/state_workers/QHOWaitingForCancelAllStateWorker.cpp b/src/lib/orderman/orders/queue_holder/state_workers/QHOWaitingForCancelAllStateWorker.cpp new file mode 100644 index 000000000..f621753a9 --- /dev/null +++ b/src/lib/orderman/orders/queue_holder/state_workers/QHOWaitingForCancelAllStateWorker.cpp @@ -0,0 +1,74 @@ +#include "lib/orderman/orders/queue_holder/state_workers/QHOWaitingForCancelAllStateWorker.h" +#include "lib/orderman/orders/queue_holder/QueueHolderOrder.h" +#include "lib/domain_model/Security.h" +#include "lib/logging/logging.h" +#include "lib/orderman/actors/order_manager/OrderBuilder.h" +#include "lib/orderman/events/BookUpdateEvent.h" +#include "lib/orderman/orders/spreader_orders/spreader/SpreaderUtils.h" +#include "lib/os/os.h" +#include "lib/utils/PBUtils.h" +#include +#include +#include "lib/os/os.h" + +namespace bts{ +namespace orderman{ + +QHOWaitingForCancelAllStateWorker::QHOWaitingForCancelAllStateWorker( + QueueHolderOrder* parent) +: +_porder(parent) +{} + +void QHOWaitingForCancelAllStateWorker::on_transition (){ + _analyze_and_cancel(); +} + +void QHOWaitingForCancelAllStateWorker::on_init_new( + const api::orderman::OrderDefinition&, + const PreActivationOrderServices&){ + _porder->_assert_false("QHOWaitingForCancelAllStateWorker::on_init_new"); +} +void QHOWaitingForCancelAllStateWorker::on_init_recovered( + const bts::api::orderman::OrderRecord&, + const PreActivationOrderServices&){ + _porder->_assert_false("QHOWaitingForCancelAllStateWorker::on_init_recovered"); +} +void QHOWaitingForCancelAllStateWorker::on_activate(Price, + Quantity, + OrderServices&){ + _porder->_assert_false("QHOWaitingForCancelAllStateWorker::on_activate"); +} +void QHOWaitingForCancelAllStateWorker::on_update(Price, + Quantity){ + LOG(OrderMan, Warn, "QHOWaitingForCancelAllStateWorker::on_update " + "key:{} rejected",_porder->key()); +} +void QHOWaitingForCancelAllStateWorker::on_cancel(){ + LOG(OrderMan, Info, "QHOWaitingForCancelAllStateWorker::on_cancel " + "key:{} already cancelled",_porder->key()); +} +void QHOWaitingForCancelAllStateWorker::on_child_order_update( + const OrderStateUpdateEvent& ev){ + if(_porder->_order_manager.on_order_update(ev)) + _analyze_and_cancel(); + else + LOG(OrderMan, Error, + "QHOWaitingForCancelAllStateWorker::on_child_order_update " + "key:{} order:{} could not be found", + _porder->key(),ev.key); +} +void QHOWaitingForCancelAllStateWorker::on_book(const Book&, + const trace::CorID&){ +} +void QHOWaitingForCancelAllStateWorker::on_time(const TimeStamp&){ + /// TODO, time-out +} +void QHOWaitingForCancelAllStateWorker::_analyze_and_cancel(){ + QHOOrderManager& order_man=_porder->_order_manager; + if(!order_man.all_orders_terminal()) + order_man.cancel(); + else + _porder->_switch_state(QueueHolderOrderState::END); +} +}} \ No newline at end of file diff --git a/src/lib/orderman/orders/queue_holder/state_workers/QHOWaitingForCancelAllStateWorker.h b/src/lib/orderman/orders/queue_holder/state_workers/QHOWaitingForCancelAllStateWorker.h new file mode 100644 index 000000000..f2e7c53f2 --- /dev/null +++ b/src/lib/orderman/orders/queue_holder/state_workers/QHOWaitingForCancelAllStateWorker.h @@ -0,0 +1,39 @@ +#pragma once + +#include "lib/orderman/orders/queue_holder/IQueueHolderOrderStateWorker.h" + +namespace bts{ +namespace orderman{ + +class QueueHolderOrder; +// transfer to this state means the order needs to +// be cancelled. _analyze_and_cancel() is called +// on_transition and everytime there is an order update. +// _analyze_and_cancel() tried cancelling all orders, +// and if orders are in terminal state goes to end +class QHOWaitingForCancelAllStateWorker : public IQueueHolderOrderStateWorker +{ +private: + QueueHolderOrder* const _porder; +public: + QHOWaitingForCancelAllStateWorker(QueueHolderOrder* parent); + QueueHolderOrderState state () const override { + return QueueHolderOrderState::WAITING_FOR_CANCEL_ALL; + } + void on_transition () override; + void on_init_new(const api::orderman::OrderDefinition&, + const PreActivationOrderServices&) override; + void on_init_recovered(const bts::api::orderman::OrderRecord&, + const PreActivationOrderServices&) override; + void on_activate(Price, Quantity, OrderServices&) override; + void on_update(Price, Quantity) override; + void on_cancel() override; + void on_child_order_update(const OrderStateUpdateEvent&) override; + void on_book(const Book&, + const trace::CorID&) override; + void on_time(const TimeStamp&) override; +private: + void _analyze_and_cancel(); +}; + +}} \ No newline at end of file diff --git a/src/lib/orderman/orders/queue_holder/state_workers/QHOWorkingStateWorker.cpp b/src/lib/orderman/orders/queue_holder/state_workers/QHOWorkingStateWorker.cpp new file mode 100644 index 000000000..136c9b699 --- /dev/null +++ b/src/lib/orderman/orders/queue_holder/state_workers/QHOWorkingStateWorker.cpp @@ -0,0 +1,112 @@ +#include "lib/orderman/orders/queue_holder/state_workers/QHOWorkingStateWorker.h" +#include "lib/orderman/orders/queue_holder/QueueHolderOrder.h" +#include "lib/domain_model/Security.h" +#include "lib/logging/logging.h" +#include "lib/orderman/actors/order_manager/OrderBuilder.h" +#include "lib/orderman/events/BookUpdateEvent.h" +#include "lib/orderman/orders/spreader_orders/spreader/SpreaderUtils.h" +#include "lib/os/os.h" +#include "lib/utils/PBUtils.h" +#include +#include +#include "lib/os/os.h" + +namespace bts{ +namespace orderman{ + +QHOWorkingStateWorker::QHOWorkingStateWorker(QueueHolderOrder* parent) +: +_porder(parent) +{} +void QHOWorkingStateWorker::on_transition (){ + if(!_analyze_moving_out()){ + const api::orderman::OrderState& state=_porder->_reported_state; + // cached updates while waiting for acks + on_update(Price(state.price()), + Quantity(state.quantity())); + } +} +void QHOWorkingStateWorker::on_init_new( + const api::orderman::OrderDefinition&, + const PreActivationOrderServices&){ + _porder->_assert_false("QHOWorkingStateWorker::on_init_new"); +} +void QHOWorkingStateWorker::on_init_recovered( + const bts::api::orderman::OrderRecord&, + const PreActivationOrderServices&){ + _porder->_assert_false("QHOWorkingStateWorker::on_init_recovered"); +} +void QHOWorkingStateWorker::on_activate(Price, + Quantity, + OrderServices&){ + _porder->_assert_false("QHOWorkingStateWorker::on_activate"); +} +void QHOWorkingStateWorker::on_update(Price price, + Quantity qty){ + _porder->_set_state_price_qty(price,qty); + if(_porder->_filled()) + _porder->_cancel_order(QueueHolderOrder::TerminationReason::FILLED); + else + _porder->_order_manager.modify_order(price, qty); +} +void QHOWorkingStateWorker::on_cancel(){ + _porder->_order_manager.cancel(); + _porder->_cancel_order(QueueHolderOrder::TerminationReason::EXTERNAL_CANCEL); +} +void QHOWorkingStateWorker::on_child_order_update( + const OrderStateUpdateEvent& ev){ + QHOOrderManager& order_man=_porder->_order_manager; + if(order_man.on_order_update(ev)){ + if(!_analyze_moving_out()){ + if(order_man.last_update_has_fills()) + // in case of fills, we can reduce + // the qty of the trailing orders to + // decrease probablity of overfills + order_man.prune_quantities(); + } + } + else + LOG(OrderMan, Error, "QHOWorkingStateWorker::on_child_order_update " + "key:{} order:{} could not be found", + _porder->key(),ev.key); +} +// returns true if state is changed +bool QHOWorkingStateWorker::_analyze_moving_out(){ + // order is cancelled if over filled or any of the + // constituent orders end up in an unexpected terminal + // state + if(_porder->_filled()){ + _porder->_cancel_order(QueueHolderOrder::TerminationReason::FILLED); + return true; + } + const QHOOrderManager& order_man=_porder->_order_manager; + if(order_man.has_cancelled_order()){ + _porder->_cancel_order( + QueueHolderOrder::TerminationReason::UNEXPECTED_CHILD_CANCEL); + return true; + } + if(order_man.has_cancelled_order()){ + _porder->_cancel_order(QueueHolderOrder::TerminationReason::CHILD_ERROR); + return true; + } + // QHO order's target qty has not been reached + // yet one or more component orders has been filled. + // switching to WAITING_FOR_FIRST_ACK will cause + // filled orders to be replaced with new orders + if (order_man.has_completed_order()){ + _porder->_switch_state(QueueHolderOrderState::WAITING_FOR_FIRST_ACK); + return true; + } + // all orders have to be acked in this state && + // if an order was cxled or errored out, the first + // if would have caught it. and if filled, the + // second would have + bts_assert(order_man.all_orders_acked() && !order_man.has_terminal_order()); + return false; +} +void QHOWorkingStateWorker::on_book(const Book&, + const trace::CorID&){ +} +void QHOWorkingStateWorker::on_time(const TimeStamp&){ +} +}} \ No newline at end of file diff --git a/src/lib/orderman/orders/queue_holder/state_workers/QHOWorkingStateWorker.h b/src/lib/orderman/orders/queue_holder/state_workers/QHOWorkingStateWorker.h new file mode 100644 index 000000000..57c14e6c2 --- /dev/null +++ b/src/lib/orderman/orders/queue_holder/state_workers/QHOWorkingStateWorker.h @@ -0,0 +1,37 @@ +#pragma once + +#include "lib/orderman/orders/queue_holder/IQueueHolderOrderStateWorker.h" + +namespace bts{ +namespace orderman{ + +class QueueHolderOrder; +// main working state +class QHOWorkingStateWorker : public IQueueHolderOrderStateWorker +{ +private: + QueueHolderOrder* const _porder; +public: + QHOWorkingStateWorker(QueueHolderOrder* parent); + QueueHolderOrderState state () const override { + return QueueHolderOrderState::WORKING; + } + void on_transition () override; + void on_init_new(const api::orderman::OrderDefinition&, + const PreActivationOrderServices&) override; + void on_init_recovered(const bts::api::orderman::OrderRecord&, + const PreActivationOrderServices&) override; + void on_activate(Price, Quantity, OrderServices&) override; + void on_update(Price, Quantity) override; + void on_cancel() override; + void on_child_order_update(const OrderStateUpdateEvent&) override; + void on_book(const Book&, + const trace::CorID&) override; + void on_time(const TimeStamp&) override; +private: + // returns true if the state is changed + bool _analyze_moving_out(); + bool _needs_cancelling() const; +}; + +}} \ No newline at end of file diff --git a/src/lib/orderman/orders/spreader_orders/ISpreaderStateWorker.h b/src/lib/orderman/orders/spreader_orders/ISpreaderStateWorker.h index 07cefede3..325d44b7a 100644 --- a/src/lib/orderman/orders/spreader_orders/ISpreaderStateWorker.h +++ b/src/lib/orderman/orders/spreader_orders/ISpreaderStateWorker.h @@ -34,7 +34,7 @@ public: // 5. called when the user cancels an order virtual void on_cancel() = 0; // 6. on market data update (support late joiners) - virtual void on_book(const Book&,trace::CorID ) = 0; + virtual void on_book(const Book&) = 0; // 15. settlement price update virtual void on_settlement_price(const SettlementUpdateEvent&) = 0; // 7. time event called by the infrastructure @@ -42,8 +42,7 @@ public: // 8. when a quoter order ack from the exchange has an error virtual void on_quoter_order_error(SpreaderLegData& leg_data) = 0; // 9. on a quoter order fill - virtual void on_quoter_order_fill(SpreaderLegData& leg_data, - trace::CorID ) = 0; + virtual void on_quoter_order_fill(SpreaderLegData& leg_data) = 0; // 10. on a quoter status update without a fill virtual void on_quoter_order_status_update(SpreaderLegData& leg_data) = 0; // 11. when a hedger order ack from the exchange has an error @@ -57,6 +56,6 @@ public: virtual void on_quoter_irrecoverable_error() = 0; // 16. when the spreader order is cracked, setting the // child orders free - virtual void on_crack () {} + virtual void on_detach () {} }; }} diff --git a/src/lib/orderman/orders/spreader_orders/SpreaderOrder.cpp b/src/lib/orderman/orders/spreader_orders/SpreaderOrder.cpp index 804583d16..24ec42c67 100644 --- a/src/lib/orderman/orders/spreader_orders/SpreaderOrder.cpp +++ b/src/lib/orderman/orders/spreader_orders/SpreaderOrder.cpp @@ -62,9 +62,9 @@ void SpreaderOrder::on_init_recovered(const bts::api::orderman::OrderRecord& ord SpreaderPreActivationOrderServices(&pao_services)); _report_state(); } -void SpreaderOrder::on_activate(Price price, Quantity quantity, - OrderServices& services, const trace::CorID&){ - if (!_active) return; +OrderOpResult SpreaderOrder::on_activate(Price price, Quantity quantity, + OrderServices& services){ + if (!_active) return OrderOpResult{api::orderman::ORDER_ERROR_OP_NOT_SUPPORTED}; SpreaderOrderServices spreader_order_services (&services); _on_activate(price, quantity, spreader_order_services); // the reason why this is immediatly reported (vs in the timer @@ -72,25 +72,29 @@ void SpreaderOrder::on_activate(Price price, Quantity quantity, // on_init_recovered, it wont subsribe to the timer event // and hence the report wont go out _comp_and_report_state(); + return OrderOpResult {}; } -void SpreaderOrder::on_update(Price price, Quantity quantity,trace::CorID const&){ - if (!_active) return; +OrderOpResult SpreaderOrder::on_update(Price price, Quantity quantity){ + if (!_active) return OrderOpResult{api::orderman::ORDER_ERROR_OP_NOT_SUPPORTED}; LOG(OrderMan, Info, "SpreaderOrder.on_update key:{} price:{} quantity:{}", key().value(), price.value(), quantity.value()); _state_worker->on_update(price, quantity); _report_state(); + return OrderOpResult {}; } -void SpreaderOrder::on_cancel(trace::CorID const&){ - if (!_active) return; +OrderOpResult SpreaderOrder::on_cancel(){ + if (!_active) return OrderOpResult{api::orderman::ORDER_ERROR_OP_NOT_SUPPORTED}; LOG(OrderMan, Info, "SpreaderOrder.on_cancel key:{}", key().value()); _state_worker->on_cancel(); _report_state(); + return OrderOpResult {}; } -void SpreaderOrder::on_crack(trace::CorID const&){ - if (!_active) return; - LOG(OrderMan, Info, "SpreaderOrder.on_crack key: {}", key().value()); - _state_worker->on_crack(); +OrderOpResult SpreaderOrder::on_detach(){ + if (!_active) return OrderOpResult{api::orderman::ORDER_ERROR_OP_NOT_SUPPORTED}; + LOG(OrderMan, Info, "SpreaderOrder.on_detach key: {}", key().value()); + _state_worker->on_detach(); _report_state(); + return OrderOpResult {}; } // ISpreaderManager //////////////////// //////////////////////////////////////// @@ -124,9 +128,8 @@ void SpreaderOrder::_on_time(const bts::mercury::TimerEvent& t_event){ } void SpreaderOrder::_on_book_update(const BookUpdateEvent& book_event){ if (!_active) return; - auto scoped = _order_services->log_scope(book_event.trace, - "SpreaderOrder::_on_book_update", key().value()); - _state_worker->on_book (book_event.book,book_event.trace); + auto scoped = _order_services->log_scope("SpreaderOrder::_on_book_update", key().value()); + _state_worker->on_book (book_event.book); } void SpreaderOrder::_on_settlement_update(const SettlementUpdateEvent& settlement_event){ @@ -158,11 +161,10 @@ void SpreaderOrder::_keep_hedging_path_hot(){ bts::api::orderman::OrderState state; state.set_filled_quantity(q_ord.current_fills().value()); state.set_last_price(q_ord.last_update_filled_price().value()); - bts::api::orderman::OrderDefinition ord_def; OrderStateUpdateEvent ord_ev (q_ord.order_key(), - key(), - ord_def, - state); + key(), + def(), + state); ord_ev.status=q_ord.status(); ord_ev.price=q_ord.last_reported_order_price().value(); _on_child_order_update(ord_ev); @@ -211,11 +213,10 @@ void SpreaderOrder::_on_non_quoter_order(const OrderStateUpdateEvent& ord_ev){ ChildOrderError order_error = _get_order_error (ord_ev, hedger.expecting_cancel_update()); LOG(OrderMan, Info, "SpreaderOrder::_on_child_order_update hedger " - "key:{} sec_key:{} state:{} order_key:{} status:{} " + "key:{} state:{} order_key:{} status:{} " "filled_qty:{} price:{} last_price:{} " "msg:{} child_order_error:{}", key(), - ord_ev.definition->security_key(), static_cast(_state_worker->state()), ord_ev.key, ord_ev.status, @@ -233,10 +234,9 @@ void SpreaderOrder::_on_non_quoter_order(const OrderStateUpdateEvent& ord_ev){ else LOG(OrderMan, Error, "SpreaderOrder::_on_child_order_update " "unknown ord " - "key:{} sec_key:{} order_key:{} status:{} " + "key:{} order_key:{} status:{} " "filled_qty:{} last_price:{} msg:{}", key(), - ord_ev.definition->security_key(), ord_ev.key, ord_ev.status, ord_ev.filled_quantity, @@ -361,12 +361,10 @@ bool SpreaderOrder::_quoters_can_accept_modification (){ } void SpreaderOrder::_send_hedge(size_t hedge_leg_index, Price hedge_price, - Quantity hedge_qty, - const trace::CorID& trace){ + Quantity hedge_qty){ _bookkeeping_data().add_new_hedger (hedge_leg_index, hedge_price, - hedge_qty, - trace); + hedge_qty); } void SpreaderOrder::_compute_hedge_price_quantity(size_t filled_leg_index, Price fill_price, diff --git a/src/lib/orderman/orders/spreader_orders/SpreaderOrder.h b/src/lib/orderman/orders/spreader_orders/SpreaderOrder.h index 3a3d8824e..f49e9c755 100644 --- a/src/lib/orderman/orders/spreader_orders/SpreaderOrder.h +++ b/src/lib/orderman/orders/spreader_orders/SpreaderOrder.h @@ -102,7 +102,7 @@ public: public: // inherited function to return the OrderDefinition. asserts // if on_init_new has not been called yet - const api::orderman::OrderDefinition& definition() const override; + const api::orderman::OrderDefinition& definition() const ; // this is the construction, can be slow void on_init_new(const bts::api::orderman::OrderDefinition& order_def, const PreActivationOrderServices&) override; @@ -111,15 +111,15 @@ public: const PreActivationOrderServices&) override; // this is in the critical path, orders can be submitted now // (this is only called once and after the on_init_new) - void on_activate(Price, Quantity, OrderServices&,trace::CorID const&) override; + OrderOpResult on_activate(Price, Quantity, OrderServices&) override; // called when the user (or a higher level order) // updates the order's price or quantity - void on_update(Price, Quantity,trace::CorID const&) override; + OrderOpResult on_update(Price, Quantity) override; // called when the user (or higher level order) cancels an order - void on_cancel(trace::CorID const&) override; - // crack means to let the lower level orders lose from the higher + OrderOpResult on_cancel() override; + // detach means to let the lower level orders lose from the higher // level order and cancel the higher level order - void on_crack(trace::CorID const&) override; + OrderOpResult on_detach() override; // ISpreaderManager //////////////////// //////////////////////////////////////// public: @@ -158,11 +158,10 @@ private: leg_data.quoter().expecting_cancel_update()); LOG(OrderMan, _cw_helper.llevel, "SpreaderOrder::_on_child_order_update quoter order " - "key:{} sec_key:{} state:{} order_key:{} status:{} " + "key:{} state:{} order_key:{} status:{} " "filled_qty:{} price:{} last_price:{} " "msg:{} child_order_error:{}", key(), - ord_ev.definition->security_key(), static_cast(_state_worker->state()), ord_ev.key, ord_ev.status, @@ -182,7 +181,7 @@ private: else{ ord_indicator = 'f'; LOG(OrderMan,_cw_helper.llevel,"h_p {} child update {}",ord_indicator,_diff_ns()); - _state_worker->on_quoter_order_fill (leg_data,ord_ev.trace); + _state_worker->on_quoter_order_fill (leg_data); } } } @@ -233,8 +232,7 @@ private: // quantity 'filled_quantity' void _send_hedge(size_t hedge_leg_index, Price hedge_price, - Quantity hedge_qty, - const trace::CorID&); + Quantity hedge_qty); void _compute_hedge_price_quantity(size_t filled_leg_index, Price filled_price, double filled_quantity, @@ -335,17 +333,14 @@ public: void test_only_on_book_update(const BookUpdateEvent& b) { _on_book_update(b); } - void test_only_on_book_update(const Book& b, - trace::CorID const&trace) { - _on_book_update(BookUpdateEvent(b, trace)); + void test_only_on_book_update(const Book& b) { + _on_book_update(BookUpdateEvent(b)); } void test_only_on_child_order_update (OrderKey order_key, bts::api::orderman::OrderStatus status, Quantity total_filled_qty, Price avg_price) { - bts::api::orderman::OrderDefinition order_def; - order_def.set_security_key(0); bts::api::orderman::OrderState order_state; order_state.set_status(status); order_state.set_filled_quantity(total_filled_qty.value()); @@ -353,9 +348,8 @@ public: order_state.set_price(avg_price.value()); OrderStateUpdateEvent ord_ev (order_key, OrderKey(0), - order_def, - order_state, - trace::CorID()); + def(), + order_state); _on_child_order_update (ord_ev); } void test_only_on_init_new( diff --git a/src/lib/orderman/orders/spreader_orders/spreader/SingleFillHedger.cpp b/src/lib/orderman/orders/spreader_orders/spreader/SingleFillHedger.cpp index 91bd8f2bd..21ccd718a 100644 --- a/src/lib/orderman/orders/spreader_orders/spreader/SingleFillHedger.cpp +++ b/src/lib/orderman/orders/spreader_orders/spreader/SingleFillHedger.cpp @@ -83,9 +83,8 @@ _end_state_worker (this, other._end_state_worker){ /****************************External Calls**************************/ /********************************************************************/ void SingleFillHedger::init_hedger (Price price, - Quantity quantity, - const trace::CorID& trace){ - _worker->init(price,quantity,trace); + Quantity quantity){ + _worker->init(price,quantity); } void SingleFillHedger::on_order_update(const SpreaderChildOrderState& u){ //bts_assert (u.order_key() == _order.order_key()); @@ -96,9 +95,8 @@ void SingleFillHedger::on_order_update(const SpreaderChildOrderState& u){ u.last_update_filled_quantity()); _worker->on_order_update (u); } -void SingleFillHedger::on_book(const Book& book, - trace::CorID &trace){ - _worker->on_book (book,trace); +void SingleFillHedger::on_book(const bts::orderman::Book& book){ + _worker->on_book (book); } void SingleFillHedger::cancel_hedge(){ LOG(OrderMan, Info, "SingleFillHedger::cancel_order key:{} state:{}", diff --git a/src/lib/orderman/orders/spreader_orders/spreader/SingleFillHedger.h b/src/lib/orderman/orders/spreader_orders/spreader/SingleFillHedger.h index 4e91d0b4f..67a7eee1c 100644 --- a/src/lib/orderman/orders/spreader_orders/spreader/SingleFillHedger.h +++ b/src/lib/orderman/orders/spreader_orders/spreader/SingleFillHedger.h @@ -50,12 +50,10 @@ private: void _switch_state (IHedgerStateWorker* new_state); // helpers void _place_order (Price price, - Quantity quantity, - const trace::CorID& trace) { + Quantity quantity) { _child_order_state.place_order(price, quantity, - _spreader.current_time(), - trace); + _spreader.current_time()); } void _modify_order (Price new_price){ _child_order_state.modify_order(new_price); @@ -95,13 +93,13 @@ public: //that live in the START state until... //iii.until init_hedger is called which sets the price //qty and causes the order to be submitted - void init_hedger (Price price, Quantity quantity,const trace::CorID&); + void init_hedger (Price price, Quantity quantity); //b. called by the spreader when there is an order update // reported by the exchange void on_order_update(const SpreaderChildOrderState& order_update_message); //c. called when the market data associated // with this security is changed - void on_book(const Book& book,trace::CorID &); + void on_book(const bts::orderman::Book& book); //d. called when the hedge order is cancelled, either // manually or automatically void cancel_hedge(); diff --git a/src/lib/orderman/orders/spreader_orders/spreader/SingleLegQuoter.cpp b/src/lib/orderman/orders/spreader_orders/spreader/SingleLegQuoter.cpp index 077002ddc..d164f50ca 100644 --- a/src/lib/orderman/orders/spreader_orders/spreader/SingleLegQuoter.cpp +++ b/src/lib/orderman/orders/spreader_orders/spreader/SingleLegQuoter.cpp @@ -104,9 +104,9 @@ void SingleLegQuoter::update_order_status(const SpreaderChildOrderState& u){ _worker->on_order_update (u); } void SingleLegQuoter::on_book(size_t leg_index, - const bts::orderman::Book& book,trace::CorID trace){ + const bts::orderman::Book& book){ bts_assert(_active_quoting); - _worker->on_book (leg_index, book,trace); + _worker->on_book (leg_index, book); } void SingleLegQuoter::update_other_leg_fills(size_t leg_index, Quantity filled_quantity){ diff --git a/src/lib/orderman/orders/spreader_orders/spreader/SingleLegQuoter.h b/src/lib/orderman/orders/spreader_orders/spreader/SingleLegQuoter.h index 8c8118935..cd8f7a5c1 100644 --- a/src/lib/orderman/orders/spreader_orders/spreader/SingleLegQuoter.h +++ b/src/lib/orderman/orders/spreader_orders/spreader/SingleLegQuoter.h @@ -101,7 +101,7 @@ public: //c. called when the market data associated // with this security is changed void on_book(size_t leg_index, - const bts::orderman::Book&,trace::CorID ); + const bts::orderman::Book&); //d. called when the order is cancelled, either // manually or automatically void cancel_order(); @@ -168,15 +168,13 @@ private: return _price_quantity_state.target_reached(); } void _place_order (Price price, - Quantity quantity, - const trace::CorID &trace) { + Quantity quantity) { _child_order_state.place_order(price, quantity, - _spreader.current_time(), - trace); + _spreader.current_time()); } - void _modify_order (Price price, Quantity quantity, trace::CorID &trace) { - _child_order_state.modify_order(price, quantity, trace); + void _modify_order (Price price, Quantity quantity) { + _child_order_state.modify_order(price, quantity); } void _cancel_order () {_child_order_state.cancel_order();} // this updates the hedge reduction in _price_quantity_state diff --git a/src/lib/orderman/orders/spreader_orders/spreader/SpreaderBookkeepingData.h b/src/lib/orderman/orders/spreader_orders/spreader/SpreaderBookkeepingData.h index a83092ab0..994b401d0 100644 --- a/src/lib/orderman/orders/spreader_orders/spreader/SpreaderBookkeepingData.h +++ b/src/lib/orderman/orders/spreader_orders/spreader/SpreaderBookkeepingData.h @@ -105,11 +105,10 @@ public: // can resize) inline SingleFillHedger& add_new_hedger(size_t leg_index, Price hedge_price, - Quantity hedge_quantity, - const trace::CorID& trace){ + Quantity hedge_quantity){ bts_assert(leg_index < _leg_data.size()); SpreaderLegData& leg_data=_leg_data[leg_index]; - return leg_data.add_new_hedger(hedge_price,hedge_quantity,trace); + return leg_data.add_new_hedger(hedge_price,hedge_quantity); } // finds the spreader fill, price (ie averages it out, using // the size and price ratio, across all legs) diff --git a/src/lib/orderman/orders/spreader_orders/spreader/SpreaderChildOrderState.cpp b/src/lib/orderman/orders/spreader_orders/spreader/SpreaderChildOrderState.cpp index 409997d54..622fd4cba 100644 --- a/src/lib/orderman/orders/spreader_orders/spreader/SpreaderChildOrderState.cpp +++ b/src/lib/orderman/orders/spreader_orders/spreader/SpreaderChildOrderState.cpp @@ -22,7 +22,6 @@ _filled_quantity(src._filled_quantity), _last_filled_price(src._last_filled_price), _last_reported_order_price(src._last_reported_order_price), _last_filled_quantity(src._last_filled_quantity), -_last_update_trace(src._last_update_trace), _out_price(src._out_price), _out_quantity(src._out_quantity), _order_place_time(src._order_place_time) @@ -46,7 +45,7 @@ void SpreaderChildOrderState::re_init (ChildOrder& child_order){ _filled_price, _filled_quantity, _base_price, _base_quantity); _n_place_orders = 0; - _n_cancel_orders = _n_modify_orders = 0; + _n_cancel_orders = _n_modify_orders = 0; _child_order = ChildOrder(); _child_order = std::move(child_order); _status = bts::api::orderman::OrderStatus::ORDER_STATUS_INACTIVE; @@ -55,9 +54,8 @@ void SpreaderChildOrderState::re_init (ChildOrder& child_order){ _last_filled_price = Price(0); _last_reported_order_price=Price(0); _last_filled_quantity = Quantity(0); - _last_update_trace=trace::CorID(); _out_price = Price(0); _out_quantity = Quantity(0); _order_place_time=bts::TimeStamp(); } -}} \ No newline at end of file +}} diff --git a/src/lib/orderman/orders/spreader_orders/spreader/SpreaderChildOrderState.h b/src/lib/orderman/orders/spreader_orders/spreader/SpreaderChildOrderState.h index f818c2cc6..4046db95a 100644 --- a/src/lib/orderman/orders/spreader_orders/spreader/SpreaderChildOrderState.h +++ b/src/lib/orderman/orders/spreader_orders/spreader/SpreaderChildOrderState.h @@ -44,9 +44,6 @@ private: Price _last_filled_price; Price _last_reported_order_price; Quantity _last_filled_quantity; - // this is the trace of the order event - // from the last on_order_update call - trace::CorID _last_update_trace; // this is latest price, qty sent out Price _out_price; Quantity _out_quantity; @@ -86,12 +83,23 @@ public: Quantity last_update_filled_quantity () const { return _last_filled_quantity; } + // all the status calls are based on the + // current order (and not the subsumed ones) bool terminal_status() const { return SpreaderUtils::order_in_terminal_state(_status); } - bool acknowledged () const { + bool acknowledged() const { return SpreaderUtils::order_acknowledged (_status); } + bool cancelled() const{ + return SpreaderUtils::order_in_cancelled_state(_status); + } + bool completed() const{ + return SpreaderUtils::order_in_completed_state(_status); + } + bool errored() const{ + return SpreaderUtils::order_in_error_state(_status); + } // this is total fills across current and // previous orders Quantity total_fills() const { @@ -116,8 +124,10 @@ public: bts::TimeStamp order_place_time() const{ return _order_place_time; } - const trace::CorID& last_update_trace() const{ - return _last_update_trace; + // returns true if the current order has been + // cancelled + bool is_cancelled() const{ + return _n_cancel_orders>0; } // init /////////////////// /////////////////////////// @@ -140,7 +150,6 @@ public: - _filled_quantity.value()); _last_filled_price = Price(e.last_price); _last_reported_order_price=Price(e.price); - _last_update_trace=e.trace; SpreaderUtils::compute_average_price(_filled_price, _filled_quantity, _last_filled_price, @@ -152,8 +161,7 @@ public: ///////////////////////////////////// void place_order(Price price, Quantity quantity, - bts::TimeStamp curr_time, - const trace::CorID& trace){ + bts::TimeStamp curr_time){ auto start = utils::TimeStamp::now(); _out_price = price; _out_quantity = quantity; @@ -161,29 +169,24 @@ public: bts_assert(_n_place_orders == 0); _n_place_orders++; if (_is_live) - _child_order.activate(price, quantity, trace); + _child_order.activate(price, quantity); LOG(OrderMan, Info, "SpreaderChildOrderState::place_order " "is_quoting:{} key:{} sec_key:{} live:{} " - "price:{} qty:{} cid:{} t:{}", + "price:{} qty:{} t:{}", _is_quoting, order_key(), _sec_key, - _is_live, price, quantity, trace.sn, - (utils::TimeStamp::now()-start).nanoseconds()); + _is_live, price, quantity, + (utils::TimeStamp::now()-start).nanoseconds()); } void modify_order(Price price){ - trace::CorID dont_care; - modify_order(price,_out_quantity,dont_care); + modify_order(price,_out_quantity); } void modify_order(Price price, Quantity quantity){ - trace::CorID dont_care; - modify_order(price,quantity,dont_care); - } - void modify_order(Price price, Quantity quantity, trace::CorID &trace){ auto start = utils::TimeStamp::now(); _out_price = price; _out_quantity = quantity; _n_modify_orders++; if (_is_live) - _child_order.update(price, quantity, trace); + _child_order.update(price, quantity); LOG(OrderMan, Info, "SpreaderChildOrderState::modify_order " "is_quoting:{} key:{} sec_key:{} live:{} " "price:{} quantity:{} mod_no:{} t:{}", diff --git a/src/lib/orderman/orders/spreader_orders/spreader/SpreaderLegData.h b/src/lib/orderman/orders/spreader_orders/spreader/SpreaderLegData.h index dd295df48..c3b2d4031 100644 --- a/src/lib/orderman/orders/spreader_orders/spreader/SpreaderLegData.h +++ b/src/lib/orderman/orders/spreader_orders/spreader/SpreaderLegData.h @@ -181,10 +181,9 @@ public: return _hedger_manager.test_only_get_hedger_at(index); } SingleFillHedger& add_new_hedger(bts::Price hedge_price, - bts::Quantity hedge_quantity, - const trace::CorID& trace){ + bts::Quantity hedge_quantity){ SingleFillHedger& rv = _hedger_manager.get_hedger(); - rv.init_hedger (hedge_price,hedge_quantity,trace); + rv.init_hedger (hedge_price,hedge_quantity); return rv; } }; diff --git a/src/lib/orderman/orders/spreader_orders/spreader/SpreaderUtils.cpp b/src/lib/orderman/orders/spreader_orders/spreader/SpreaderUtils.cpp index 84eb24597..d6079fb3b 100644 --- a/src/lib/orderman/orders/spreader_orders/spreader/SpreaderUtils.cpp +++ b/src/lib/orderman/orders/spreader_orders/spreader/SpreaderUtils.cpp @@ -45,13 +45,25 @@ bool SpreaderUtils::resolve_synthetic_spread (const SpreaderPreActivationOrderSe quoter_order_def.set_security_key (leg.security().id()); quoter_order_def.set_side(leg_order_side); quoter_order_def.set_sub_type(bts::api::orderman::OrderSubType::ORDER_SUB_TYPE_QUOTING_LEG); - quoter_order_def.mutable_custom_def()->mutable_limit()->MergeFrom (api::orderman::LimitOrderDefinition()); + + uint32_t n_queue_holder_orders=leg_params.quote_params().n_queue_holder_orders(); + if(n_queue_holder_orders>0){ + api::orderman::QueueHolderDefinition qho_order_def; + qho_order_def.set_n_queue_orders(n_queue_holder_orders); + qho_order_def.mutable_child()->mutable_limit()->MergeFrom (api::orderman::LimitOrderDefinition()); + quoter_order_def.mutable_custom_def()->mutable_queue_holder()->MergeFrom (qho_order_def); + } + else{ + quoter_order_def.mutable_custom_def()->mutable_limit()->MergeFrom (api::orderman::LimitOrderDefinition()); + } + if(leg_params.quote_params().has_quote_hidden()) quoter_order_def.set_time_in_force(bts::api::orderman::TimeInForce::TIME_IN_FORCE_IOC); else quoter_order_def.set_time_in_force(bts::api::orderman::TimeInForce::TIME_IN_FORCE_DAY); // hedger order def api::orderman::OrderDefinition hedger_order_def = quoter_order_def; + hedger_order_def.mutable_custom_def()->mutable_limit()->MergeFrom (api::orderman::LimitOrderDefinition()); hedger_order_def.set_time_in_force(bts::api::orderman::TimeInForce::TIME_IN_FORCE_DAY); hedger_order_def.set_sub_type(bts::api::orderman::OrderSubType::ORDER_SUB_TYPE_HEDGING_LEG); LegPropertyData leg_property_data(leg_idx, leg, leg_params, leg_order_side,sec.synthetic().price_calc()); diff --git a/src/lib/orderman/orders/spreader_orders/spreader/SpreaderUtils.h b/src/lib/orderman/orders/spreader_orders/spreader/SpreaderUtils.h index fecbf9430..aa890d3d1 100644 --- a/src/lib/orderman/orders/spreader_orders/spreader/SpreaderUtils.h +++ b/src/lib/orderman/orders/spreader_orders/spreader/SpreaderUtils.h @@ -239,27 +239,39 @@ public: // cum qty upto that price. // returns false if the target_price is not found. // this is used to find the qty and cumm_qty - static bool find_qty_at_price_level (const Book& book, + static bool find_qty_upto_price_level (const Book& book, api::Side book_side, Price target_price, - double tick_size, - Quantity& price_qty, + double, Quantity& cumm_qty){ - price_qty = Quantity(0); cumm_qty = Quantity(0); + cumm_qty = Quantity(0); const size_t n_levels = book.n_levels(); const bts::orderman::BookSide& book_depth = book.side(book_side); for (size_t level = 0; level < n_levels; level++){ - const md::PriceSize& level_price_qty = book_depth[level]; - double level_price = level_price_qty.price(); - price_qty = Quantity(level_price_qty.size()); + const md::PriceSize& level_price_qty = book_depth[level]; + double level_price = level_price_qty.price(); + auto price_qty = Quantity(level_price_qty.size()); + if(securities::is_better(book_side,target_price,Price(level_price)) || + price_qty.value()==0) + break; cumm_qty = Quantity(cumm_qty.value() + price_qty.value()); - if (bts::securities::test_price_equality (level_price, - target_price.value(), - tick_size)) - return true; - } - price_qty = Quantity(0); cumm_qty = Quantity(0); - return false; + } + return cumm_qty.value()!=0; + } + // returns true if the price (3rd arg) + // crosses into the side (2nd arg) of the + // book (1rst arg). if the side of the + // book is empty, the function returns + // false. + static bool crosses_book(const Book& book, + api::Side side, + Price price, + double tick_size){ + const auto& book_side = book.side(side); + return (side==api::SIDE_BUY && book_side[0].size() > 0 && + securities::gr_than_eq(book_side[0].price(),price.value(),tick_size)) || + (side==api::SIDE_SELL && book_side[0].size() > 0 && + securities::gr_than_eq(price.value(),book_side[0].price(),tick_size)); } // find the top of the synthetic book static Price top_of_book_price (const ISpreaderManager&, @@ -394,8 +406,8 @@ public: Price& out_price){ out_price = current_price; api::Side book_side = invert_side(hedge_side); - Quantity price_level_qty, cumm_qty; - bool find_qty_at_price = find_qty_at_price_level (book, book_side, current_price, tick_size, price_level_qty, cumm_qty); + Quantity cumm_qty; + bool find_qty_at_price = find_qty_upto_price_level (book, book_side, current_price, tick_size, cumm_qty); if (find_qty_at_price){ Quantity qty_threshold = _quantity_threshold(params.quantity_threshold(), current_qty); if (cumm_qty.value() > qty_threshold.value()){ @@ -419,8 +431,8 @@ public: Price& out_price){ out_price = current_price; api::Side book_side = invert_side(hedge_side); - Quantity price_level_qty, cumm_qty; - bool find_qty_at_price = find_qty_at_price_level (book, book_side, current_price, tick_size, price_level_qty, cumm_qty); + Quantity cumm_qty; + bool find_qty_at_price = find_qty_upto_price_level (book, book_side, current_price, tick_size, cumm_qty); if (find_qty_at_price){ Quantity qty_threshold = _quantity_threshold(params.quantity_threshold(), current_qty); if (cumm_qty.value() < qty_threshold.value()){ @@ -623,18 +635,16 @@ public: const Book& book, Price& price, Quantity& quantity){ - Quantity out_qty(0), out_cum_qty(0); + Quantity out_cum_qty(0); if(leg.trading_side()==api::Side::SIDE_BUY) - find_qty_at_price_level(book,api::Side::SIDE_SELL, + find_qty_upto_price_level(book,api::Side::SIDE_SELL, price, leg.tick_size(), - out_qty, out_cum_qty); else if(leg.trading_side()==api::Side::SIDE_SELL) - find_qty_at_price_level(book,api::Side::SIDE_BUY, + find_qty_upto_price_level(book,api::Side::SIDE_BUY, price, leg.tick_size(), - out_qty, out_cum_qty); quantity = Quantity(std::min(quantity.value(),out_cum_qty.value())); } diff --git a/src/lib/orderman/orders/spreader_orders/spreader/external_interfacing/SpreaderOrderBuilder.cpp b/src/lib/orderman/orders/spreader_orders/spreader/external_interfacing/SpreaderOrderBuilder.cpp index 4a4fda9d7..b746a9178 100644 --- a/src/lib/orderman/orders/spreader_orders/spreader/external_interfacing/SpreaderOrderBuilder.cpp +++ b/src/lib/orderman/orders/spreader_orders/spreader/external_interfacing/SpreaderOrderBuilder.cpp @@ -11,7 +11,7 @@ SpreaderOrderBuilder::SpreaderOrderBuilder (bts::orderman::OrderKey parent_key, _is_live(spreader_pao_services.is_live()){ if (_is_live){ LOG(OrderMan, Info, "SpreaderOrderBuilder.cons parent_key: {} sec_key: {}", parent_key, order_def.security_key()); - _real_order_builder = bts::orderman::OrderBuilder(parent_key, order_def, spreader_pao_services.pre_services(), reserve_sz); + _real_order_builder = bts::orderman::OrderBuilder(parent_key, order_def, spreader_pao_services.pre_services().order_factory, reserve_sz); } } SpreaderOrderBuilder::SpreaderOrderBuilder(SpreaderOrderBuilder&&) @@ -33,4 +33,4 @@ void SpreaderOrderBuilder::activate(SpreaderOrderServices& order_services){ if (_is_live) _real_order_builder.activate(order_services.order_services()); } -}} \ No newline at end of file +}} diff --git a/src/lib/orderman/orders/spreader_orders/spreader/external_interfacing/SpreaderOrderBuilder.h b/src/lib/orderman/orders/spreader_orders/spreader/external_interfacing/SpreaderOrderBuilder.h index a80fd728c..771bbf121 100644 --- a/src/lib/orderman/orders/spreader_orders/spreader/external_interfacing/SpreaderOrderBuilder.h +++ b/src/lib/orderman/orders/spreader_orders/spreader/external_interfacing/SpreaderOrderBuilder.h @@ -55,9 +55,9 @@ public: SpreaderOrderServices (bts::orderman::OrderServices* order_services); bts::orderman::OrderServices& order_services(); void report_state(const api::orderman::OrderState &state); - trace::ScopedPerfLogEntry log_scope(trace::CorID cid, const char *entry_kind, + trace::ScopedPerfLogEntry log_scope(const char *entry_kind, uint64_t uint64_1 = 0,const char *txt_1 = "",uint32_t uint32_1 = 0); - void log(trace::CorID cid, const char *entry_kind, + void log(const char *entry_kind, uint64_t uint64_1 = 0,const char *txt_1 = "",uint32_t uint32_1 = 0); bool is_live(); }; diff --git a/src/lib/orderman/orders/spreader_orders/spreader/external_interfacing/SpreaderOrderServices.cpp b/src/lib/orderman/orders/spreader_orders/spreader/external_interfacing/SpreaderOrderServices.cpp index b9c26a0d5..c4da34827 100644 --- a/src/lib/orderman/orders/spreader_orders/spreader/external_interfacing/SpreaderOrderServices.cpp +++ b/src/lib/orderman/orders/spreader_orders/spreader/external_interfacing/SpreaderOrderServices.cpp @@ -16,24 +16,22 @@ void SpreaderOrderServices::report_state(const api::orderman::OrderState &state) if (is_live()) _order_services->report_state(state); } -trace::ScopedPerfLogEntry SpreaderOrderServices::log_scope(trace::CorID cid, - const char *entry_kind, +trace::ScopedPerfLogEntry SpreaderOrderServices::log_scope(const char *entry_kind, uint64_t uint64_1, const char *txt_1, uint32_t uint32_1){ if(_is_live) - return _order_services->log_scope(cid,entry_kind,uint64_1,txt_1,uint32_1); + return _order_services->log_scope(entry_kind,uint64_1,txt_1,uint32_1); else return trace::ScopedPerfLogEntry (); } -void SpreaderOrderServices::log(trace::CorID cid, - const char *entry_kind, +void SpreaderOrderServices::log(const char *entry_kind, uint64_t uint64_1, const char *txt_1, uint32_t uint32_1) { if(_is_live) - _order_services->log(cid, entry_kind, uint64_1, txt_1, uint32_1); + _order_services->log(entry_kind, uint64_1, txt_1, uint32_1); } bool SpreaderOrderServices::is_live() {return _is_live;} diff --git a/src/lib/orderman/orders/spreader_orders/spreader/external_interfacing/SpreaderPreActivationOrderServices.cpp b/src/lib/orderman/orders/spreader_orders/spreader/external_interfacing/SpreaderPreActivationOrderServices.cpp index e4ba33b7c..d0e546c28 100644 --- a/src/lib/orderman/orders/spreader_orders/spreader/external_interfacing/SpreaderPreActivationOrderServices.cpp +++ b/src/lib/orderman/orders/spreader_orders/spreader/external_interfacing/SpreaderPreActivationOrderServices.cpp @@ -3,27 +3,31 @@ namespace bts{ namespace orderman{ -SpreaderPreActivationOrderServices::SpreaderPreActivationOrderServices (const bts::orderman::PreActivationOrderServices* pre_services) +SpreaderPreActivationOrderServices::SpreaderPreActivationOrderServices +(const bts::orderman::PreActivationOrderServices* pre_services) : _pre_services(pre_services), _test_only_pre_services (nullptr) {} -SpreaderPreActivationOrderServices::SpreaderPreActivationOrderServices (TestOnlySpreaderPreActivationOrderServices* test_only_pre_services) +SpreaderPreActivationOrderServices::SpreaderPreActivationOrderServices +(TestOnlySpreaderPreActivationOrderServices* test_only_pre_services) : _pre_services(nullptr), _test_only_pre_services (test_only_pre_services) {} -const bts::api::Security* SpreaderPreActivationOrderServices::resolve (SecurityKey key) const{ +const bts::api::Security* SpreaderPreActivationOrderServices::resolve ( + SecurityKey key) const{ if (is_live ()) return _pre_services->sec_db.resolve(key); else return _test_only_pre_services->resolve(key); } -bool SpreaderPreActivationOrderServices::is_live () const{ +bool SpreaderPreActivationOrderServices::is_live() const{ return _pre_services != nullptr; } -const bts::orderman::PreActivationOrderServices& SpreaderPreActivationOrderServices::pre_services() const{ - bts_assert(is_live ()); +const bts::orderman::PreActivationOrderServices& +SpreaderPreActivationOrderServices::pre_services() const{ + bts_assert(is_live()); return *_pre_services; } diff --git a/src/lib/orderman/orders/spreader_orders/spreader/hedger/HedgerManager.h b/src/lib/orderman/orders/spreader_orders/spreader/hedger/HedgerManager.h index 6827ac7d2..c54821ba5 100644 --- a/src/lib/orderman/orders/spreader_orders/spreader/hedger/HedgerManager.h +++ b/src/lib/orderman/orders/spreader_orders/spreader/hedger/HedgerManager.h @@ -50,9 +50,9 @@ public: return nullptr; } // udpates all the hedgers with the book update - void update_book (const Book& book, trace::CorID& cid){ + void update_book (const Book& book){ for (SingleFillHedger& hedger : _hedgers) - hedger.on_book(book, cid); + hedger.on_book(book); } // udpates all the hedgers with the book update void update_time(const bts::TimeStamp& ts){ @@ -105,4 +105,4 @@ public: } }; -}} \ No newline at end of file +}} diff --git a/src/lib/orderman/orders/spreader_orders/spreader/hedger/IHedgerStateWorker.h b/src/lib/orderman/orders/spreader_orders/spreader/hedger/IHedgerStateWorker.h index 97b831af9..c9d61af95 100644 --- a/src/lib/orderman/orders/spreader_orders/spreader/hedger/IHedgerStateWorker.h +++ b/src/lib/orderman/orders/spreader_orders/spreader/hedger/IHedgerStateWorker.h @@ -22,13 +22,12 @@ public: virtual const std::string state_text () const = 0; // called once and only once, before any other calls. virtual void init (Price price, - Quantity quantity, - const trace::CorID&) = 0; + Quantity quantity) = 0; // called only when this hedger's order is updated virtual void on_order_update (const SpreaderChildOrderState& order_update) = 0; // called only when the security that the hedger is working on // has a market data update - virtual void on_book (const bts::orderman::Book& book,trace::CorID &) = 0; + virtual void on_book (const bts::orderman::Book& book) = 0; // when the spreader wants the hedger to cancel its order virtual void cancel() = 0; // on terminate, the hedger should simply go to its end state diff --git a/src/lib/orderman/orders/spreader_orders/spreader/hedger/hedger_states/HedgerEndStateWorker.cpp b/src/lib/orderman/orders/spreader_orders/spreader/hedger/hedger_states/HedgerEndStateWorker.cpp index ffaecd75c..f1836203c 100644 --- a/src/lib/orderman/orders/spreader_orders/spreader/hedger/hedger_states/HedgerEndStateWorker.cpp +++ b/src/lib/orderman/orders/spreader_orders/spreader/hedger/hedger_states/HedgerEndStateWorker.cpp @@ -14,14 +14,13 @@ void HedgerEndStateWorker::on_transition (){ } void HedgerEndStateWorker::init (Price, - Quantity, - const trace::CorID&){ + Quantity){ bts_assert_msg (false, "HedgerEndStateWorker::init illegal operation"); } void HedgerEndStateWorker::on_order_update(const SpreaderChildOrderState&){ } -void HedgerEndStateWorker::on_book(const Book&, - trace::CorID &){ +void HedgerEndStateWorker::on_book(const bts::orderman::Book&){ + } void HedgerEndStateWorker::cancel(){ } diff --git a/src/lib/orderman/orders/spreader_orders/spreader/hedger/hedger_states/HedgerEndStateWorker.h b/src/lib/orderman/orders/spreader_orders/spreader/hedger/hedger_states/HedgerEndStateWorker.h index aca2f01ee..a213fbdd6 100644 --- a/src/lib/orderman/orders/spreader_orders/spreader/hedger/hedger_states/HedgerEndStateWorker.h +++ b/src/lib/orderman/orders/spreader_orders/spreader/hedger/hedger_states/HedgerEndStateWorker.h @@ -23,9 +23,9 @@ public: void on_transition () override; HedgerState state () const override {return HedgerState::END;} const std::string state_text () const override {return "END";} - void init (Price price,Quantity quantity,const trace::CorID& trace) override; + void init (Price price,Quantity quantity) override; void on_order_update (const SpreaderChildOrderState& order_update) override; - void on_book (const Book& book,trace::CorID &) override; + void on_book (const bts::orderman::Book& book) override; void cancel() override; void terminate() override; void on_time(const TimeStamp&) override; diff --git a/src/lib/orderman/orders/spreader_orders/spreader/hedger/hedger_states/HedgerStartStateWorker.cpp b/src/lib/orderman/orders/spreader_orders/spreader/hedger/hedger_states/HedgerStartStateWorker.cpp index fd62f0ae9..1655a3042 100644 --- a/src/lib/orderman/orders/spreader_orders/spreader/hedger/hedger_states/HedgerStartStateWorker.cpp +++ b/src/lib/orderman/orders/spreader_orders/spreader/hedger/hedger_states/HedgerStartStateWorker.cpp @@ -14,11 +14,10 @@ void HedgerStartStateWorker::on_transition (){ } void HedgerStartStateWorker::init (Price price, - Quantity quantity, - const trace::CorID& trace){ + Quantity quantity){ _hedger->_price_quantity_state.re_init(price,quantity); if(quantity.value() > 0){ - _hedger->_place_order (price, quantity,trace); + _hedger->_place_order (price, quantity); _hedger->transform_to_WAITING_FOR_FIRST_ACK (); } } @@ -26,8 +25,8 @@ void HedgerStartStateWorker::on_order_update(const SpreaderChildOrderState&){ bts_assert_msg (false, "HedgerStartStateWorker::on_order_update " "illegal operation"); } -void HedgerStartStateWorker::on_book(const Book&, - trace::CorID &){ +void HedgerStartStateWorker::on_book(const bts::orderman::Book&){ + } void HedgerStartStateWorker::cancel(){ _hedger->transform_to_END (); diff --git a/src/lib/orderman/orders/spreader_orders/spreader/hedger/hedger_states/HedgerStartStateWorker.h b/src/lib/orderman/orders/spreader_orders/spreader/hedger/hedger_states/HedgerStartStateWorker.h index a1329fbb5..5d577119e 100644 --- a/src/lib/orderman/orders/spreader_orders/spreader/hedger/hedger_states/HedgerStartStateWorker.h +++ b/src/lib/orderman/orders/spreader_orders/spreader/hedger/hedger_states/HedgerStartStateWorker.h @@ -21,9 +21,9 @@ public: void on_transition () override; HedgerState state () const override {return HedgerState::START;} const std::string state_text () const override {return "START";} - void init (Price price,Quantity quantity,const trace::CorID&) override; + void init (Price price,Quantity quantity) override; void on_order_update (const SpreaderChildOrderState& order_update) override; - void on_book (const Book& book,trace::CorID &) override; + void on_book (const bts::orderman::Book& book) override; void cancel() override; void terminate() override; void on_time(const TimeStamp&) override; diff --git a/src/lib/orderman/orders/spreader_orders/spreader/hedger/hedger_states/HedgerWaitingForCancelAckStateWorker.cpp b/src/lib/orderman/orders/spreader_orders/spreader/hedger/hedger_states/HedgerWaitingForCancelAckStateWorker.cpp index e2cc95077..f5f96b6fc 100644 --- a/src/lib/orderman/orders/spreader_orders/spreader/hedger/hedger_states/HedgerWaitingForCancelAckStateWorker.cpp +++ b/src/lib/orderman/orders/spreader_orders/spreader/hedger/hedger_states/HedgerWaitingForCancelAckStateWorker.cpp @@ -6,8 +6,7 @@ namespace bts{ namespace orderman{ void HedgerWaitingForCancelAckStateWorker::init (Price, - Quantity, - const trace::CorID&){ + Quantity){ bts_assert_msg (false, "HedgerWaitingForCancelAckStateWorker::init " "illegal operation"); } @@ -17,7 +16,7 @@ void HedgerWaitingForCancelAckStateWorker::on_order_update(const SpreaderChildOr if (order_update.terminal_status()) _hedger->transform_to_END (); } -void HedgerWaitingForCancelAckStateWorker::on_book(const bts::orderman::Book&,trace::CorID &){ +void HedgerWaitingForCancelAckStateWorker::on_book(const bts::orderman::Book&){ } void HedgerWaitingForCancelAckStateWorker::cancel(){ } diff --git a/src/lib/orderman/orders/spreader_orders/spreader/hedger/hedger_states/HedgerWaitingForCancelAckStateWorker.h b/src/lib/orderman/orders/spreader_orders/spreader/hedger/hedger_states/HedgerWaitingForCancelAckStateWorker.h index 49190e7d0..f4576cb4d 100644 --- a/src/lib/orderman/orders/spreader_orders/spreader/hedger/hedger_states/HedgerWaitingForCancelAckStateWorker.h +++ b/src/lib/orderman/orders/spreader_orders/spreader/hedger/hedger_states/HedgerWaitingForCancelAckStateWorker.h @@ -25,9 +25,9 @@ public: const std::string state_text () const override { return "WAITING_FOR_CANCEL_ACK"; } - void init (Price price,Quantity quantity,const trace::CorID&) override; + void init (Price price,Quantity quantity) override; void on_order_update (const SpreaderChildOrderState& order_update) override; - void on_book (const bts::orderman::Book& book,trace::CorID &) override; + void on_book (const bts::orderman::Book& book) override; void cancel() override; void terminate() override; void on_time(const TimeStamp&) override; diff --git a/src/lib/orderman/orders/spreader_orders/spreader/hedger/hedger_states/HedgerWaitingForFirstAckCancelledStateWorker.cpp b/src/lib/orderman/orders/spreader_orders/spreader/hedger/hedger_states/HedgerWaitingForFirstAckCancelledStateWorker.cpp index b4b059b49..4965b37f2 100644 --- a/src/lib/orderman/orders/spreader_orders/spreader/hedger/hedger_states/HedgerWaitingForFirstAckCancelledStateWorker.cpp +++ b/src/lib/orderman/orders/spreader_orders/spreader/hedger/hedger_states/HedgerWaitingForFirstAckCancelledStateWorker.cpp @@ -8,8 +8,7 @@ namespace orderman{ void HedgerWaitingForFirstAckCancelledStateWorker::init( Price, - Quantity, - const trace::CorID&){ + Quantity){ bts_assert_msg (false, "HedgerWaitingForFirstAckCancelledStateWorker::init " "illegal operation"); } @@ -27,8 +26,8 @@ void HedgerWaitingForFirstAckCancelledStateWorker::on_order_update( _hedger->transform_to_WAITING_FOR_CANCEL_ACK (); } } -void HedgerWaitingForFirstAckCancelledStateWorker::on_book(const Book&, - trace::CorID &){ +void HedgerWaitingForFirstAckCancelledStateWorker::on_book(const bts::orderman::Book&){ + } void HedgerWaitingForFirstAckCancelledStateWorker::cancel(){ } @@ -37,4 +36,4 @@ void HedgerWaitingForFirstAckCancelledStateWorker::terminate(){ } void HedgerWaitingForFirstAckCancelledStateWorker::on_time(const TimeStamp&){ } -}} \ No newline at end of file +}} diff --git a/src/lib/orderman/orders/spreader_orders/spreader/hedger/hedger_states/HedgerWaitingForFirstAckCancelledStateWorker.h b/src/lib/orderman/orders/spreader_orders/spreader/hedger/hedger_states/HedgerWaitingForFirstAckCancelledStateWorker.h index 5bb7d0652..0365202b6 100644 --- a/src/lib/orderman/orders/spreader_orders/spreader/hedger/hedger_states/HedgerWaitingForFirstAckCancelledStateWorker.h +++ b/src/lib/orderman/orders/spreader_orders/spreader/hedger/hedger_states/HedgerWaitingForFirstAckCancelledStateWorker.h @@ -25,9 +25,9 @@ public: const std::string state_text () const override { return "WAITING_FOR_FIRST_ACK_CANCELLED"; } - void init (Price price,Quantity quantity,const trace::CorID& trace) override; + void init (Price price,Quantity quantity) override; void on_order_update (const SpreaderChildOrderState& order_update) override; - void on_book (const Book& book,trace::CorID &) override; + void on_book (const bts::orderman::Book& book) override; void cancel() override; void terminate() override; void on_time(const TimeStamp&) override; diff --git a/src/lib/orderman/orders/spreader_orders/spreader/hedger/hedger_states/HedgerWaitingForFirstAckStateWorker.cpp b/src/lib/orderman/orders/spreader_orders/spreader/hedger/hedger_states/HedgerWaitingForFirstAckStateWorker.cpp index 9de455b87..e40134aee 100644 --- a/src/lib/orderman/orders/spreader_orders/spreader/hedger/hedger_states/HedgerWaitingForFirstAckStateWorker.cpp +++ b/src/lib/orderman/orders/spreader_orders/spreader/hedger/hedger_states/HedgerWaitingForFirstAckStateWorker.cpp @@ -5,8 +5,7 @@ namespace bts{ namespace orderman{ void HedgerWaitingForFirstAckStateWorker::init (Price, - Quantity, - const trace::CorID&){ + Quantity){ bts_assert_msg (false, "HedgerWaitingForFirstAckStateWorker::init " "illegal operation"); } @@ -21,8 +20,7 @@ void HedgerWaitingForFirstAckStateWorker::on_order_update( // this means the first ack _hedger->transform_to_WORKING (); } -void HedgerWaitingForFirstAckStateWorker::on_book(const Book&, - trace::CorID &){ +void HedgerWaitingForFirstAckStateWorker::on_book(const bts::orderman::Book&){ } void HedgerWaitingForFirstAckStateWorker::cancel(){ _hedger->transform_to_WAITING_FOR_FIRST_ACK_CANCELLED (); diff --git a/src/lib/orderman/orders/spreader_orders/spreader/hedger/hedger_states/HedgerWaitingForFirstAckStateWorker.h b/src/lib/orderman/orders/spreader_orders/spreader/hedger/hedger_states/HedgerWaitingForFirstAckStateWorker.h index 385f186af..f854ed800 100644 --- a/src/lib/orderman/orders/spreader_orders/spreader/hedger/hedger_states/HedgerWaitingForFirstAckStateWorker.h +++ b/src/lib/orderman/orders/spreader_orders/spreader/hedger/hedger_states/HedgerWaitingForFirstAckStateWorker.h @@ -26,9 +26,9 @@ public: const std::string state_text () const override { return "WAITING_FOR_FIRST_ACK"; } - void init (Price price,Quantity quantity,const trace::CorID& trace) override; + void init (Price price,Quantity quantity) override; void on_order_update (const SpreaderChildOrderState& order_update) override; - void on_book (const Book& book,trace::CorID &) override; + void on_book (const bts::orderman::Book& book) override; void cancel() override; void terminate() override; void on_time(const TimeStamp&) override; diff --git a/src/lib/orderman/orders/spreader_orders/spreader/hedger/hedger_states/HedgerWorkingStateWorker.cpp b/src/lib/orderman/orders/spreader_orders/spreader/hedger/hedger_states/HedgerWorkingStateWorker.cpp index d4bbe57c5..e771b2836 100644 --- a/src/lib/orderman/orders/spreader_orders/spreader/hedger/hedger_states/HedgerWorkingStateWorker.cpp +++ b/src/lib/orderman/orders/spreader_orders/spreader/hedger/hedger_states/HedgerWorkingStateWorker.cpp @@ -10,8 +10,7 @@ void HedgerWorkingStateWorker::on_transition(){ _order_touch_time = _hedger->_current_time(); } void HedgerWorkingStateWorker::init(Price, - Quantity, - const trace::CorID&){ + Quantity){ bts_assert_msg (false, "HedgerWorkingStateWorker::init illegal operation"); } void HedgerWorkingStateWorker::on_order_update( @@ -22,8 +21,7 @@ void HedgerWorkingStateWorker::on_order_update( if (order_update.terminal_status()) _hedger->transform_to_END (); } -void HedgerWorkingStateWorker::on_book(const Book&, - trace::CorID &){ +void HedgerWorkingStateWorker::on_book(const bts::orderman::Book&){ double new_price; if (SpreaderUtils::post_hedge_market_based_price_action( _hedger->_child_order_state.out_price().value(), diff --git a/src/lib/orderman/orders/spreader_orders/spreader/hedger/hedger_states/HedgerWorkingStateWorker.h b/src/lib/orderman/orders/spreader_orders/spreader/hedger/hedger_states/HedgerWorkingStateWorker.h index 69de3a1b4..36ca3be85 100644 --- a/src/lib/orderman/orders/spreader_orders/spreader/hedger/hedger_states/HedgerWorkingStateWorker.h +++ b/src/lib/orderman/orders/spreader_orders/spreader/hedger/hedger_states/HedgerWorkingStateWorker.h @@ -23,9 +23,9 @@ public: void on_transition () override; HedgerState state () const override {return HedgerState::WORKING;} const std::string state_text () const override {return "WORKING";} - void init (Price price,Quantity quantity,const trace::CorID& trace) override; + void init (Price price,Quantity quantity) override; void on_order_update (const SpreaderChildOrderState& order_update) override; - void on_book (const Book& book,trace::CorID &) override; + void on_book (const bts::orderman::Book& book) override; void cancel() override; void terminate() override; void on_time(const TimeStamp&) override; diff --git a/src/lib/orderman/orders/spreader_orders/spreader/quoter/IQuoterStateWorker.h b/src/lib/orderman/orders/spreader_orders/spreader/quoter/IQuoterStateWorker.h index a83697af0..ab37c9576 100644 --- a/src/lib/orderman/orders/spreader_orders/spreader/quoter/IQuoterStateWorker.h +++ b/src/lib/orderman/orders/spreader_orders/spreader/quoter/IQuoterStateWorker.h @@ -26,7 +26,7 @@ public: virtual void on_order_update (const SpreaderChildOrderState& order_update) = 0; // called when any of the legs in the spread has a book update //virtual void on_book (TickToTradeCorID corid, size_t leg_id, const Book& book) = 0; - virtual void on_book (size_t, const bts::orderman::Book&,trace::CorID &) = 0; + virtual void on_book (size_t, const bts::orderman::Book&) = 0; // when the spreader wants the quoter to cancel its order virtual void cancel() = 0; // on terminate, the quoter should simply go to its end state diff --git a/src/lib/orderman/orders/spreader_orders/spreader/quoter/quoter_states/QuoterEndStateWorker.cpp b/src/lib/orderman/orders/spreader_orders/spreader/quoter/quoter_states/QuoterEndStateWorker.cpp index 24c417c8f..f0e50057c 100644 --- a/src/lib/orderman/orders/spreader_orders/spreader/quoter/quoter_states/QuoterEndStateWorker.cpp +++ b/src/lib/orderman/orders/spreader_orders/spreader/quoter/quoter_states/QuoterEndStateWorker.cpp @@ -29,7 +29,7 @@ void QuoterEndStateWorker::one_time_activate (Price, Quantity){ void QuoterEndStateWorker::on_order_update (const SpreaderChildOrderState&) {} void QuoterEndStateWorker::on_book (size_t, - const bts::orderman::Book&,trace::CorID &) + const bts::orderman::Book&) {} void QuoterEndStateWorker::cancel() {} diff --git a/src/lib/orderman/orders/spreader_orders/spreader/quoter/quoter_states/QuoterEndStateWorker.h b/src/lib/orderman/orders/spreader_orders/spreader/quoter/quoter_states/QuoterEndStateWorker.h index 2a52ee1a6..adb35e726 100644 --- a/src/lib/orderman/orders/spreader_orders/spreader/quoter/quoter_states/QuoterEndStateWorker.h +++ b/src/lib/orderman/orders/spreader_orders/spreader/quoter/quoter_states/QuoterEndStateWorker.h @@ -25,7 +25,7 @@ public: virtual void on_transition () override; void one_time_activate (Price, Quantity) override; void on_order_update (const SpreaderChildOrderState& order_update) override; - void on_book (size_t leg_id, const bts::orderman::Book& book,trace::CorID &) override; + void on_book (size_t leg_id, const bts::orderman::Book& book) override; void cancel() override; void terminate() override; void on_time(const TimeStamp& ts) override; diff --git a/src/lib/orderman/orders/spreader_orders/spreader/quoter/quoter_states/QuoterStartStateWorker.cpp b/src/lib/orderman/orders/spreader_orders/spreader/quoter/quoter_states/QuoterStartStateWorker.cpp index 38d3b9dea..f99df82d8 100644 --- a/src/lib/orderman/orders/spreader_orders/spreader/quoter/quoter_states/QuoterStartStateWorker.cpp +++ b/src/lib/orderman/orders/spreader_orders/spreader/quoter/quoter_states/QuoterStartStateWorker.cpp @@ -24,7 +24,7 @@ void QuoterStartStateWorker::on_order_update (const SpreaderChildOrderState&){ bts_assert_msg (false, "QuoterStartStateWorker::on_order_update is an illegal operation, nothing can happen before one_time_activate"); } void QuoterStartStateWorker::on_book (size_t, - const bts::orderman::Book&,trace::CorID &){ + const bts::orderman::Book&){ } void QuoterStartStateWorker::cancel(){ // since no order has been sent for this leg, diff --git a/src/lib/orderman/orders/spreader_orders/spreader/quoter/quoter_states/QuoterStartStateWorker.h b/src/lib/orderman/orders/spreader_orders/spreader/quoter/quoter_states/QuoterStartStateWorker.h index dae5ada02..4699dc319 100644 --- a/src/lib/orderman/orders/spreader_orders/spreader/quoter/quoter_states/QuoterStartStateWorker.h +++ b/src/lib/orderman/orders/spreader_orders/spreader/quoter/quoter_states/QuoterStartStateWorker.h @@ -23,7 +23,7 @@ public: virtual void on_transition () override {} void one_time_activate (Price, Quantity) override; void on_order_update (const SpreaderChildOrderState& order_update) override; - void on_book (size_t leg_id, const bts::orderman::Book& book,trace::CorID &) override; + void on_book (size_t leg_id, const bts::orderman::Book& book) override; void cancel() override; void terminate() override; void on_time(const TimeStamp& ts) override; diff --git a/src/lib/orderman/orders/spreader_orders/spreader/quoter/quoter_states/QuoterWaitingForCancelAckStateWorker.cpp b/src/lib/orderman/orders/spreader_orders/spreader/quoter/quoter_states/QuoterWaitingForCancelAckStateWorker.cpp index bf493f55f..f37e45996 100644 --- a/src/lib/orderman/orders/spreader_orders/spreader/quoter/quoter_states/QuoterWaitingForCancelAckStateWorker.cpp +++ b/src/lib/orderman/orders/spreader_orders/spreader/quoter/quoter_states/QuoterWaitingForCancelAckStateWorker.cpp @@ -20,8 +20,7 @@ void QuoterWaitingForCancelAckStateWorker::on_order_update (const SpreaderChildO _quoter->_transform_to_END (); } void QuoterWaitingForCancelAckStateWorker::on_book (size_t, - const bts::orderman::Book&, - trace::CorID &){ + const bts::orderman::Book&){ } void QuoterWaitingForCancelAckStateWorker::cancel(){ } diff --git a/src/lib/orderman/orders/spreader_orders/spreader/quoter/quoter_states/QuoterWaitingForCancelAckStateWorker.h b/src/lib/orderman/orders/spreader_orders/spreader/quoter/quoter_states/QuoterWaitingForCancelAckStateWorker.h index 9ef9d2409..5ca656321 100644 --- a/src/lib/orderman/orders/spreader_orders/spreader/quoter/quoter_states/QuoterWaitingForCancelAckStateWorker.h +++ b/src/lib/orderman/orders/spreader_orders/spreader/quoter/quoter_states/QuoterWaitingForCancelAckStateWorker.h @@ -24,7 +24,7 @@ public: virtual void on_transition () override {} void one_time_activate (Price, Quantity) override; void on_order_update (const SpreaderChildOrderState& order_update) override; - void on_book (size_t leg_id, const bts::orderman::Book& book,trace::CorID &) override; + void on_book (size_t leg_id, const bts::orderman::Book& book) override; void cancel() override; void terminate() override; void on_time(const TimeStamp& ts) override; diff --git a/src/lib/orderman/orders/spreader_orders/spreader/quoter/quoter_states/QuoterWaitingForFirstAckCancelledWorker.cpp b/src/lib/orderman/orders/spreader_orders/spreader/quoter/quoter_states/QuoterWaitingForFirstAckCancelledWorker.cpp index b674b1d3b..c18876ba4 100644 --- a/src/lib/orderman/orders/spreader_orders/spreader/quoter/quoter_states/QuoterWaitingForFirstAckCancelledWorker.cpp +++ b/src/lib/orderman/orders/spreader_orders/spreader/quoter/quoter_states/QuoterWaitingForFirstAckCancelledWorker.cpp @@ -25,7 +25,7 @@ void QuoterWaitingForFirstAckCancelledWorker::on_order_update (const SpreaderChi _quoter->_transform_to_WAITING_FOR_CANCEL_ACK (); } } -void QuoterWaitingForFirstAckCancelledWorker::on_book (size_t , const bts::orderman::Book& ,trace::CorID &) { +void QuoterWaitingForFirstAckCancelledWorker::on_book (size_t , const bts::orderman::Book& ) { } void QuoterWaitingForFirstAckCancelledWorker::cancel(){ } diff --git a/src/lib/orderman/orders/spreader_orders/spreader/quoter/quoter_states/QuoterWaitingForFirstAckCancelledWorker.h b/src/lib/orderman/orders/spreader_orders/spreader/quoter/quoter_states/QuoterWaitingForFirstAckCancelledWorker.h index 085e9b919..9b39f9f4d 100644 --- a/src/lib/orderman/orders/spreader_orders/spreader/quoter/quoter_states/QuoterWaitingForFirstAckCancelledWorker.h +++ b/src/lib/orderman/orders/spreader_orders/spreader/quoter/quoter_states/QuoterWaitingForFirstAckCancelledWorker.h @@ -30,7 +30,7 @@ public: virtual void on_transition () override {} void one_time_activate (Price, Quantity) override; void on_order_update (const SpreaderChildOrderState& order_update) override; - void on_book (size_t leg_id, const bts::orderman::Book& book,trace::CorID &) override; + void on_book (size_t leg_id, const bts::orderman::Book& book) override; void cancel() override; void terminate() override; void on_time(const TimeStamp& ts) override; diff --git a/src/lib/orderman/orders/spreader_orders/spreader/quoter/quoter_states/QuoterWaitingForFirstAckWorker.cpp b/src/lib/orderman/orders/spreader_orders/spreader/quoter/quoter_states/QuoterWaitingForFirstAckWorker.cpp index cd5e845b2..44d3bc21b 100644 --- a/src/lib/orderman/orders/spreader_orders/spreader/quoter/quoter_states/QuoterWaitingForFirstAckWorker.cpp +++ b/src/lib/orderman/orders/spreader_orders/spreader/quoter/quoter_states/QuoterWaitingForFirstAckWorker.cpp @@ -22,7 +22,7 @@ void QuoterWaitingForFirstAckWorker::on_order_update (const SpreaderChildOrderSt _quoter->_transform_to_WORKING (); } void QuoterWaitingForFirstAckWorker::on_book (size_t, - const bts::orderman::Book&,trace::CorID &){ + const bts::orderman::Book&){ _analyze_and_act(); } void QuoterWaitingForFirstAckWorker::cancel(){ diff --git a/src/lib/orderman/orders/spreader_orders/spreader/quoter/quoter_states/QuoterWaitingForFirstAckWorker.h b/src/lib/orderman/orders/spreader_orders/spreader/quoter/quoter_states/QuoterWaitingForFirstAckWorker.h index d4c8d0ed0..5515cd8ea 100644 --- a/src/lib/orderman/orders/spreader_orders/spreader/quoter/quoter_states/QuoterWaitingForFirstAckWorker.h +++ b/src/lib/orderman/orders/spreader_orders/spreader/quoter/quoter_states/QuoterWaitingForFirstAckWorker.h @@ -28,7 +28,7 @@ public: virtual void on_transition () override {} void one_time_activate (Price, Quantity) override; void on_order_update (const SpreaderChildOrderState& order_update) override; - void on_book (size_t leg_id, const bts::orderman::Book& book,trace::CorID & ) override; + void on_book (size_t leg_id, const bts::orderman::Book& book) override; void cancel() override; void terminate() override; void on_time(const TimeStamp& ts) override; diff --git a/src/lib/orderman/orders/spreader_orders/spreader/quoter/quoter_states/QuoterWaitingForIOCWorker.cpp b/src/lib/orderman/orders/spreader_orders/spreader/quoter/quoter_states/QuoterWaitingForIOCWorker.cpp index 588761444..cd182d950 100644 --- a/src/lib/orderman/orders/spreader_orders/spreader/quoter/quoter_states/QuoterWaitingForIOCWorker.cpp +++ b/src/lib/orderman/orders/spreader_orders/spreader/quoter/quoter_states/QuoterWaitingForIOCWorker.cpp @@ -24,7 +24,7 @@ void QuoterWaitingForIOCWorker::on_order_update (const SpreaderChildOrderState& } } void QuoterWaitingForIOCWorker::on_book (size_t, - const bts::orderman::Book&,trace::CorID &){ + const bts::orderman::Book&){ } void QuoterWaitingForIOCWorker::cancel(){ _quoter->_transform_to_WAITING_FOR_FIRST_ACK_CANCELLED (); diff --git a/src/lib/orderman/orders/spreader_orders/spreader/quoter/quoter_states/QuoterWaitingForIOCWorker.h b/src/lib/orderman/orders/spreader_orders/spreader/quoter/quoter_states/QuoterWaitingForIOCWorker.h index 69ba40109..7c77266e5 100644 --- a/src/lib/orderman/orders/spreader_orders/spreader/quoter/quoter_states/QuoterWaitingForIOCWorker.h +++ b/src/lib/orderman/orders/spreader_orders/spreader/quoter/quoter_states/QuoterWaitingForIOCWorker.h @@ -31,7 +31,7 @@ public: void one_time_activate (Price, Quantity) override; void on_order_update (const SpreaderChildOrderState& order_update) override; void on_book (size_t leg_id, - const bts::orderman::Book& book,trace::CorID &) override; + const bts::orderman::Book& book) override; void cancel() override; void terminate() override; void on_time(const TimeStamp& ts) override; diff --git a/src/lib/orderman/orders/spreader_orders/spreader/quoter/quoter_states/QuoterWaitingForSizeStateWorker.cpp b/src/lib/orderman/orders/spreader_orders/spreader/quoter/quoter_states/QuoterWaitingForSizeStateWorker.cpp index b5588cd95..d1ec2af21 100644 --- a/src/lib/orderman/orders/spreader_orders/spreader/quoter/quoter_states/QuoterWaitingForSizeStateWorker.cpp +++ b/src/lib/orderman/orders/spreader_orders/spreader/quoter/quoter_states/QuoterWaitingForSizeStateWorker.cpp @@ -19,9 +19,8 @@ void QuoterWaitingForSizeStateWorker::on_order_update (const SpreaderChildOrderS bts_assert_msg (false, "QuoterWaitingForSizeStateWorker::on_order_update " "is an illegal operation"); } -void QuoterWaitingForSizeStateWorker::on_book (size_t, - const Book&,trace::CorID &trace){ - _longpath_analyze_and_act (trace); +void QuoterWaitingForSizeStateWorker::on_book (size_t, const bts::orderman::Book& ){ + _longpath_analyze_and_act (); } void QuoterWaitingForSizeStateWorker::cancel(){ // since no order has been sent for this leg, cancel just takes @@ -45,10 +44,6 @@ void QuoterWaitingForSizeStateWorker::update_spreader_order (Price price, _longpath_analyze_and_act (); } void QuoterWaitingForSizeStateWorker::_longpath_analyze_and_act(){ - trace::CorID trace; - _longpath_analyze_and_act(trace); -} -void QuoterWaitingForSizeStateWorker::_longpath_analyze_and_act(trace::CorID &){ if (_quoter->_price_quantity_state.target_reached()){ LOG(OrderMan, Info, "QuoterWaitingForSizeStateWorker key:{} " "target reached, transforming to end", @@ -65,7 +60,7 @@ void QuoterWaitingForSizeStateWorker::_longpath_analyze_and_act(trace::CorID &){ "key:{} price:{} quantity:{}", _quoter->_key(), out_price, out_quantity); // this is the only place where a quoter order is entered - _quoter->_place_order(out_price, out_quantity, trace::CorID {}); + _quoter->_place_order(out_price, out_quantity); if(_quoter->_hidden_order) _quoter->_transform_to_WAITING_FOR_IOC(); else _quoter->_transform_to_WAITING_FOR_FIRST_ACK (); } diff --git a/src/lib/orderman/orders/spreader_orders/spreader/quoter/quoter_states/QuoterWaitingForSizeStateWorker.h b/src/lib/orderman/orders/spreader_orders/spreader/quoter/quoter_states/QuoterWaitingForSizeStateWorker.h index 5cbad6abf..8f866e90f 100644 --- a/src/lib/orderman/orders/spreader_orders/spreader/quoter/quoter_states/QuoterWaitingForSizeStateWorker.h +++ b/src/lib/orderman/orders/spreader_orders/spreader/quoter/quoter_states/QuoterWaitingForSizeStateWorker.h @@ -30,7 +30,7 @@ public: virtual void on_transition () override {} void one_time_activate (Price, Quantity) override; void on_order_update (const SpreaderChildOrderState& order_update) override; - void on_book (size_t leg_id, const bts::orderman::Book& book,trace::CorID &) override; + void on_book (size_t leg_id, const bts::orderman::Book& book) override; void cancel() override; void terminate() override; void on_time(const TimeStamp& ts) override; @@ -41,6 +41,5 @@ private: // if it has. otherwise computes the price, qty and if // its valid, places an order goes to waiting_for_first_ack void _longpath_analyze_and_act (); - void _longpath_analyze_and_act (trace::CorID &); }; }} diff --git a/src/lib/orderman/orders/spreader_orders/spreader/quoter/quoter_states/QuoterWorkingStateWorker.cpp b/src/lib/orderman/orders/spreader_orders/spreader/quoter/quoter_states/QuoterWorkingStateWorker.cpp index ddc8246d6..14c5d30f4 100644 --- a/src/lib/orderman/orders/spreader_orders/spreader/quoter/quoter_states/QuoterWorkingStateWorker.cpp +++ b/src/lib/orderman/orders/spreader_orders/spreader/quoter/quoter_states/QuoterWorkingStateWorker.cpp @@ -17,9 +17,7 @@ void QuoterWorkingStateWorker::on_transition (){ // waiting for the ack, things could have changed (namely // fills in other legs, books, order qty change), hence // we analyze and potentially modify/cxl immediatly - trace::CorID ack_message_trace_id= - _quoter->_child_order_state.last_update_trace(); - _longpath_analyze_and_act (ack_message_trace_id); + _longpath_analyze_and_act (); } void QuoterWorkingStateWorker::one_time_activate (Price, Quantity){ @@ -27,16 +25,14 @@ void QuoterWorkingStateWorker::one_time_activate (Price, } void QuoterWorkingStateWorker::on_order_update (const SpreaderChildOrderState& u){ bts_assert (u.acknowledged()); - trace::CorID ack_message_trace_id=u.last_update_trace(); if (u.terminal_status()) _quoter->_transform_to_END (); else - _longpath_analyze_and_act (ack_message_trace_id); + _longpath_analyze_and_act (); } void QuoterWorkingStateWorker::on_book (size_t, - const bts::orderman::Book&, - trace::CorID &trace){ - _longpath_analyze_and_act (trace); + const bts::orderman::Book&){ + _longpath_analyze_and_act (); } void QuoterWorkingStateWorker::cancel(){ _quoter->_cancel_order(); @@ -58,11 +54,6 @@ void QuoterWorkingStateWorker::update_spreader_order (Price price, _longpath_analyze_and_act (); } void QuoterWorkingStateWorker::_longpath_analyze_and_act () -{ - trace::CorID trace; - _longpath_analyze_and_act(trace); -} -void QuoterWorkingStateWorker::_longpath_analyze_and_act (trace::CorID &trace) { if (_quoter->_price_quantity_state.target_reached()){ // this could happen if @@ -86,7 +77,7 @@ void QuoterWorkingStateWorker::_longpath_analyze_and_act (trace::CorID &trace) if (order_quantity.value() != _quoter->_price_quantity_state.out_quantity().value()) // this is a size change, size changes always go through regardless of the // quoting parameters - _modify_order (computed_price, order_quantity,trace); + _modify_order (computed_price, order_quantity); else{ bool reprice = true; if (_quoter->_this_leg_data.leg_params().quote_params().has_quote_mute_zone()) @@ -94,18 +85,18 @@ void QuoterWorkingStateWorker::_longpath_analyze_and_act (trace::CorID &trace) _quoter->_this_leg_data.tick_size(), _quoter->_this_leg_data.leg_params().quote_params().quote_mute_zone()); reprice=reprice && !(_quoter->_spreader.in_cache_warming_cycle()); if (reprice) - _modify_order (computed_price, order_quantity,trace); + _modify_order (computed_price, order_quantity); } } } } -void QuoterWorkingStateWorker::_modify_order (Price price, Quantity quantity,trace::CorID &trace ){ +void QuoterWorkingStateWorker::_modify_order (Price price, Quantity quantity){ bool same_price_qty = _quoter->_price_quantity_state.out_quantity() == quantity && bts::securities::test_price_equality(_quoter->_price_quantity_state.out_price().value(), price.value(), _quoter->_this_leg_data.tick_size()); if (!same_price_qty){ _quoter->_commit_drivers (price); - _quoter->_modify_order(price, quantity,trace); + _quoter->_modify_order(price, quantity); } } }} diff --git a/src/lib/orderman/orders/spreader_orders/spreader/quoter/quoter_states/QuoterWorkingStateWorker.h b/src/lib/orderman/orders/spreader_orders/spreader/quoter/quoter_states/QuoterWorkingStateWorker.h index e7f5ee612..33a5dc77f 100644 --- a/src/lib/orderman/orders/spreader_orders/spreader/quoter/quoter_states/QuoterWorkingStateWorker.h +++ b/src/lib/orderman/orders/spreader_orders/spreader/quoter/quoter_states/QuoterWorkingStateWorker.h @@ -23,7 +23,7 @@ public: virtual void on_transition () override; void one_time_activate (Price, Quantity) override; void on_order_update (const SpreaderChildOrderState& order_update) override; - void on_book (size_t leg_id, const bts::orderman::Book& book,trace::CorID &) override; + void on_book (size_t leg_id, const bts::orderman::Book& book) override; void cancel() override; void terminate() override; void on_time(const TimeStamp& ts) override; @@ -34,8 +34,7 @@ private: // i. if target reached => cxl order and go to waiting_for_cancel_ack_final // ii. if computed_qty = 0 => cxl order and go to waiting_for_cancel_ack_continue // iii. if reprice (ie qty changed or price changed beyond the threshold) => requote - void _longpath_analyze_and_act (trace::CorID &); void _longpath_analyze_and_act (); - void _modify_order (Price price, Quantity quantity,trace::CorID &); + void _modify_order (Price price, Quantity quantity); }; }} diff --git a/src/lib/orderman/orders/spreader_orders/spreader_states/SpreaderEndStateWorker.cpp b/src/lib/orderman/orders/spreader_orders/spreader_states/SpreaderEndStateWorker.cpp index b0bc2c9dc..563215c4f 100644 --- a/src/lib/orderman/orders/spreader_orders/spreader_states/SpreaderEndStateWorker.cpp +++ b/src/lib/orderman/orders/spreader_orders/spreader_states/SpreaderEndStateWorker.cpp @@ -34,7 +34,7 @@ void SpreaderEndStateWorker::on_update(Price, Quantity){ } void SpreaderEndStateWorker::on_cancel(){ } -void SpreaderEndStateWorker::on_book(const Book&,trace::CorID){ +void SpreaderEndStateWorker::on_book(const Book&){ } void SpreaderEndStateWorker::on_settlement_price(const SettlementUpdateEvent&){ } @@ -42,8 +42,7 @@ void SpreaderEndStateWorker::on_time(const TimeStamp&){ } void SpreaderEndStateWorker::on_quoter_order_error(SpreaderLegData&){ } -void SpreaderEndStateWorker::on_quoter_order_fill(SpreaderLegData&, - trace::CorID){ +void SpreaderEndStateWorker::on_quoter_order_fill(SpreaderLegData&){ } void SpreaderEndStateWorker::on_quoter_order_status_update(SpreaderLegData&){ } diff --git a/src/lib/orderman/orders/spreader_orders/spreader_states/SpreaderEndStateWorker.h b/src/lib/orderman/orders/spreader_orders/spreader_states/SpreaderEndStateWorker.h index cdf791845..5546a5402 100644 --- a/src/lib/orderman/orders/spreader_orders/spreader_states/SpreaderEndStateWorker.h +++ b/src/lib/orderman/orders/spreader_orders/spreader_states/SpreaderEndStateWorker.h @@ -20,12 +20,11 @@ public: void on_activate(Price, Quantity, SpreaderOrderServices&) override; void on_update(Price, Quantity) override; void on_cancel() override; - void on_book(const Book&,trace::CorID) override; + void on_book(const Book&) override; void on_settlement_price(const SettlementUpdateEvent&) override; void on_time(const TimeStamp&) override; void on_quoter_order_error(SpreaderLegData& leg_data) override; - void on_quoter_order_fill(SpreaderLegData& leg_data, - trace::CorID) override; + void on_quoter_order_fill(SpreaderLegData& leg_data) override; void on_quoter_order_status_update(SpreaderLegData& leg_data) override; void on_hedger_order_error(SingleFillHedger&) override; void on_hedger_order_update(SingleFillHedger&) override; diff --git a/src/lib/orderman/orders/spreader_orders/spreader_states/SpreaderStartStateWorker.cpp b/src/lib/orderman/orders/spreader_orders/spreader_states/SpreaderStartStateWorker.cpp index 39dc6844f..182f1ca26 100644 --- a/src/lib/orderman/orders/spreader_orders/spreader_states/SpreaderStartStateWorker.cpp +++ b/src/lib/orderman/orders/spreader_orders/spreader_states/SpreaderStartStateWorker.cpp @@ -130,7 +130,7 @@ void SpreaderStartStateWorker::on_cancel(){ // and hence it goes directly to END _spreader->_transform_to_END(); } -void SpreaderStartStateWorker::on_book(const bts::orderman::Book&,trace::CorID ){ +void SpreaderStartStateWorker::on_book(const bts::orderman::Book&){ bts_assert_msg (false, "SpreaderStartStateWorker::on_book is an illegal operation"); } void SpreaderStartStateWorker::on_settlement_price(const SettlementUpdateEvent&){ @@ -143,8 +143,7 @@ void SpreaderStartStateWorker::on_time(const TimeStamp&){ void SpreaderStartStateWorker::on_quoter_order_error(SpreaderLegData&){ bts_assert_msg (false, "SpreaderStartStateWorker::on_quoter_order_error is an illegal operation"); } -void SpreaderStartStateWorker::on_quoter_order_fill(SpreaderLegData&, - trace::CorID){ +void SpreaderStartStateWorker::on_quoter_order_fill(SpreaderLegData&){ bts_assert_msg (false, "SpreaderStartStateWorker::on_quoter_order_fill is an illegal operation"); } void SpreaderStartStateWorker::on_quoter_order_status_update(SpreaderLegData&){ diff --git a/src/lib/orderman/orders/spreader_orders/spreader_states/SpreaderStartStateWorker.h b/src/lib/orderman/orders/spreader_orders/spreader_states/SpreaderStartStateWorker.h index 78e92a3cd..80f299fbf 100644 --- a/src/lib/orderman/orders/spreader_orders/spreader_states/SpreaderStartStateWorker.h +++ b/src/lib/orderman/orders/spreader_orders/spreader_states/SpreaderStartStateWorker.h @@ -25,12 +25,11 @@ public: SpreaderOrderServices&) override; void on_update(Price, Quantity) override; void on_cancel() override; - void on_book(const Book&,trace::CorID ) override; + void on_book(const Book&) override; void on_time(const TimeStamp&) override; void on_settlement_price(const SettlementUpdateEvent&) override; void on_quoter_order_error(SpreaderLegData& leg_data) override; - void on_quoter_order_fill(SpreaderLegData& leg_data, - trace::CorID ) override; + void on_quoter_order_fill(SpreaderLegData& leg_data) override; void on_quoter_order_status_update(SpreaderLegData& leg_data) override; void on_hedger_order_error(SingleFillHedger&) override; void on_hedger_order_update(SingleFillHedger&) override; diff --git a/src/lib/orderman/orders/spreader_orders/spreader_states/SpreaderWaitingForCancelAllStateWorker.cpp b/src/lib/orderman/orders/spreader_orders/spreader_states/SpreaderWaitingForCancelAllStateWorker.cpp index 935e54e74..e4008053c 100644 --- a/src/lib/orderman/orders/spreader_orders/spreader_states/SpreaderWaitingForCancelAllStateWorker.cpp +++ b/src/lib/orderman/orders/spreader_orders/spreader_states/SpreaderWaitingForCancelAllStateWorker.cpp @@ -33,7 +33,7 @@ void SpreaderWaitingForCancelAllStateWorker::on_update(Price, } void SpreaderWaitingForCancelAllStateWorker::on_cancel(){ } -void SpreaderWaitingForCancelAllStateWorker::on_book(const Book&,trace::CorID ){ +void SpreaderWaitingForCancelAllStateWorker::on_book(const Book&){ } void SpreaderWaitingForCancelAllStateWorker::on_time(const TimeStamp& ts){ if (ms_diff (ts, _cancel_timestamp) >= _spreader->_cancel_timeout){ @@ -49,9 +49,8 @@ void SpreaderWaitingForCancelAllStateWorker::on_quoter_order_error( SpreaderLegData& leg_data){ leg_data.quoter().update_order_status (leg_data.order_update_message()); } -void SpreaderWaitingForCancelAllStateWorker::on_quoter_order_fill( - SpreaderLegData& leg_data, - trace::CorID ){ +void SpreaderWaitingForCancelAllStateWorker::on_quoter_order_fill(SpreaderLegData& leg_data){ + leg_data.quoter().update_order_status (leg_data.order_update_message()); } void SpreaderWaitingForCancelAllStateWorker::on_quoter_order_status_update( diff --git a/src/lib/orderman/orders/spreader_orders/spreader_states/SpreaderWaitingForCancelAllStateWorker.h b/src/lib/orderman/orders/spreader_orders/spreader_states/SpreaderWaitingForCancelAllStateWorker.h index cf6f7ca0b..e046b202b 100644 --- a/src/lib/orderman/orders/spreader_orders/spreader_states/SpreaderWaitingForCancelAllStateWorker.h +++ b/src/lib/orderman/orders/spreader_orders/spreader_states/SpreaderWaitingForCancelAllStateWorker.h @@ -23,12 +23,11 @@ public: SpreaderOrderServices&) override; void on_update(Price, Quantity) override; void on_cancel() override; - void on_book(const Book&,trace::CorID ) override; + void on_book(const Book&) override; void on_settlement_price(const SettlementUpdateEvent&) override; void on_time(const TimeStamp&) override; void on_quoter_order_error(SpreaderLegData& leg_data) override; - void on_quoter_order_fill(SpreaderLegData& leg_data, - trace::CorID ) override; + void on_quoter_order_fill(SpreaderLegData& leg_data) override; void on_quoter_order_status_update(SpreaderLegData& leg_data) override; void on_hedger_order_error(SingleFillHedger&) override; void on_hedger_order_update(SingleFillHedger&) override; diff --git a/src/lib/orderman/orders/spreader_orders/spreader_states/SpreaderWaitingForInitialDataStateWorker.cpp b/src/lib/orderman/orders/spreader_orders/spreader_states/SpreaderWaitingForInitialDataStateWorker.cpp index 978639db8..3c60e3e81 100644 --- a/src/lib/orderman/orders/spreader_orders/spreader_states/SpreaderWaitingForInitialDataStateWorker.cpp +++ b/src/lib/orderman/orders/spreader_orders/spreader_states/SpreaderWaitingForInitialDataStateWorker.cpp @@ -45,8 +45,7 @@ void SpreaderWaitingForInitialDataStateWorker::on_update(Price, void SpreaderWaitingForInitialDataStateWorker::on_cancel(){ _spreader->_transform_to_END(); } -void SpreaderWaitingForInitialDataStateWorker::on_book(const Book& book, - trace::CorID){ +void SpreaderWaitingForInitialDataStateWorker::on_book(const Book& book){ SpreaderBookkeepingData& bookkeeping_data = _spreader->_bookkeeping_data(); SpreaderLegData& md_leg = bookkeeping_data.get_leg_data(book.security_key()); md_leg.update_book(book); @@ -70,8 +69,7 @@ void SpreaderWaitingForInitialDataStateWorker::on_quoter_order_error(SpreaderLeg bts_assert_msg (false, "SpreaderWaitingForInitialDataStateWorker::" "on_quoter_order_error is an illegal operation"); } -void SpreaderWaitingForInitialDataStateWorker::on_quoter_order_fill(SpreaderLegData&, - trace::CorID){ +void SpreaderWaitingForInitialDataStateWorker::on_quoter_order_fill(SpreaderLegData&){ bts_assert_msg (false, "SpreaderWaitingForInitialDataStateWorker::" "on_quoter_order_fill is an illegal operation"); } diff --git a/src/lib/orderman/orders/spreader_orders/spreader_states/SpreaderWaitingForInitialDataStateWorker.h b/src/lib/orderman/orders/spreader_orders/spreader_states/SpreaderWaitingForInitialDataStateWorker.h index c344a8542..f7bda3470 100644 --- a/src/lib/orderman/orders/spreader_orders/spreader_states/SpreaderWaitingForInitialDataStateWorker.h +++ b/src/lib/orderman/orders/spreader_orders/spreader_states/SpreaderWaitingForInitialDataStateWorker.h @@ -25,12 +25,11 @@ public: SpreaderOrderServices&) override; void on_update(Price, Quantity) override; void on_cancel() override; - void on_book(const Book&,trace::CorID) override; + void on_book(const Book&) override; void on_settlement_price(const SettlementUpdateEvent&) override; void on_time(const TimeStamp&) override; void on_quoter_order_error(SpreaderLegData& leg_data) override; - void on_quoter_order_fill(SpreaderLegData& leg_data, - trace::CorID ) override; + void on_quoter_order_fill(SpreaderLegData& leg_data) override; void on_quoter_order_status_update(SpreaderLegData& leg_data) override; void on_hedger_order_error(SingleFillHedger&) override; void on_hedger_order_update(SingleFillHedger&) override; diff --git a/src/lib/orderman/orders/spreader_orders/spreader_states/SpreaderWorkingStateWorker.cpp b/src/lib/orderman/orders/spreader_orders/spreader_states/SpreaderWorkingStateWorker.cpp index 0e477ef55..f501298e0 100644 --- a/src/lib/orderman/orders/spreader_orders/spreader_states/SpreaderWorkingStateWorker.cpp +++ b/src/lib/orderman/orders/spreader_orders/spreader_states/SpreaderWorkingStateWorker.cpp @@ -42,7 +42,7 @@ void SpreaderWorkingStateWorker::on_cancel(){ _spreader->_cancel_orders (true, true); _spreader->_transform_to_WAITING_FOR_CANCEL_ALL (); } -void SpreaderWorkingStateWorker::on_book(const Book& book,trace::CorID trace){ +void SpreaderWorkingStateWorker::on_book(const Book& book){ SpreaderBookkeepingData& bookkeeping_data = _spreader->_bookkeeping_data(); // this is a key->index lookup SpreaderLegData& md_leg = bookkeeping_data.get_leg_data(book.security_key()); @@ -53,10 +53,10 @@ void SpreaderWorkingStateWorker::on_book(const Book& book,trace::CorID trace){ for (size_t q_idx = 0; q_idx < bookkeeping_data.n_legs(); q_idx++){ SpreaderLegData& d = bookkeeping_data.get_leg_data(q_idx); if (d.leg_property_data().is_active_quoting()) - d.quoter().on_book(md_leg.leg_property_data().leg_index(), book,trace); + d.quoter().on_book(md_leg.leg_property_data().leg_index(), book); } //send md to hedgers hedging this security only - md_leg.hedger_manager().update_book(book,trace); + md_leg.hedger_manager().update_book(book); } void SpreaderWorkingStateWorker::on_settlement_price(const SettlementUpdateEvent&){ } @@ -75,8 +75,7 @@ void SpreaderWorkingStateWorker::on_quoter_order_error(SpreaderLegData& leg_data _spreader->_cancel_orders (true, true); _spreader->_transform_to_WAITING_FOR_CANCEL_ALL (); } -void SpreaderWorkingStateWorker::on_quoter_order_fill(SpreaderLegData& leg_data, - trace::CorID trace){ +void SpreaderWorkingStateWorker::on_quoter_order_fill(SpreaderLegData& leg_data){ const CacheWarmingState& cw=_spreader->_cw_helper; SpreaderChildOrderState& updated_order = leg_data.order_update_message(); double mult = cw.fill_mult; @@ -134,8 +133,7 @@ void SpreaderWorkingStateWorker::on_quoter_order_fill(SpreaderLegData& leg_data, // a hedge is sent regardless _spreader->_send_hedge(other_leg_data.leg_property_data().leg_index(), hedge_price, - Quantity(total_unhedged_qty), - trace); + Quantity(total_unhedged_qty)); LOG(OrderMan,cw.llevel,"h_p send hedge {} {}", q_idx, _spreader->_diff_ns()); } } diff --git a/src/lib/orderman/orders/spreader_orders/spreader_states/SpreaderWorkingStateWorker.h b/src/lib/orderman/orders/spreader_orders/spreader_states/SpreaderWorkingStateWorker.h index 214e2eba1..fbe002964 100644 --- a/src/lib/orderman/orders/spreader_orders/spreader_states/SpreaderWorkingStateWorker.h +++ b/src/lib/orderman/orders/spreader_orders/spreader_states/SpreaderWorkingStateWorker.h @@ -22,12 +22,11 @@ public: SpreaderOrderServices&) override; void on_update(Price, Quantity) override; void on_cancel() override; - void on_book(const Book&,trace::CorID ) override; + void on_book(const Book&) override; void on_settlement_price(const SettlementUpdateEvent&) override; void on_time(const TimeStamp&) override; void on_quoter_order_error(SpreaderLegData& leg_data) override; - void on_quoter_order_fill(SpreaderLegData& leg_data, - trace::CorID ) override; + void on_quoter_order_fill(SpreaderLegData& leg_data) override; void on_quoter_order_status_update(SpreaderLegData& leg_data) override; void on_hedger_order_error(SingleFillHedger&) override; void on_hedger_order_update(SingleFillHedger&) override; diff --git a/src/lib/orderman/orders/spreader_orders/tests/spreader_tests.cpp b/src/lib/orderman/orders/spreader_orders/tests/spreader_tests.cpp index f29fb2b67..dbdb6cd90 100644 --- a/src/lib/orderman/orders/spreader_orders/tests/spreader_tests.cpp +++ b/src/lib/orderman/orders/spreader_orders/tests/spreader_tests.cpp @@ -47,9 +47,8 @@ TEST_CASE ("quoter price quantity state", "[spreader]") REQUIRE (s.out_price() == Price (0.0)); REQUIRE (s.out_quantity() == Quantity (0)); // set out price and quantity - trace::CorID dont_care; bts::TimeStamp ts; - order.place_order(Price (-0.35), Quantity (123),ts,dont_care); + order.place_order(Price (-0.35), Quantity (123),ts); REQUIRE (s.target_spread_price() == Price (-1.0)); REQUIRE (s.target_leg_quantity() == Quantity (200)); REQUIRE (s.aggregated_filled_quantity() == Quantity (25)); @@ -102,9 +101,8 @@ TEST_CASE ("quoter price quantity state", "[spreader]") s.add_hedged_reduction (Quantity(5)); s.add_hedged_reduction (Quantity(15)); // set out values - trace::CorID dont_care; bts::TimeStamp ts; - order_2.place_order (Price(1), Quantity (50),ts,dont_care); + order_2.place_order (Price(1), Quantity (50),ts); REQUIRE (s.target_spread_price() == Price (-1.0)); REQUIRE (s.target_leg_quantity() == Quantity (200)); REQUIRE (s.aggregated_filled_quantity() == Quantity (40)); @@ -126,7 +124,7 @@ TEST_CASE ("quoter price quantity state", "[spreader]") on_order_update (order_2, api::orderman::OrderStatus::ORDER_STATUS_WORKING, Quantity (10), Price (2000)); s.add_hedged_reduction (Quantity(3)); s.add_hedged_reduction (Quantity(7)); - order_2.place_order (Price(0.75), Quantity (50),ts,dont_care); + order_2.place_order (Price(0.75), Quantity (50),ts); REQUIRE (s.target_spread_price() == Price (-1.0)); REQUIRE (s.target_leg_quantity() == Quantity (200)); REQUIRE (s.aggregated_filled_quantity() == Quantity (10)); @@ -1278,11 +1276,9 @@ TEST_CASE ("hedger_START_state", "[spreader]") SpreaderManagerForTest& sm = *sm_ptr; ChildOrder co; - trace::CorID trace; SingleFillHedger& hedger = bookeeping_data.add_new_hedger(1, hedger_price, - hedger_quantity, - trace); + hedger_quantity); verify_complete_hedger_state (hedger, HedgerState::WAITING_FOR_FIRST_ACK, hedger_price, @@ -1362,11 +1358,9 @@ TEST_CASE ("hedger_WAITING_FOR_FIRST_ACK_state", "[spreader]") ChildOrder co; //SingleFillHedger hedger (sm, sm.get_leg_data (1), co, hedger_price, hedger_quantity,false); - trace::CorID trace; SingleFillHedger& hedger = bookeeping_data.add_new_hedger(1, hedger_price, - hedger_quantity, - trace); + hedger_quantity); verify_complete_hedger_state (hedger, HedgerState::WAITING_FOR_FIRST_ACK, hedger_price, hedger_quantity, Quantity (0), hedger_price, hedger_quantity, hedger_quantity); SECTION("1. init") { @@ -1425,11 +1419,9 @@ TEST_CASE ("hedger_WAITING_FOR_FIRST_ACK_CANCELLED_state", "[spreader]") SpreaderManagerForTest& sm = *sm_ptr; ChildOrder co; - trace::CorID trace; SingleFillHedger& hedger = bookeeping_data.add_new_hedger(1, hedger_price, - hedger_quantity, - trace); + hedger_quantity); verify_complete_hedger_state (hedger, HedgerState::WAITING_FOR_FIRST_ACK, hedger_price, @@ -1504,11 +1496,9 @@ TEST_CASE ("hedger_WAITING_FOR_CANCEL_ACK_state", "[spreader]") SpreaderManagerForTest& sm = *sm_ptr; ChildOrder co; - trace::CorID trace; SingleFillHedger& hedger = bookeeping_data.add_new_hedger(1, hedger_price, - hedger_quantity, - trace); + hedger_quantity); verify_complete_hedger_state (hedger, HedgerState::WAITING_FOR_FIRST_ACK, hedger_price, @@ -1586,11 +1576,9 @@ TEST_CASE ("hedger_END_state", "[spreader]") SpreaderManagerForTest& sm = *sm_ptr; ChildOrder co; - trace::CorID trace; SingleFillHedger& hedger = bookeeping_data.add_new_hedger(1, hedger_price, - hedger_quantity, - trace); + hedger_quantity); verify_complete_hedger_state (hedger, HedgerState::WAITING_FOR_FIRST_ACK, hedger_price, @@ -1649,11 +1637,9 @@ TEST_CASE ("hedger_WORKING", "[spreader]") SpreaderManagerForTest& sm = *sm_ptr; ChildOrder co; - trace::CorID trace; SingleFillHedger& hedger = bookeeping_data.add_new_hedger(1, hedger_price, - hedger_quantity, - trace); + hedger_quantity); verify_complete_hedger_state (hedger, HedgerState::WAITING_FOR_FIRST_ACK, hedger_price, @@ -1782,7 +1768,7 @@ TEST_CASE ("spreader_START", "[spreader]") } SECTION("5. on_cancel") { - spreader.on_cancel(trace::CorID()); + spreader.on_cancel(); REQUIRE(spreader.test_only_func_spreader_state() == SpreaderState::END); LOG(OrderMan, Diag, "spreader_START.on_cancel"); } @@ -1898,7 +1884,7 @@ TEST_CASE ("spreader_WORKING", "[spreader]") // be as is spreader_price = Price (0); spreader_quantity = Quantity (200); - spreader.on_update (spreader_price, spreader_quantity,trace::CorID()); + spreader.on_update (spreader_price, spreader_quantity); verify_basic_spreader_state (spreader, SpreaderState::WORKING, spreader_price, spreader_quantity); verify_complete_quoter_state (leg_data_1.quoter(), QuoterState::WORKING, false, spreader_price, spreader_quantity, Quantity (30), Quantity(55), Price(1998), Quantity(130), Quantity(115), false); verify_complete_quoter_state (leg_data_2.quoter(), QuoterState::WORKING, false, spreader_price, spreader_quantity, Quantity (55), Quantity(30), Price(2004), Quantity(165), Quantity(115), false); @@ -1908,7 +1894,7 @@ TEST_CASE ("spreader_WORKING", "[spreader]") } SECTION("5. on_cancel") { - spreader.on_cancel(trace::CorID()); + spreader.on_cancel(); verify_basic_spreader_state (spreader, SpreaderState::WAITING_FOR_CANCEL_ALL, spreader_price, spreader_quantity); generic_validate_quoters (QuoterState::WAITING_FOR_CANCEL_ACK, true); generic_validate_hedgers (HedgerState::WAITING_FOR_CANCEL_ACK); @@ -1929,7 +1915,7 @@ TEST_CASE ("spreader_WORKING", "[spreader]") new double[5] {2005, 2006, 2007, 2008, 2009}, new uint16_t[5] {0, 0, 0, 0, 0}, true); - spreader.test_only_on_book_update (modified_book, trace::CorID()); + spreader.test_only_on_book_update (modified_book); verify_basic_spreader_state (spreader, SpreaderState::WORKING, spreader_price, spreader_quantity); generic_validate_quoters (QuoterState::WORKING, false); generic_validate_hedgers (HedgerState::WORKING); @@ -1944,7 +1930,7 @@ TEST_CASE ("spreader_WORKING", "[spreader]") new uint16_t[5] {25, 25, 20, 20, 10}, true); //spreader.on_book (bts::orderman::trace::CorID(), modified_book); - spreader.test_only_on_book_update (modified_book,trace::CorID()); + spreader.test_only_on_book_update (modified_book); verify_basic_spreader_state (spreader, SpreaderState::WORKING, spreader_price, spreader_quantity); verify_complete_quoter_state (leg_data_1.quoter(), QuoterState::WORKING, false, spreader_price, Quantity (100), Quantity (30), Quantity(55), Price(1999), Quantity(45), Quantity(15), false); verify_complete_quoter_state (leg_data_2.quoter(), QuoterState::WORKING, false, spreader_price, Quantity (100), Quantity (55), Quantity(30), Price(2000), Quantity(70), Quantity(15), false); @@ -1960,7 +1946,7 @@ TEST_CASE ("spreader_WORKING", "[spreader]") new uint16_t[5] {25, 25, 20, 20, 10}, true); //spreader.on_book (bts::orderman::trace::CorID(), modified_book); - spreader.test_only_on_book_update (modified_book,trace::CorID()); + spreader.test_only_on_book_update (modified_book); verify_basic_spreader_state (spreader, SpreaderState::WORKING, spreader_price, spreader_quantity); verify_complete_quoter_state (leg_data_1.quoter(), QuoterState::WORKING, false, spreader_price, Quantity (100), Quantity (30), Quantity(55), Price(2000), Quantity(34), Quantity(15), false); verify_complete_quoter_state (leg_data_2.quoter(), QuoterState::WORKING, false, spreader_price, Quantity (100), Quantity (55), Quantity(30), Price(2000), Quantity(70), Quantity(15), false); @@ -1974,7 +1960,7 @@ TEST_CASE ("spreader_WORKING", "[spreader]") new uint16_t[5] {25, 25, 20, 20, 10}, true); //spreader.on_book (bts::orderman::trace::CorID(), modified_book); - spreader.test_only_on_book_update (modified_book, trace::CorID()); + spreader.test_only_on_book_update (modified_book); verify_basic_spreader_state (spreader, SpreaderState::WORKING, spreader_price, spreader_quantity); verify_complete_quoter_state (leg_data_1.quoter(), QuoterState::WORKING, false, spreader_price, Quantity (100), Quantity (30), Quantity(55), Price(2001), Quantity(45), Quantity(15), false); verify_complete_quoter_state (leg_data_2.quoter(), QuoterState::WORKING, false, spreader_price, Quantity (100), Quantity (55), Quantity(30), Price(2000), Quantity(70), Quantity(15), false); @@ -1989,7 +1975,7 @@ TEST_CASE ("spreader_WORKING", "[spreader]") new uint16_t[5] {25, 25, 20, 20, 10}, true); //spreader.on_book (bts::orderman::trace::CorID(), modified_book); - spreader.test_only_on_book_update (modified_book, trace::CorID()); + spreader.test_only_on_book_update (modified_book); verify_basic_spreader_state (spreader, SpreaderState::WORKING, spreader_price, spreader_quantity); verify_complete_quoter_state (leg_data_1.quoter(), QuoterState::WAITING_FOR_CANCEL_ACK, false, spreader_price, Quantity (100), Quantity (30), Quantity(55), Price(2001), Quantity(45), Quantity(15), false); verify_complete_quoter_state (leg_data_2.quoter(), QuoterState::WORKING, false, spreader_price, Quantity (100), Quantity (55), Quantity(30), Price(2000), Quantity(70), Quantity(15), false); @@ -2205,7 +2191,7 @@ TEST_CASE ("spreader_WAITING_FOR_CANCEL_ACK", "[spreader]") // now cancel the spreader bts::TimeStamp cancel_timestamp = std::chrono::system_clock::now(); spreader.test_only_on_time (cancel_timestamp); - spreader.on_cancel (trace::CorID()); + spreader.on_cancel (); auto validate_state = [&]() -> void { verify_basic_spreader_state (spreader, SpreaderState::WAITING_FOR_CANCEL_ALL, spreader_price, spreader_quantity); @@ -2228,7 +2214,7 @@ TEST_CASE ("spreader_WAITING_FOR_CANCEL_ACK", "[spreader]") } SECTION("4. on_update") { - spreader.on_update (Price(-0.05), Quantity(200),trace::CorID()); + spreader.on_update (Price(-0.05), Quantity(200)); validate_state(); // order changes dont go through validate_state(); @@ -2236,7 +2222,7 @@ TEST_CASE ("spreader_WAITING_FOR_CANCEL_ACK", "[spreader]") } SECTION("5. on_cancel") { - spreader.on_cancel(trace::CorID()); + spreader.on_cancel(); // already in cancel state, no change validate_state(); LOG(OrderMan, Diag, "spreader_WAITING_FOR_CANCEL_ACK.on_cancel"); @@ -2354,34 +2340,43 @@ TEST_CASE ("spreader_WAITING_FOR_CANCEL_ACK", "[spreader]") } TEST_CASE ("find_target_price_in_book", "[spreader]"){ SECTION("0.05"){ - Quantity out_level_qty, out_cum_qty; + Quantity out_cum_qty; bts::orderman::Book book; uint16_t sizes[] = { 11, 13, 17, 19, 23 }; double prices[] = { 22, 21.15, 20.10, 20.05, 20.00 }; fill_book (book, prices, sizes, bts::api::Side::SIDE_BUY); // middle - bool res = SpreaderUtils::find_qty_at_price_level(book, bts::api::Side::SIDE_BUY, Price(20.10), 0.05, out_level_qty, out_cum_qty); + bool res = SpreaderUtils::find_qty_upto_price_level(book, bts::api::Side::SIDE_BUY, Price(20.10), 0.05, out_cum_qty); REQUIRE(res); - REQUIRE(out_level_qty.value()==17); REQUIRE(out_cum_qty.value()==41); // first - res = SpreaderUtils::find_qty_at_price_level(book, bts::api::Side::SIDE_BUY, Price(22.00), 0.05, out_level_qty, out_cum_qty); + res = SpreaderUtils::find_qty_upto_price_level(book, bts::api::Side::SIDE_BUY, Price(22.00), 0.05, out_cum_qty); REQUIRE(res); - REQUIRE(out_level_qty.value()==11); REQUIRE(out_cum_qty.value()==11); // last - res = SpreaderUtils::find_qty_at_price_level(book, bts::api::Side::SIDE_BUY, Price(20.00), 0.05, out_level_qty, out_cum_qty); + res = SpreaderUtils::find_qty_upto_price_level(book, bts::api::Side::SIDE_BUY, Price(20.00), 0.05, out_cum_qty); REQUIRE(res); - REQUIRE(out_level_qty.value()==23); REQUIRE(out_cum_qty.value()==83); - // not found - res = SpreaderUtils::find_qty_at_price_level(book, bts::api::Side::SIDE_BUY, Price(21.00), 0.05, out_level_qty, out_cum_qty); - REQUIRE(!res); + // missing + res = SpreaderUtils::find_qty_upto_price_level(book, bts::api::Side::SIDE_BUY, Price(21.00), 0.05, out_cum_qty); + REQUIRE(res); + REQUIRE(out_cum_qty.value()==24); + // missing + res = SpreaderUtils::find_qty_upto_price_level(book, bts::api::Side::SIDE_BUY, Price(20.075), 0.05, out_cum_qty); + REQUIRE(res); + REQUIRE(out_cum_qty.value()==41); // rounding error - res = SpreaderUtils::find_qty_at_price_level(book, bts::api::Side::SIDE_BUY, Price(20.04999999), 0.05, out_level_qty, out_cum_qty); + res = SpreaderUtils::find_qty_upto_price_level(book, bts::api::Side::SIDE_BUY, Price(20.04999999), 0.05, out_cum_qty); REQUIRE(res); - REQUIRE(out_level_qty.value()==19); REQUIRE(out_cum_qty.value()==60); + // before + res = SpreaderUtils::find_qty_upto_price_level(book, bts::api::Side::SIDE_BUY, Price(22.05), 0.05, out_cum_qty); + REQUIRE(!res); + REQUIRE(out_cum_qty.value()==0); + // after + res = SpreaderUtils::find_qty_upto_price_level(book, bts::api::Side::SIDE_BUY, Price(19), 0.05, out_cum_qty); + REQUIRE(res); + REQUIRE(out_cum_qty.value()==83); } SECTION("1/32"){ Quantity out_level_qty, out_cum_qty; @@ -2390,34 +2385,33 @@ TEST_CASE ("find_target_price_in_book", "[spreader]"){ double prices[] = { 100.21875, 100.28125, 101, 101.53125, 101.71875 }; fill_book (book, prices, sizes, bts::api::Side::SIDE_SELL); // first - bool res = SpreaderUtils::find_qty_at_price_level(book, bts::api::Side::SIDE_SELL, Price(100.21875), 0.03125, out_level_qty, out_cum_qty); + bool res = SpreaderUtils::find_qty_upto_price_level(book, bts::api::Side::SIDE_SELL, Price(100.21875), 0.03125, out_cum_qty); REQUIRE(res); - REQUIRE(out_level_qty.value()==12); REQUIRE(out_cum_qty.value()==12); // middle - res = SpreaderUtils::find_qty_at_price_level(book, bts::api::Side::SIDE_SELL, Price(101.53125), 0.03125, out_level_qty, out_cum_qty); + res = SpreaderUtils::find_qty_upto_price_level(book, bts::api::Side::SIDE_SELL, Price(101.53125), 0.03125, out_cum_qty); REQUIRE(res); - REQUIRE(out_level_qty.value()==24); REQUIRE(out_cum_qty.value()==132); // end - res = SpreaderUtils::find_qty_at_price_level(book, bts::api::Side::SIDE_SELL, Price(101.71875), 0.03125, out_level_qty, out_cum_qty); + res = SpreaderUtils::find_qty_upto_price_level(book, bts::api::Side::SIDE_SELL, Price(101.71875), 0.03125, out_cum_qty); REQUIRE(res); - REQUIRE(out_level_qty.value()==33); REQUIRE(out_cum_qty.value()==165); // absent - res = SpreaderUtils::find_qty_at_price_level(book, bts::api::Side::SIDE_SELL, Price(101.5625), 0.03125, out_level_qty, out_cum_qty); - REQUIRE(!res); - REQUIRE(out_level_qty.value()==0); - REQUIRE(out_cum_qty.value()==0); - res = SpreaderUtils::find_qty_at_price_level(book, bts::api::Side::SIDE_BUY, Price(101.71875), 0.03125, out_level_qty, out_cum_qty); - REQUIRE(!res); - REQUIRE(out_level_qty.value()==0); - REQUIRE(out_cum_qty.value()==0); - // rounding - res = SpreaderUtils::find_qty_at_price_level(book, bts::api::Side::SIDE_SELL, Price(101.531249999999), 0.03125, out_level_qty, out_cum_qty); + res = SpreaderUtils::find_qty_upto_price_level(book, bts::api::Side::SIDE_SELL, Price(101.5625), 0.03125, out_cum_qty); REQUIRE(res); - REQUIRE(out_level_qty.value()==24); REQUIRE(out_cum_qty.value()==132); + // rounding + res = SpreaderUtils::find_qty_upto_price_level(book, bts::api::Side::SIDE_SELL, Price(101.531249999999), 0.03125, out_cum_qty); + REQUIRE(res); + REQUIRE(out_cum_qty.value()==132); + // before + res = SpreaderUtils::find_qty_upto_price_level(book, bts::api::Side::SIDE_SELL, Price(100.21875-0.03125), 0.03125, out_cum_qty); + REQUIRE(!res); + REQUIRE(out_cum_qty.value()==0); + // after + res = SpreaderUtils::find_qty_upto_price_level(book, bts::api::Side::SIDE_SELL, Price(101.71875+0.03125), 0.03125, out_cum_qty); + REQUIRE(res); + REQUIRE(out_cum_qty.value()==165); } } TEST_CASE ("prehedge_payless", "[spreader]"){ @@ -4023,4 +4017,4 @@ TEST_CASE ("scratch_pad_2", "[spreader]"){ LOG(OrderMan, Info, "hrs:{} mins:{} sec:{}", ptm->tm_hour, ptm->tm_min, ptm->tm_sec); } -}} \ No newline at end of file +}} diff --git a/src/lib/orderman/orders/spreader_orders/tests/tests_common.h b/src/lib/orderman/orders/spreader_orders/tests/tests_common.h index 0df60ab72..2843ae4f1 100644 --- a/src/lib/orderman/orders/spreader_orders/tests/tests_common.h +++ b/src/lib/orderman/orders/spreader_orders/tests/tests_common.h @@ -114,7 +114,7 @@ void on_order_update (SpreaderChildOrderState& order, //order_state.set_filled_quantity (order.current_fills().value() + last_filled_quantity.value()); order_state.set_filled_quantity (filled_quantity.value()); bts::api::orderman::OrderDefinition order_def; - OrderStateUpdateEvent e (OrderKey(),OrderKey(),order_def, order_state); + OrderStateUpdateEvent e (OrderKey(),OrderKey(),std::make_shared (order_def),order_state); order.on_order_update(e); } /**********************************************************************/ @@ -447,8 +447,7 @@ void fire_book_update (double* prices, uint16_t* sizes, api::Side side, size_t l bts::orderman::Book book; fill_book (book, prices, sizes, side); sm.set_book (book, leg_index); - trace::CorID trace; - quoter.on_book (leg_index, book,trace); + quoter.on_book (leg_index, book); } void verify_leg_data (SpreaderLegData& l, bts::orderman::OrderKey, size_t leg_index, uint32_t sec_key, uint32_t exp_yr, uint32_t exp_m, uint32_t exp_day, const std::string& symbol, double leg_mult, double price_mult, api::Side side) { @@ -498,8 +497,7 @@ void fire_book_update_hedger (double* prices, uint16_t* sizes, api::Side side, S { bts::orderman::Book book; fill_book (book, prices, sizes, side); - trace::CorID trace; - hedger.on_book (book,trace); + hedger.on_book (book); } void verify_complete_hedger_state (const SingleFillHedger& hedger, HedgerState state, @@ -606,11 +604,11 @@ void set_spreader_orders (SpreaderOrder& spreader, double* leg_1_bid_prices, uin bts::orderman::Book book_leg_1 = get_book (SecurityKey (leg_1_id), 5, leg_1_bid_prices, leg_1_bid_sizes, leg_1_ask_prices, leg_1_ask_sizes, true); - spreader.test_only_on_book_update (bts::orderman::BookUpdateEvent(book_leg_1, trace::CorID())); + spreader.test_only_on_book_update (bts::orderman::BookUpdateEvent(book_leg_1)); bts::orderman::Book book_leg_2 = get_book (SecurityKey (leg_2_id), 5, leg_2_bid_prices, leg_2_bid_sizes, leg_2_ask_prices, leg_2_ask_sizes, true); - spreader.test_only_on_book_update (bts::orderman::BookUpdateEvent(book_leg_2,trace::CorID())); + spreader.test_only_on_book_update (bts::orderman::BookUpdateEvent(book_leg_2)); if(leg_data_1.leg_property_data().is_active_quoting()) spreader.test_only_on_child_order_update (leg_data_1.order_key(), api::orderman::OrderStatus::ORDER_STATUS_WORKING, Quantity (leg_1_fills), Price (leg_1_filled_price)); if(leg_data_2.leg_property_data().is_active_quoting()) diff --git a/src/lib/orderman/server/OrderServiceServer.cpp b/src/lib/orderman/server/OrderServiceServer.cpp index b31bc2416..af49ce401 100644 --- a/src/lib/orderman/server/OrderServiceServer.cpp +++ b/src/lib/orderman/server/OrderServiceServer.cpp @@ -17,6 +17,7 @@ #include "lib/orderman/actors/SecuritySrc.h" #include "lib/orderman/actors/ServiceBridge.h" #include "lib/orderman/actors/order_manager/OrderManager.h" +#include "lib/orderman/events/OrderOpResultEvent.h" #include "lib/orderman/order_factory/DynamicOrderRegistry.h" #include "lib/plugin/SparkServices.h" #include "lib/plugin/plugin.h" @@ -91,11 +92,13 @@ ActorThread *find_thread_for_actor( struct OrderServiceServer::PImpl { PImpl(bts::api::ServiceContext &ctx, md::MDClient& mdc, - DynamicOrderRegistry const &d, metrics::MetricsContainer &stats, trace::PerfLog &log) + DynamicOrderRegistry const &d, metrics::MetricsContainer &stats, + trace::PerfLog &log) : service_bridge(), service_ready(false), known_orders(), known_fills(), publish_orders(), publish_fills(), admin_service(ctx.locate()), md_consumer(mdc.current_consumer()), - stats(stats), dyn_order_registry(d),log(log) {} + stats(stats), dyn_order_registry(d), log(log), in_flight_order_ops(), + current_req_op_id(0) {} ServiceBridge *service_bridge; @@ -112,6 +115,9 @@ struct OrderServiceServer::PImpl { metrics::MetricsContainer &stats; DynamicOrderRegistry const &dyn_order_registry; trace::PerfLog &log; + std::unordered_map> + in_flight_order_ops; + uint32_t current_req_op_id; }; OrderServiceServer::OrderServiceServer( @@ -120,7 +126,6 @@ OrderServiceServer::OrderServiceServer( DynamicOrderRegistry const &d, metrics::MetricsContainer &stats, trace::PerfLog &log) : api::orderman::OrderServiceBase(ctx), me(new PImpl(ctx, mdc, d, stats,log)) { - me->publish_orders = make_orders_publisher(); me->publish_fills = make_fills_publisher(); @@ -140,7 +145,7 @@ OrderServiceServer::OrderServiceServer( "Could not find a configured thread for MDSource. See the " "OrdermanCfg key"); - thread->executor.spawn(me->md_consumer, me->stats,log); + thread->executor.spawn(me->md_consumer, me->stats, log); // OrderManager thread = find_thread_for_actor("OrderManager", me->actor_threads); @@ -199,15 +204,20 @@ OrderServiceServer::OrderServiceServer( "the OrdermanCfg key"); me->service_bridge = new ServiceBridge( [this]() { me->service_ready = true; }, - [this, &ctx](auto const &orders) { ctx.post([this, orders] { this->on_orders(orders); }); }, - [this, &ctx](auto const &fill) { ctx.post([this, fill] { this->on_fills(fill); }); }, - me->dyn_order_registry, thread->executor.make_proxy(),mdc.oracle()); + [this, &ctx](auto const &order_op_result) { + ctx.post([this, order_op_result] { + this->on_order_op_result(order_op_result); + }); + }, + me->dyn_order_registry, + thread->executor.make_proxy(),mdc.oracle()); + thread->executor.activate(me->service_bridge); @@ -278,51 +288,60 @@ void OrderServiceServer::on_fills( void OrderServiceServer::create_order( const api::orderman::Create &c, const api::Response &r) { - api::orderman::Response response; - if (!me->service_ready) + + if (!me->service_ready) { + api::orderman::Response response; response.set_error_code(api::orderman::ORDER_ERROR_SERVER_NOT_READY); - else - response = me->service_bridge->create_order(c); - r(response); + r(response); + } else { + me->in_flight_order_ops[++me->current_req_op_id] = r; + me->service_bridge->create_order(me->current_req_op_id, c); + } } void OrderServiceServer::cancel_order( const api::orderman::Cancel &cancel, const api::Response &r) { - api::orderman::Response response; - response.set_order_key(cancel.order_key()); - if (!me->service_ready) + if (!me->service_ready) { + api::orderman::Response response; + response.set_order_key(cancel.order_key()); response.set_error_code(api::orderman::ORDER_ERROR_SERVER_NOT_READY); - else - response = me->service_bridge->cancel_order(cancel); - r(response); + r(response); + } else { + me->in_flight_order_ops[++me->current_req_op_id] = r; + me->service_bridge->cancel_order(me->current_req_op_id, cancel); + } } void OrderServiceServer::update_order( const api::orderman::Update &update, const api::Response &r) { - api::orderman::Response response; - response.set_order_key(update.order_key()); - if (!me->service_ready) + if (!me->service_ready) { + api::orderman::Response response; + response.set_order_key(update.order_key()); response.set_error_code(api::orderman::ORDER_ERROR_SERVER_NOT_READY); - else - response = me->service_bridge->update_order(update); - r(response); + r(response); + } else { + me->in_flight_order_ops[++me->current_req_op_id] = r; + me->service_bridge->update_order(me->current_req_op_id, update); + } } -void OrderServiceServer::crack_order( - const api::orderman::Crack &crack, +void OrderServiceServer::detach_order( + const api::orderman::Detach &detach, const api::Response &r) { - api::orderman::Response response; - response.set_order_key(crack.order_key()); - if (!me->service_ready) + if (!me->service_ready) { + api::orderman::Response response; + response.set_order_key(detach.order_key()); response.set_error_code(api::orderman::ORDER_ERROR_SERVER_NOT_READY); - else - response = me->service_bridge->crack_order(crack); - r(response); + r(response); + } else { + me->in_flight_order_ops[++me->current_req_op_id] = r; + me->service_bridge->detach_order(me->current_req_op_id, detach); + } } void OrderServiceServer::get_registered_dynamic_order_types( @@ -336,5 +355,18 @@ void OrderServiceServer::get_registered_dynamic_order_types( r(response); } +void OrderServiceServer::on_order_op_result( + OrderOpResultEvent const &op_result) { + auto it = me->in_flight_order_ops.find(op_result.req_id); + bts_assert(it!=me->in_flight_order_ops.end()); + auto &responder = it->second; + api::orderman::Response r; + r.set_order_key(op_result.ok.value()); + r.set_error_code(op_result.result.error); + r.set_msg(op_result.result.error_msg); + responder(r); + me->in_flight_order_ops.erase(it); +} + } // namespace orderman } // namespace bts diff --git a/src/lib/orderman/server/OrderServiceServer.h b/src/lib/orderman/server/OrderServiceServer.h index 999b46790..5e38970cd 100644 --- a/src/lib/orderman/server/OrderServiceServer.h +++ b/src/lib/orderman/server/OrderServiceServer.h @@ -13,6 +13,7 @@ class MetricsContainer; } namespace orderman { class DynamicOrderRegistry; +class OrderOpResultEvent; class OrderServiceServer : public api::orderman::OrderServiceBase { public: @@ -29,7 +30,7 @@ class OrderServiceServer : public api::orderman::OrderServiceBase { const api::Response &) override; void update_order(const api::orderman::Update &, const api::Response &) override; - void crack_order(const api::orderman::Crack &, + void detach_order(const api::orderman::Detach &, const api::Response &) override; void get_registered_dynamic_order_types( const api::VoidMessage &, @@ -41,6 +42,7 @@ class OrderServiceServer : public api::orderman::OrderServiceBase { std::unique_ptr me; void on_orders(std::vector const &); void on_fills(std::vector const &); + void on_order_op_result(OrderOpResultEvent const&); }; } // namespace orderman diff --git a/src/lib/orderman2/orderman_utils/Book.h b/src/lib/orderman2/orderman_utils/Book.h deleted file mode 100644 index 3e505b38a..000000000 --- a/src/lib/orderman2/orderman_utils/Book.h +++ /dev/null @@ -1,72 +0,0 @@ -#pragma once - -#include -#include "lib/domain_model/common.h" -#include "lib/config/protos/MarketData.pb.h" -#include "lib/md/PriceSize.h" - - -namespace bts { -namespace orderman2 { - -using BookSide = std::array ; - -class Book { -public: - Book () : - _security_key(), - _book() - {} - - Book (SecurityKey key) : - _security_key(key), - _book() - {} - - Book (SecurityKey key, - BookSide const&bid, - BookSide const&ask) : - _security_key(key), - _book {bid,ask} - {} - - Book (Book const&rhs) - : _security_key(rhs._security_key), - _book(rhs._book) - {} - - Book &operator=(Book const &rhs) - { - _security_key = rhs._security_key; - _book = rhs._book; - return *this; - } - - SecurityKey security_key() const {return _security_key;} ; - - BookSide const &bid () const {return _book[0];} - BookSide const &ask () const {return _book[1];} - BookSide &bid () {return _book[0];} - BookSide &ask () {return _book[1];} - - size_t n_levels() const {return std::tuple_size();} - - BookSide const& side(api::Side bs) const - { - bts_assert_d(bs != api::SIDE_UNDEFINED); - return _book[bs - api::SIDE_BUY]; - } - - BookSide & side(api::Side bs) - { - bts_assert_d(bs != api::SIDE_UNDEFINED); - return _book[bs - api::SIDE_BUY]; - } - -private: - friend class MDSource; - SecurityKey _security_key; - std::array _book; -}; - -}} diff --git a/src/lib/orderman2/orderman_utils/orderman_utils.h b/src/lib/orderman2/orderman_utils/orderman_utils.h deleted file mode 100644 index 540f6a9a3..000000000 --- a/src/lib/orderman2/orderman_utils/orderman_utils.h +++ /dev/null @@ -1,10 +0,0 @@ -#pragma once - -#include "lib/utils/ValueWrapper.h" - -namespace bts { -namespace orderman2 { -using Price = utils::ValueWrapper; -using Quantity = utils::ValueWrapper; -using OrderKey = utils::ValueWrapper; -}} diff --git a/src/lib/orderman2/orders/NativeOrder.cpp b/src/lib/orderman2/orders/NativeOrder.cpp deleted file mode 100644 index 96e505504..000000000 --- a/src/lib/orderman2/orders/NativeOrder.cpp +++ /dev/null @@ -1,2 +0,0 @@ -#include "NativeOrder.h" - diff --git a/src/lib/orderman2/orders/NativeOrder.h b/src/lib/orderman2/orders/NativeOrder.h deleted file mode 100644 index 3e03df4de..000000000 --- a/src/lib/orderman2/orders/NativeOrder.h +++ /dev/null @@ -1,57 +0,0 @@ -#pragma once -#include "Order.h" - - -namespace bts { -namespace orderman { - - -struct PermissionQueryResult { - bool can_send; - std::string error_msg; -}; - -struct RouteQueryResult { - bool has_route; - std::string error_msg; - api::orderman::RoutingRecord routing_record; -}; - -class NativeOrder2 : public Order2 { -public: - virtual void on_execution_report(std::string const &, OrderKey, - ExecutionReport const &){}; - virtual void on_cancel_reject(std::string const &, OrderKey, - std::string const & /*msg*/){}; - virtual void on_gateway_status(std::string const &, bool /*is_connected*/){}; - - void subscribe_execution_report(std::string const &gw, OrderKey k); - void unsubscribe_execution_report(std::string const &gw, OrderKey k); - void subscribe_cancel_reject(std::string const &gw, OrderKey k); - void unsubscribe_cancel_reject(std::string const &gw, OrderKey k); - void subscribe_gateway_status(std::string const &); - void unsubscribe_gateway_status(std::string const &); - - RouteQueryResult get_route(AccountID, UserID, api::Security const &); - PermissionRec - get_permission_record(api::orderman::RoutingRecord const &routing, AccountID, - UserID, api::Security const &, api::Side); - - PermissionQueryResult can_send_new_order(PermissionRec const &, Quantity, - Price); - - PermissionQueryResult can_update_order(PermissionRec const &, Quantity from, - Quantity to, Price p); - - bool is_route_connected(api::orderman::RoutingRecord const &); - void send_fix(api::orderman::RoutingRecord const &rr, - jetfix::MessageTypes mt, jetfix::FIXFragment const &f); - - TimeStamp time() const; - mercury::TimeStampStr time_str() const; - private: - struct PImpl; - std::unique_ptr me; -}; - -}} diff --git a/src/lib/orderman2/orders/Order.cpp b/src/lib/orderman2/orders/Order.cpp deleted file mode 100644 index a14ec8bed..000000000 --- a/src/lib/orderman2/orders/Order.cpp +++ /dev/null @@ -1,2 +0,0 @@ -#include "Order.h" - diff --git a/src/lib/orderman2/orders/Order.h b/src/lib/orderman2/orders/Order.h deleted file mode 100644 index 24c10b533..000000000 --- a/src/lib/orderman2/orders/Order.h +++ /dev/null @@ -1,70 +0,0 @@ -#pragma once - -#include "lib/api/services/OrderService.pb.h" -#include "lib/domain_model/common.h" -#include "lib/jetfix/common/OutFIX.h" -#include "lib/mercury/common/mercury_common.h" -#include "lib/orderman/orderman_utils/Book.h" -#include "lib/orderman/orderman_utils/ExecutionReport.h" -#include "lib/orderman/orderman_utils/orderman_common.h" - -#include - -namespace bts { -namespace api { -namespace orderman { -class OrderDefinition; -class OrderRecord; -} // namespace orderman -} // namespace api -} // namespace bts - -namespace bts { -namespace orderman { - -struct ChildOrderDescriptor {}; -struct ChildOrder {}; - -class PermissionRec {}; - -class Order2 { - public: - virtual ~Order2(); - - virtual void on_init_new(api::orderman::OrderDefinition const &) = 0; - virtual void on_init_recovered(api::orderman::OrderRecord const &) = 0; - - virtual void on_activate(Price, Quantity) = 0; - virtual void on_update(Price, Quantity) = 0; - virtual void on_cancel() = 0; - virtual void on_child_order_update(OrderKey, api::orderman::OrderState const &){}; - virtual void on_book(SecurityKey, Book const &) {} - virtual void on_settlement(SecurityKey, Book const &) {} - virtual void on_time(TimeStamp const &) {} - - void subscribe_child_updates(OrderKey child); - void unsubscribe_child_updates(OrderKey child); - void subscribe_book(SecurityKey); - void unsubscribe_book(SecurityKey); - void subscribe_settlement(SecurityKey); - void unsubscribe_settlement(SecurityKey); - void subscribe_time(); - void unsubscribe_time(); - - api::Security const *resolve_security(SecurityKey const &k) const; - void report_state(const api::orderman::OrderState &state); - - ChildOrderDescriptor const & - make_child_order_descriptor(api::orderman::OrderDefinition const &, - size_t hint = 1); - ChildOrder make_child_order(ChildOrderDescriptor const &desc); - void send_child(ChildOrder ch, Price, Quantity); - void update_child(ChildOrder ch, Price, Quantity); - void cancel_child(ChildOrder ch); - - private: - struct PImpl; - std::unique_ptr me; -}; -} // namespace orderman -} // namespace bts diff --git a/src/lib/plugin/SparkServices.cpp b/src/lib/plugin/SparkServices.cpp index 444b3a1e8..b3c74fae3 100644 --- a/src/lib/plugin/SparkServices.cpp +++ b/src/lib/plugin/SparkServices.cpp @@ -11,16 +11,22 @@ struct SparkServices::PImpl { }; SparkServices::SparkServices(orderman::DynamicOrderRegistry &r) - : me(new PImpl(r)) {} + : me(new PImpl(r)) {} SparkServices::~SparkServices() {} void SparkServices::register_dynamic_order( - api::orderman::DynamicOrderDescriptor const &desc, - std::function()> const &builder) { + api::orderman::DynamicOrderDescriptor const &desc, + std::function()> const &builder) { me->dyn_order_registry.register_dynamic_order(desc, builder); } +void SparkServices::register_dynamic_algo_order( + api::orderman::DynamicOrderDescriptor const &desc, + std::function()> const &builder) { + me->dyn_order_registry.register_dynamic_algo_order(desc, builder); +} + extern "C" void initialize_spark_plugin(SparkServices &) {} } // namespace bts diff --git a/src/lib/plugin/SparkServices.h b/src/lib/plugin/SparkServices.h index 36f13df24..70de0c9cf 100644 --- a/src/lib/plugin/SparkServices.h +++ b/src/lib/plugin/SparkServices.h @@ -8,7 +8,8 @@ namespace bts { namespace orderman { -class DynamicOrder; +class Order; +class IAlgoOrder; class DynamicOrderRegistry; } // namespace orderman @@ -19,8 +20,11 @@ class SparkServices { void register_dynamic_order( api::orderman::DynamicOrderDescriptor const &desc, - std::function()> const &builder); + std::function()> const &builder); + void register_dynamic_algo_order( + api::orderman::DynamicOrderDescriptor const &desc, + std::function()> const &builder); private: struct PImpl; std::unique_ptr me; diff --git a/src/lib/plugin/plugin.cpp b/src/lib/plugin/plugin.cpp index 67e1ab16e..5cab0e815 100644 --- a/src/lib/plugin/plugin.cpp +++ b/src/lib/plugin/plugin.cpp @@ -1,14 +1,14 @@ #include "lib/logging/logging.h" -#include "lib/logging/logging.h" #include "lib/orderman/actors/order_manager/OrderBuilder.h" -#include "lib/utils/PBUtils.h" #include "lib/plugin/SparkServices.h" +#include "lib/utils/PBUtils.h" +#include "lib/config/config.h" +#include "lib/config/protos/system.pb.h" #include #include #include - namespace bts { namespace plugin { @@ -16,8 +16,10 @@ using namespace bts::orderman; void init_plugins(SparkServices &services) { - static std::vector(boost::filesystem::path(),""))> keep_alive; - + static std::vector( + boost::filesystem::path(), ""))> + keep_alive; + auto plugin_path = os::sparkd_wd() + "/plugins/"; if (!boost::filesystem::is_directory(plugin_path)) { LOG(Plugin, Info, @@ -32,6 +34,15 @@ void init_plugins(SparkServices &services) { auto &f = *iter; auto pl = f.path().string(); + + if (pl == "order_plugin_example.so" && + config::get().type() != "dev") { + LOG(Plugin, Info, + "Skipping order_plugin_example.so because we are not running in dev mode", + plugin_path); + continue; + } + LOG(Plugin, Info, "Attempting to initialize plugin {}", pl); try { auto init_plugin = boost::dll::import( diff --git a/src/lib/sparkproto/SparkProtos.proto b/src/lib/sparkproto/SparkProtos.proto index 08ad8512c..bcc2830d0 100644 --- a/src/lib/sparkproto/SparkProtos.proto +++ b/src/lib/sparkproto/SparkProtos.proto @@ -65,6 +65,11 @@ message QuoteParams QuoteMaxOrderMove quote_max_order_move = 1040; QuoteHidden quote_hidden = 1050; ConditionalQuoting conditional_quoting=1060; + // default value 0, 1 means we will have one trailing + // order behind the top level + // (once we have ChildOrder's here, we can reture this + // and the user can embed a QHO here) + uint32 n_queue_holder_orders=2000; } /*************************************Quote MuteZone*********************************** @@ -450,6 +455,13 @@ message PostHedgeOppositeMarketVolumeBasedForcedCross uint32 cross_ticks = 20; } +message ExecutionStrategy +{ + bool deleted = 1; + map leg_params_map = 20; + bool cancel_hedges_on_cancel = 30; +} + // EVERYTHING BELOW THIS LINE IS OBSOLETE // obsolete @@ -477,329 +489,4 @@ message StopLimitOrder { // obsolete message IcebergOrder { uint32 show_quantity = 20; -} -message ExecutionStrategy -{ - bool deleted = 1; - map leg_params_map = 20; - bool cancel_hedges_on_cancel = 30; -} -// obsolete -message PriceType -{ - enum Status - { - BID = 0; - ASK = 1; - LTP = 2; - } - - Status status = 10; -} - -// obsolete -message PriceOffset -{ - PriceType price_type = 10; - int32 offset_in_ticks = 20; -} - -// obsolete -message OrderTime -{ - oneof Time - { - uint64 absolute_time = 10; - uint64 offset_from_now = 20; - bool now = 30; - } -} - -// /********** Trigger Data **********/ - -// obsolete -message TrailingTrigger -{ - PriceType price_type = 10; - int32 number_of_ticks = 20; - oneof TriggerType - { - bool stop = 30; - bool invserse_stop = 40; - } -} - -// obsolete -message QuantityTrigger -{ - QuantityMeasure quantity_measure = 10; - oneof Relation - { - bool less_than_equalto = 20; - bool greater_than_equalto = 30; - } - uint32 threshold_quantity = 40; -} - -// obsolete -message AbsolutePriceTrigger -{ - PriceType price_type = 10; - double trigger_price = 20; - QuantityTrigger quantity_trigger = 30; -} - -// obsolete -message PriceTrigger -{ - oneof Trigger - { - TrailingTrigger trailing_trigger = 10; - AbsolutePriceTrigger absolute_price_trigger = 20; - } -} - -// /***************************************BTS ShootTillHit******************************************* -// This is the equivelant of TT's Retry Order. This Order keeps submitting a child order at a specified -// interval until it is either accepted or rejected a specified max number of times. This is used to get a -// favorable position in queue before open. -// Spreader: Not supported (legging risk of one leg getting accepted ?) -// */ - -// obsolete -message BTSShootTillHitParameters -{ - uint32 max_number_of_tries = 10; - uint32 time_between_retries_micro_seconds = 20; - /// This could be a specific time, now, or offset from now - OrderTime order_entry_time = 30; -} - -// obsolete -message BTSShootTillHitOrder -{ - /// Only support a limit or market as Retry's - /// We can make Retry a general parameter for - /// every order - oneof NativeOrderType - { - MarketOrder market_order = 10; - LimitOrder limit_order = 20; - } - BTSShootTillHitParameters shoot_till_hit_parameters = 30; -} - -// /*************************************************************************************************/ - - -// /****************************BTS With a Tick (general parameter)********************************** -// This order wraps around a limit order that is automatically repriced one tick towards the inside market -// i. When the best available price to trade is more than one tick away from the limit price -// ii. When the best available price is one tick away and the size falls below a certain threshold -// The idea is that instead of chasing the market (and cross it), you submit it away from the market and only -// cross the market when the liquidity of the opposite side drops below a threshold. -// */ - -// obsolete -message BTSWithATickParameters -{ - QuantityMeasure quantity_threshold = 10; -} - -// obsolete -message BTSWithATickOrder -{ - BTSWithATickParameters order_parameters = 10; - oneof NativeOrderType - { - LimitOrder limit_order = 20; - } - /// The price can also be submitted as an offset from B/A/LTP - /// instead of an asbolute price - PriceOffset price_offset = 30; -} - -// /*************************************************************************************************/ - -// /***************************************BTS Timed Window(general parameters)*********************** -// This order wraps a Limit or Market order in a Timed Window ie sends the order to the market -// at the Start Time (absolute or relative). At the Stop Time, it performs the End Action for -// which there is only one option, Cancel -// */ - -// obsolete -/// This can also be a general parameter -message BTSTimedWindowParameters -{ - OrderTime start_time = 10; - OrderTime stop_time = 20; - oneof EndAction - { - bool cancel = 30; - } -} - -// obsolete -message BTSTimedWindowOrder -{ - BTSTimedWindowParameters order_parameters = 10; - oneof NativeOrderType - { - MarketOrder market_order = 20; - LimitOrder limit_order = 30; - } - // The price can also be submitted as an offset from B/A/LTP - /// instead of an asbolute price - PriceOffset price_offset = 40; - BTSWithATickParameters withatick_parameters = 50; /// optional -} - -// /*************************************************************************************************/ - -// /***************************************BTS Trailing Limit**************************************** -// Submits a limit order at a fixed distance from the market. It is repriced relative to the market. -// Trailing orders are always set better than the current market (hence ticks can not be negative). So -// for a bid order, it’s submitted a fixed number of ticks below the market. If the market goes up, -// the order moves higher. If the market goes down the order price is not adjusted. -// (However, when orders are submitted relative to LTP, they can better the market, and get filled -// immediatly) -// */ - -// obsolete -message BTSTrailingLimitOrder -{ - PriceOffset price_offset = 10; - BTSTimedWindowParameters optional_timed_parameters = 20; -} - -// /*************************************************************************************************/ - -// /***************************************BTS Stop ************************************************* -// Conditional order to buy when the price rises to a designated price level (or sell when it falls). -// Buy stop orders are placed above the market and sells below. The trigger price (also called stop price) -// can be an -// i. Absolute price from where the user clicks on the ladder -// ii. Trailing price that trails the market by a constant amount (for buy orders, trigger price goes down -// as the market goes down, so the market penetrates the trigger price on its way up). -// When the market penetrates the trigger price, a limit order is sent "payup" ticks away form B/A/LTP -// */ - -// obsolete -message BTSStopOrder -{ - PriceTrigger price_trigger = 10; - oneof NativeTriggerOrderType - { - MarketOrder market_order = 20; - LimitOrder limit_order = 30; - } - oneof TriggerOrderPrice - { - PriceOffset payup = 40; - double price = 50; - } - BTSWithATickParameters optional_withatick_parameters = 60; - BTSTimedWindowParameters optional_timed_parameters = 70; -} - -// /*************************************************************************************************/ - -// /***************************************BTS IfTouched ******************************************** -// Opposite of BTS Stop (Both in terms of where the order is placed, and how it trails the market -// */ - -// obsolete -message BTSIfTouchedOrder -{ - PriceTrigger price_trigger = 10; - oneof NativeTriggerOrderType - { - MarketOrder market_order = 20; - LimitOrder limit_order = 30; - } - oneof OrderPrice - { - PriceOffset payup = 40; - double price = 50; - } - BTSWithATickParameters optional_withatick_parameters = 60; - BTSTimedWindowParameters optional_timed_parameters = 70; -} - -// /*************************************************************************************************/ - -// /***************************************BTS Iceberg*********************************************** -// Breaks a large order into smaller disclosed orders, each of which is sent after the -// previous has been filled. -// */ - -// obsolete -message BTSIcebergOrder -{ - QuantityMeasure display_quantity = 10; - oneof ChildOrderOffset - { - PriceOffset market_offset = 20; - double diff_from_last_fill = 30; - } - /// Optional Parameters - BTSWithATickParameters withatick_parameters = 40; - PriceTrigger price_trigger = 60; - BTSTimedWindowParameters timed_window_parameters = 70; -} - -// /*************************************************************************************************/ - -// /***************************************BTS TimeSlice*************************************/ - -// obsolete -message BTSTimeSliceOrder -{ - double interval = 10; - QuantityMeasure display_quantity = 20; - oneof ChildOrderType - { - MarketOrder market_order = 30; - LimitOrder limit_order = 40; - } - PriceOffset child_order_offset = 50; - /// the earlier order can either be left, or its - /// price moved toward the inside market by payup_ticks - oneof LeftOverAction - { - bool leave = 60; - double payup_ticks = 70; - } - /// Optional Parameters - BTSWithATickParameters withatick_parameters = 80; - BTSTimedWindowParameters timed_window_parameters = 90; - PriceTrigger price_trigger = 100; -} - -// /*************************************************************************************************/ - -// /***************************************BTS OCO*********************************************** -// Sends a Stop-Loss and a Limit order of the same quantity at different price levels for the same -// security. For buy's the Limit is sent at a lower price level. -// i. A fill in the limit order decreases the size of the Stop Order. -// ii. If the stop order is trigerred, the Limit order is cancelled -// */ - -// obsolete -message BTSOCOOrder -{ - PriceTrigger price_trigger = 10; - oneof NativeTriggerOrderType - { - MarketOrder market_order = 20; - LimitOrder limit_order = 30; - } - oneof OrderPrice - { - PriceOffset payup = 40; - double price = 50; - } - BTSWithATickParameters optional_withatick_parameters = 60; - BTSTimedWindowParameters optional_timed_parameters = 70; - /// The price for the limit order is in the main order object -} +} \ No newline at end of file diff --git a/src/lib/tracing/PerfLog.cpp b/src/lib/tracing/PerfLog.cpp index 78980b5bb..70c16e58e 100644 --- a/src/lib/tracing/PerfLog.cpp +++ b/src/lib/tracing/PerfLog.cpp @@ -23,6 +23,16 @@ namespace bts { namespace trace { + +const char* PerfLog::get_thread_name() +{ + char *thread_name_buffer = new char[17]; + pthread_getname_np(pthread_self(), thread_name_buffer,16); + return thread_name_buffer; +} + +thread_local char const * PerfLog::_thread_name_ptr = get_thread_name(); + auto insert_trace = "insert into trace (" "session_start," "ts," @@ -297,9 +307,7 @@ size_t PerfLog::flush_current_batch_to_disk() { me->insert_trace_statement->bind(":uint64_1", (long long)ev.uint64_1); me->insert_trace_statement->bind(":cor_event", (long long)ev.cor_event.to_uint64()); - char tn[17]; - pthread_getname_np(ev.thread_id, tn, BTS_ARRAYSIZE(tn) - 1); - me->insert_trace_statement->bind(":thread", tn); + me->insert_trace_statement->bind(":thread", ev.thread_name); me->insert_trace_statement->exec(); count++; me->insert_trace_statement->reset(); diff --git a/src/lib/tracing/PerfLog.h b/src/lib/tracing/PerfLog.h index 749351232..4a42c77ef 100644 --- a/src/lib/tracing/PerfLog.h +++ b/src/lib/tracing/PerfLog.h @@ -19,7 +19,7 @@ struct PerfLogEntry { const char *entry_kind; const char *txt_1; uint64_t uint64_1; - pthread_t thread_id; + const char* thread_name; utils::TimeStamp cor_event; uint32_t sn; uint32_t uint32_1; @@ -27,6 +27,8 @@ struct PerfLogEntry { class PerfLog { tbb::concurrent_queue _pending; + static thread_local const char* _thread_name_ptr; + bool _disabled; struct PImpl; std::unique_ptr me; @@ -39,7 +41,7 @@ class PerfLog { void log(CorID cid, const char *entry_kind, uint64_t uint64_1 = 0, const char *txt_1 = "", uint32_t uint32_1 = 0) { _pending.push({utils::TimeStamp::now(), cid.channel, entry_kind, txt_1, - uint64_1, pthread_self(), utils::TimeStamp(), cid.sn, + uint64_1, _thread_name_ptr, utils::TimeStamp(), cid.sn, uint32_1}); } @@ -47,20 +49,20 @@ class PerfLog { uint64_t uint64_1 = 0, const char *txt_1 = "", uint32_t uint32_1 = 0) { _pending.push({ts, cid.channel, entry_kind, txt_1, uint64_1, - pthread_self(), utils::TimeStamp(), cid.sn, uint32_1}); + _thread_name_ptr,utils::TimeStamp(), cid.sn, uint32_1}); } void log(CorID cid, utils::TimeStamp ts, utils::TimeStamp ts2, const char *entry_kind, uint64_t uint64_1 = 0, const char *txt_1 = "", uint32_t uint32_1 = 0) { _pending.push({ts, cid.channel, entry_kind, txt_1, uint64_1, - pthread_self(), ts2, cid.sn, uint32_1}); + _thread_name_ptr,ts2, cid.sn, uint32_1}); } void flush() { _pending.push({utils::TimeStamp(), nullptr, nullptr, nullptr, 0, - pthread_self(), utils::TimeStamp(), 0, 0}); + _thread_name_ptr,utils::TimeStamp(), 0, 0}); } void log(PerfLogEntry const &e) { _pending.push(e); } @@ -78,6 +80,8 @@ class PerfLog { size_t flush_current_batch_to_disk() ; bool is_flush_signal(PerfLogEntry const&); void init_db(); + static const char*get_thread_name(); + friend class ScopedPerfLogEntry; }; class ScopedPerfLogEntry { @@ -92,7 +96,7 @@ class ScopedPerfLogEntry { entry_kind, txt_1, uint64_1, - pthread_self(), + l._thread_name_ptr, utils::TimeStamp(), cid.sn, uint32_1} { @@ -108,7 +112,7 @@ class ScopedPerfLogEntry { entry_kind, txt_1, uint64_1, - pthread_self(), + l._thread_name_ptr, utils::TimeStamp(), cid.sn, uint32_1} { } diff --git a/src/lib/utils/ConcurrentPool.h b/src/lib/utils/ConcurrentPool.h index 92d86e7ea..c0f9851bd 100644 --- a/src/lib/utils/ConcurrentPool.h +++ b/src/lib/utils/ConcurrentPool.h @@ -8,7 +8,7 @@ namespace utils { template class ConcurrentPool { - tbb::concurrent_vector> _all; + tbb::concurrent_vector _all; tbb::concurrent_queue _free; size_t _initial_size; size_t _grow_size; @@ -19,7 +19,10 @@ class ConcurrentPool { reserve(initial_size); } - ~ConcurrentPool() { } + ~ConcurrentPool() { + for (auto b : _all) + delete [] b; + } T* allocate() { T* result = nullptr; @@ -34,13 +37,13 @@ class ConcurrentPool { } void reserve(size_t count) { - std::unique_ptr buffer {new T[count]}; + auto buffer = new T[count]; _outstanding += count; for (size_t x = 0; x < count; ++x) { T* temp = &buffer[x]; release(&temp); } - _all.push_back(std::move(buffer)); + _all.push_back(buffer); } void release(T** item) { @@ -57,8 +60,7 @@ class ConcurrentPool { for (auto iter = _all.begin(); iter != _all.end(); ++iter) { size_t size = (iter == _all.begin()) ? _initial_size : _grow_size; for (size_t x = 0; x < size; ++x) { - const std::unique_ptr& bucket = *iter; - const T* start = bucket.get(); + const T* start = *iter; cb(start[x]); } } diff --git a/src/lib/utils/Puid.h b/src/lib/utils/Puid.h index f4e7a8538..2340320a9 100644 --- a/src/lib/utils/Puid.h +++ b/src/lib/utils/Puid.h @@ -26,8 +26,8 @@ BTS_EXPORT Puid gen_puid (std::string const &scope); // machines) BTS_EXPORT std::vector gen_ids (std::string const &scope, int n_ids); // Similar to the above but instead of copying the ids to a vector -// this simply the first free id (x) and skips ahead by n_ids so that the -// next gen_id call will will be x+n_ids +// this simply returns the first free id (x) and skips ahead by n_ids +// so that the next gen_id call will will be x+n_ids BTS_EXPORT uint64_t reserve_ids (std::string const &scope, int n_ids); // generate a single id BTS_EXPORT uint64_t gen_id (std::string const &scope); diff --git a/src/lib/utils/SharedList.h b/src/lib/utils/SharedList.h index 345055ebf..9a47e2701 100644 --- a/src/lib/utils/SharedList.h +++ b/src/lib/utils/SharedList.h @@ -15,8 +15,10 @@ #include #include #include +#include #include +#include namespace bts { namespace utils { @@ -238,6 +240,38 @@ public: offset = sizeof(SegmentHeader); } } + + void dump_to(const char* directory) const { + using namespace std; + boost::system::error_code _; + if (!boost::filesystem::exists(directory, _)) { + boost::filesystem::create_directories(directory, _); + } + + if (!boost::filesystem::is_directory(directory)) { + LOG(md,Error, "Error dumping memory to {}", std::string(directory)); + return; + } + + boost::filesystem::path root(directory); + + // OK to hold the lock for a while as we're typically crashing when this is called + tbb::queuing_mutex::scoped_lock lock(_mutex); + + for (size_t x = 0; x < _segments.size(); ++x) { + char segment_name[512]; + SharedList::get_segment_name(segment_name, BTS_ARRAYSIZE(segment_name), _name, x); + + // create/overwrite output file + std::ofstream writer( (root/segment_name).string(), ios::out | ios::app | ios::binary); + if (writer.is_open()) { + // writer just loves signed types + writer.write( + (const char*)_segments[x].address, + (std::streamsize)_segments[x].size); + } + } + } private: BTS_NO_COPY(SharedListReader); @@ -281,7 +315,7 @@ private: const std::string _name; THeader* _header; // null value indicates no memory segment - tbb::queuing_mutex _mutex; + mutable tbb::queuing_mutex _mutex; std::unique_ptr _shm; std::vector _segments; }; diff --git a/src/sdk/README.md b/src/sdk/README.md index 51dbde907..63a91c61b 100644 --- a/src/sdk/README.md +++ b/src/sdk/README.md @@ -1,6 +1,6 @@ -# BTS Spark +# BTS Spark -Our offering consists of a client UI ([Spark Client](https://www.bluetradingsystems.com/bts-spark#ladder-algo-screen)), a high performance professional futures front end, connected via our proprietary protocol over TCP to our Spark Server, which in turn connects to execution venues via their native protocols (typically FIX/TCP for execution and some proprietary protocol over UDP multicast for market data). +Our offering consists of a client UI ([Spark Client](https://www.bluetradingsystems.com/bts-spark#ladder-algo-screen)), a high performance professional futures front end, connected via our proprietary protocol over TCP to our Spark Server, which in turn connects to execution venues via their native protocols (typically FIX/TCP for execution and some proprietary protocol over UDP multicast for market data). ![alt text](https://www.bluetradingsystems.com/images/Images/api/API.png) @@ -41,20 +41,20 @@ $ docker run \ -i \ -t bluetradingsystems/linux_docker \ /bin/bash - -``` + +``` * Note that the lifetime of docker instance above is tied to the life of the shell instance, so if you exit bash, the container stops running. To start and re-attach to the container, use: ``` $ docker start --attach -i bts_sdk ``` - * If you prefer to run docker as a daemon, check out [``~/spark_sdk/sdk_shell.sh``](sdk_shell.sh) - + * If you prefer to run docker as a daemon, check out [``~/spark_sdk/sdk_shell.sh``](sdk_shell.sh) + ### Git * We assume the git you are using is git-lfs compatible; if you're using the git that comes with our docker, you're all set. -* else go here: https://github.com/git-lfs/git-lfs/wiki/Installation +* else go here: https://github.com/git-lfs/git-lfs/wiki/Installation Now that you're ssh'd into the docker container, clone the repo into ```~/spark_sdk/``` and cd to that directory @@ -67,9 +67,9 @@ $ cd spark_sdk ### Development -Look at [examples/md_publisher_example.cpp](examples/md_publisher_example.cpp) to look at how to build a custom market data producer +Algo Orders typically implement the [IAlgoOrder](include/spark/lib/orderman/orders/algo/IAlgoOrder.h) interface to respond to events and use the [IAlgoServices](include/spark/lib/orderman/orders/algo/IAlgoServices.h) interface to create and control child orders as well as manage their own life cycles. See [examples/order_plugin_example.cpp](examples/order_plugin_example.cpp) for a fully fledged example -Look at [examples/order_plugin_example.cpp](examples/order_plugin_example.cpp) to look at how to create custom algos. +Look at [examples/md_publisher_example.cpp](examples/md_publisher_example.cpp) to look at how to build a custom market data producer run ```build_examples.sh``` to make sure you can build the examples, this will produce an ```order_plugin_example.so``` @@ -79,20 +79,20 @@ $ ./build_examples.sh ``` #### Server Layout * Spark servers reside on a port, usually 8000, but your production instance could be on a different $PORT - + ##### SDK Package Layout * The sdk puts logs in ``~/sparkdata/data/logging/log`` * The sdk package has binaries in ``spark_skd/lib`` * Put plugins in ``spark_sdk/lib/plugins/`` for debugging ##### Production layout -* Production Logs are in ``~/$PORT/sparkdata/data/logging/log`` on the host +* Production Logs are in ``~/$PORT/sparkdata/data/logging/log`` on the host * Production binaries are in ``/sparkbin`` inside the docker container * Production algo plugins should go into the ``/sparkbin/plugins`` directory #### Recorded market data * We first check for http://mdreplay/spark/futures.coconut - + * Then fall back to ``./data_files/ relative to the sparkd binary`` ## Debugging @@ -109,7 +109,7 @@ In gdb: * https://darkdust.net/files/GDB%20Cheat%20Sheet.pdf ``` -(gdb) break order_plugin_example.cpp:366 +(gdb) break order_plugin_example.cpp:366 ``` ## Running without debugger @@ -119,7 +119,7 @@ $ cp -f order_plugin_example.so ~/spark_sdk/lib/plugins/ $ cd ~/spark_sdk/lib $ ./sparkd run ``` - + ## Connect to Admin (Risk) UI to set limits or add users * Browse to http://location:$PORT * Login as bts, no password @@ -144,6 +144,6 @@ $ ./sparkd run ``` include: "http://location:$PORT/config/" ``` - - ## Download the Spark windows client + + ## Download the Spark windows client * Download the bts installer here: diff --git a/src/sdk/examples/order_plugin_example.cpp b/src/sdk/examples/order_plugin_example.cpp index 03de5fa67..82747faea 100644 --- a/src/sdk/examples/order_plugin_example.cpp +++ b/src/sdk/examples/order_plugin_example.cpp @@ -1,12 +1,13 @@ -#include "spark/lib/logging/logging.h" -#include "spark/lib/orderman/orders/DynamicOrder.h" +#include "spark/lib/config/config.h" +#include "spark/lib/config/protos/system.pb.h" +#include "spark/lib/domain_model/Security.h" +#include "spark/lib/orderman/orders/algo/IAlgoOrder.h" +#include "spark/lib/orderman/orders/algo/IAlgoServices.h" #include "spark/lib/plugin/SparkServices.h" -#include "spark/lib/orderman/actors/order_manager/ChildOrder.h" -#include "spark/lib/orderman/actors/order_manager/OrderBuilder.h" -#include "spark/lib/orderman/orders/DynamicOrder.h" + +#include "spark/lib/orderman/order_factory/IOrderFactory.h" +#include "spark/lib/orderman/orderman_utils/Book.h" #include "spark/lib/utils/PBUtils.h" -#include "lib/config/protos/system.pb.h" -#include "lib/config/config.h" using namespace bts::api::orderman; using namespace bts::orderman; @@ -14,376 +15,317 @@ using namespace bts::orderman; namespace bts { namespace order_example { -class DynamicIcebergOrder : public DynamicOrder { +// Join starts working N ticks away from the market (usually) and then +// watches for the opposite inside to become same side inside market; +// if there is then enough size on that market, it will join. +class DynamicJoin : public IAlgoOrder { public: - DynamicIcebergOrder(); - ~DynamicIcebergOrder(); - OrderDefinition const &definition() const override; - void on_init_new(OrderDefinition const &, - const PreActivationOrderServices &) override; - void on_init_recovered(OrderRecord const &, - const PreActivationOrderServices &) override; - void on_activate(Price, Quantity, OrderServices &, - trace::CorID const&) override; - void on_update(Price, Quantity, trace::CorID const&) override; - void on_crack(trace::CorID const &) override; - void on_cancel(trace::CorID const &) override; + DynamicJoin(); + ~DynamicJoin(); + + OrderOpResult do_before_launch(IBeforeLaunchAlgoServices &) override; + void do_launch(IAlgoServices &) override; + void do_launch_attached(IAlgoServices &, OrderKey, ChildState) override; + void do_update(api::orderman::Update const &) override; + void on_book(SecurityKey, Book const &) override; + void on_child_change(OrderKey, ChildState const &) override; private: - void report_state(); - void send_next_child_order(); - - void merge_states(OrderState const &iceberg_state, - OrderState const &child_state, OrderState *merged); - - void on_child_order_update(OrderStateUpdateEvent const &); - void transition(OrderStatus new_state, std::string const &msg); - void transition(OrderStatus new_state); - - struct ActiveChild; + enum class Status; struct PImpl; std::unique_ptr me; + + IAlgoServices &algo_services() const; + void try_to_join(); }; -struct DynamicIcebergOrder::ActiveChild { - ActiveChild() {} - ChildOrder order; - api::orderman::OrderState state; - void clear() { state = api::orderman::OrderState(); } +// The three stages our algo goes through. We start by waiting to +// observe the book for our security (WAITING_FOR_MD). Once we have a +// book we use it to derive our target price and we continue to +// monitor the book to see if we should join the market +// (WAITING_TO_JOIN). Once the size and price constraints are met we +// jump to the target price (JOINED). We remain in the JOINED state +// until our order is filled or canceled. +enum class DynamicJoin::Status { WAITING_FOR_MD, WAITING_TO_JOIN, JOINED }; + +// All state information needed for this algo +struct DynamicJoin::PImpl { + IAlgoServices *algo_services; + Quantity min_quantity_to_join; + Status status = Status::WAITING_FOR_MD; + OrderKey child_key = null_order_key(); + ChildTemplate *child_template = nullptr; + Book book_at_inception; + Book last_book; }; -struct DynamicIcebergOrder::PImpl { - PImpl() : services(nullptr), child() {} +DynamicJoin::DynamicJoin() : me(new PImpl()) {} +DynamicJoin::~DynamicJoin() {} +IAlgoServices &DynamicJoin::algo_services() const { return *me->algo_services; } - OrderServices *services; - api::orderman::OrderDefinition def; - api::orderman::OrderState state; - OrderBuilder child_builder; - ActiveChild child; - Quantity show_quantity; -}; +// This is called outside of the latency sensitive path +// once. Expensive initialization should be done here, rather than +// in do_launch() +OrderOpResult DynamicJoin::do_before_launch(IBeforeLaunchAlgoServices &serv) { + auto &def = serv.definition(); + bts_assert(def.has_custom_def()); + bts_assert(def.custom_def().has_dynamic()); -DynamicIcebergOrder::DynamicIcebergOrder() : me(new PImpl()) {} -DynamicIcebergOrder::~DynamicIcebergOrder() {} -api::orderman::OrderDefinition const &DynamicIcebergOrder::definition() const { - return me->def; -} + // Validate our parameters, returning an error if we find a + // problem. If an error is returned here the order will be + // abandoned. + auto ¶ms = def.custom_def().dynamic().order_params(); + auto mqi = params.find("Min Quantity"); + if (mqi == params.end() || mqi->second.as_uint32() == 0) + return OrderOpResult{ + ORDER_ERROR_INVALID_ORDER_DEFINITON, + "Min Quantity parameter must be defined and non zero"}; -void DynamicIcebergOrder::on_init_new( - api::orderman::OrderDefinition const &def, - const PreActivationOrderServices &services) { - me->def = def; - me->state.mutable_dynamic(); + me->min_quantity_to_join = Quantity(mqi->second.as_uint32()); - auto const &iceberg_def = def.custom_def().dynamic(); - me->show_quantity = - Quantity(iceberg_def.order_params().at("show_size").as_uint32()); + if (!serv.is_attaching()) { + // If we are not attaching, create a child template so we can + // quickly launch our child when the time comes. - auto child_def = def; - *child_def.mutable_custom_def() = - iceberg_def.order_params().at("child").as_order_def(); - if (me->show_quantity.value() != 0) { - me->child_builder = OrderBuilder( - key(), child_def, services, - std::max((size_t)1, (size_t)(me->show_quantity).value() / 10)); - transition(ORDER_STATUS_INACTIVE); + // We will be sending a limit order with the same side, + // security, trader, account, etc, as this algo order, so just + // copy our definition to the child definition to start with. + auto child_def = def; + // Now add a limit order component to mark our child as a limit + // order. Limit orders do not require any extra parameters + // beyond those already inherited from this algo order + // (i.e. beyond what we obtained through serv.definition()) so + // we can just use a default constructed LimitOrderDefinition. + *child_def.mutable_custom_def()->mutable_limit() = LimitOrderDefinition{}; + // Now just build the child template and cache it for future use + me->child_template = &(serv.make_child_template(child_def)); } else { - auto msg = fmt::format("Show quantity must be greater than 0"); - me->state.set_last_msg(msg); - transition(ORDER_STATUS_REJECTED_BY_SPARK, msg); + // If we are attaching to an existing order then we do not need + // to spawn a new child, so there is no need to setup a child + // template } + + // All is good, return a default constructed OrderOpResult which + // indicates success. + return {}; } -void DynamicIcebergOrder::on_init_recovered( - api::orderman::OrderRecord const &rec, const PreActivationOrderServices &) { - auto const &def = rec.def(); - me->def = def; - me->state = rec.state(); +// Called in the latency sensitive path, once, when the algo is first +// launched. +void DynamicJoin::do_launch(IAlgoServices &services) { + // Cache our algo services + me->algo_services = &services; - switch (me->state.status()) { + LOG(OrderMan, Diag, "Lauching DynamicJoin k: {} ", + algo_services().order_key().value()); - case ORDER_STATUS_WORKING: - case ORDER_STATUS_DISCONNECTED: { - auto msg = "System restarted with active iceberg order"; - me->state.set_last_msg(msg); - transition(ORDER_STATUS_ERROR, msg); - break; + // Launch our child order + me->child_key = + services.launch_child(*me->child_template, algo_services().price(), + algo_services().quantity()); + + // Subscribe to market data + services.subscribe_book(SecurityKey(algo_services().security().id())); +} + +// Called in the latency sensitive path, once, when the algo is first +// launched. In this case the algo is provided with an existing order +// it is now responsible for managing. +void DynamicJoin::do_launch_attached(IAlgoServices &services, + OrderKey attached_order, ChildState st) { + // The order was launched and attached to an existing order, with + // key 'attached_order' and current state 'st' + + // Cache our algo services + me->algo_services = &services; + + LOG(OrderMan, Diag, + "Lauching DynamicJoin k: {} Attached to existing order: {}", + algo_services().order_key().value(), attached_order.value()); + + // Cache the key of the attached order we will be managing + me->child_key = attached_order; + + // Subscribe to market data + services.subscribe_book(SecurityKey(services.security().id())); + + // Simulate a child change so we can update our own state to + // reflect that of the child order we attached to. From this point + // forward there is no distinction between an algo instance that + // spawned a new child order and one that attached to an existing + // order. + on_child_change(attached_order, st); +} + +// Called when a human (or a supervising algo) updates a parameter for +// this algo. The implementation validates the update and depending on +// the validation outcome either applies the update or terminates the +// algo. +void DynamicJoin::do_update(api::orderman::Update const &update) { + LOG(OrderMan, Diag, "DynamicJoin k: {} receiving update: {}", + algo_services().order_key().value(), utils::pb::to_string(update)); + + // Validate update + if (update.quantity() == 0) { + // An invalid update has been detected so we terminate the + // algo, signaling an error. Any child orders launched by + // this algo will also be terminated. + algo_services().terminate_error("Invalid update"); + return; } - // terminal states - case ORDER_STATUS_ERROR: - case ORDER_STATUS_REJECTED_BY_SPARK: - case ORDER_STATUS_COMPLETED: - case ORDER_STATUS_CANCELED: - break; - case ORDER_STATUS_PENDING_WORKING: - case ORDER_STATUS_INACTIVE: - case OrderStatus_INT_MIN_SENTINEL_DO_NOT_USE_: - case OrderStatus_INT_MAX_SENTINEL_DO_NOT_USE_: - bts_assert(false); - break; - } -} + // Updates have two parts, a standard part consisting of price and + // size and present in all updates, and an optional part that is + // specific to the algo in question. Below we check for the + // existance of this optional part and validate if present. + bool has_new_min_qty = false; + if (update.has_custom()) { + auto ¶ms = update.custom().dynamic().order_params(); + auto mqi = params.find("Min Quantity"); -void DynamicIcebergOrder::on_activate(Price p, Quantity q, - OrderServices &services, - trace::CorID const &) { - bts_assert(!me->services); - me->services = &services; - me->child_builder.activate(services); - - switch (me->state.status()) { - case ORDER_STATUS_INACTIVE: - me->state.set_price(p.value()); - me->state.set_quantity(q.value()); - services.subscribe_to_child_updates( - [this](auto const &os) { this->on_child_order_update(os); }); - transition(ORDER_STATUS_WORKING); - send_next_child_order(); - break; - - // these are not possible since the on_init_recovered code - // would have transitioned us to error already - case ORDER_STATUS_WORKING: - case ORDER_STATUS_PENDING_WORKING: - case ORDER_STATUS_DISCONNECTED: { - bts_assert(false); - break; - } - // terminal states - case ORDER_STATUS_ERROR: - case ORDER_STATUS_REJECTED_BY_SPARK: - case ORDER_STATUS_COMPLETED: - case ORDER_STATUS_CANCELED: - break; - case OrderStatus_INT_MIN_SENTINEL_DO_NOT_USE_: - case OrderStatus_INT_MAX_SENTINEL_DO_NOT_USE_: - bts_assert(false); - break; - } - report_state(); -} - -void DynamicIcebergOrder::on_update(Price p, Quantity q, trace::CorID const &) { - switch (me->state.status()) { - case ORDER_STATUS_WORKING: - case ORDER_STATUS_PENDING_WORKING: - LOG(Plugin, Info, - "Updating DynamicIceberg order {} to price {} quantity {}", - key().value(), p.value(), q.value()); - me->state.set_price(p.value()); - me->state.set_quantity(q.value()); - break; - case ORDER_STATUS_DISCONNECTED: - case ORDER_STATUS_REJECTED_BY_SPARK: - case ORDER_STATUS_COMPLETED: - case ORDER_STATUS_CANCELED: - case ORDER_STATUS_ERROR: - transition(me->state.status(), "Cannot update order"); - break; - - case ORDER_STATUS_INACTIVE: - case OrderStatus_INT_MIN_SENTINEL_DO_NOT_USE_: - case OrderStatus_INT_MAX_SENTINEL_DO_NOT_USE_: - bts_assert(false); - break; - } - report_state(); -} - -void DynamicIcebergOrder::on_crack(trace::CorID const &) {} - -void DynamicIcebergOrder::on_cancel(trace::CorID const &) { - switch (me->state.status()) { - case ORDER_STATUS_WORKING: - LOG(Plugin, Info, "Canceling DynamicIceberg Order {}", key().value()); - me->child.order.cancel(); - transition(ORDER_STATUS_CANCELED); - break; - case ORDER_STATUS_PENDING_WORKING: - case ORDER_STATUS_DISCONNECTED: - case ORDER_STATUS_REJECTED_BY_SPARK: - case ORDER_STATUS_COMPLETED: - case ORDER_STATUS_CANCELED: - case ORDER_STATUS_ERROR: - transition(me->state.status(), "Cannot cancel order"); - break; - - case ORDER_STATUS_INACTIVE: - case OrderStatus_INT_MIN_SENTINEL_DO_NOT_USE_: - case OrderStatus_INT_MAX_SENTINEL_DO_NOT_USE_: - bts_assert(false); - break; - } - report_state(); -} - -void DynamicIcebergOrder::report_state() { - if (me->child.state.filled_quantity()) { - api::orderman::OrderState merged_state; - merge_states(me->state, me->child.state, &merged_state); - me->services->report_state(merged_state); - } else - me->services->report_state(me->state); -} - -void DynamicIcebergOrder::merge_states( - api::orderman::OrderState const &iceberg_state, - api::orderman::OrderState const &child_state, - api::orderman::OrderState *merged) { - auto child_order_fills = child_state.filled_quantity(); - auto child_order_avg_price = child_state.avg_price(); - auto child_order_last_price = child_state.last_price(); - - auto iceberg_fills = iceberg_state.filled_quantity(); - auto iceberg_avg_price = iceberg_state.avg_price(); - - *merged = iceberg_state; - merged->set_filled_quantity(child_order_fills + iceberg_fills); - merged->set_last_price(child_order_last_price); - merged->set_avg_price((child_order_fills * child_order_avg_price + - iceberg_fills * iceberg_avg_price) / - (child_order_fills + iceberg_fills)); -} - -void DynamicIcebergOrder::send_next_child_order() { - bts_assert(me->state.quantity() > me->state.filled_quantity()); - - auto remaining = me->state.quantity() - me->state.filled_quantity(); - auto to_send = std::min(remaining, me->show_quantity.value()); - me->child.order = me->child_builder.build(); - LOG(Plugin, Info, - "DynamicIceberg order {} creating new child order {} with size " - "{} price {}. Filled {} so far out of {}", - key().value(), me->child.order.key().value(), to_send, me->state.price(), - me->state.filled_quantity(), me->state.quantity()); - - me->child.order.activate(Price(me->state.price()), Quantity(to_send)); -} - -void DynamicIcebergOrder::on_child_order_update( - OrderStateUpdateEvent const &ev) { - switch (me->state.status()) { - case ORDER_STATUS_WORKING: - if (ev.key == me->child.order.key()) { - me->child.state = ev.rebuild_state(); - - switch (me->child.state.status()) { - - case ORDER_STATUS_WORKING: - case ORDER_STATUS_PENDING_WORKING: - // nothing to do but report new state - break; - - case ORDER_STATUS_COMPLETED: { - api::orderman::OrderState merged_state; - merge_states(me->state, me->child.state, &merged_state); - me->state = merged_state; - me->child.clear(); - if (me->state.quantity() > me->state.filled_quantity()) - send_next_child_order(); - else - transition(ORDER_STATUS_COMPLETED); - break; - } - - case ORDER_STATUS_CANCELED: - LOG(Plugin, Info, - "Unexpected cancel of child {} in DynamicIceberg Order {}. " - "Canceling parent", - ev.key.value(), key().value()); - transition(ORDER_STATUS_CANCELED); - break; - - case ORDER_STATUS_DISCONNECTED: - case ORDER_STATUS_REJECTED_BY_SPARK: - case ORDER_STATUS_ERROR: - me->child.clear(); - transition(ORDER_STATUS_ERROR, "Unexpected child order state"); - break; - - case ORDER_STATUS_INACTIVE: - case OrderStatus_INT_MIN_SENTINEL_DO_NOT_USE_: - case OrderStatus_INT_MAX_SENTINEL_DO_NOT_USE_: - bts_assert(false); - break; - } - - } else { - LOG(Plugin, Info, - "DynamicIceberg order {} received update for non active child " - "order{} . update state = {} ", - key().value(), me->child.order.key().value(), - utils::pb::to_string(ev.rebuild_state())); + if (mqi == params.end() || mqi->second.as_uint32() == 0) { + algo_services().terminate_error( + "Minimum quantity to join must be greater than 0"); + return; } - break; + has_new_min_qty = true; + me->min_quantity_to_join = Quantity(mqi->second.as_uint32()); + } - case ORDER_STATUS_CANCELED: - case ORDER_STATUS_ERROR: - case ORDER_STATUS_DISCONNECTED: - case ORDER_STATUS_COMPLETED: - break; + // Update is good, forward it to our child + Update child_update; + child_update.set_price(update.price()); + child_update.set_quantity(update.quantity()); + algo_services().update_child(me->child_key, child_update); - case ORDER_STATUS_PENDING_WORKING: - case ORDER_STATUS_REJECTED_BY_SPARK: - case ORDER_STATUS_INACTIVE: - case OrderStatus_INT_MIN_SENTINEL_DO_NOT_USE_: - case OrderStatus_INT_MAX_SENTINEL_DO_NOT_USE_: - bts_assert(false); + // Try to join again if conditions changed + if (me->status == Status::WAITING_TO_JOIN && has_new_min_qty) + try_to_join(); +} + +// Called when the book for the specified security has changed +void DynamicJoin::on_book(SecurityKey, Book const &b) { + + // Cache the book, so we can reffer to it in the event of a + // parameter change that might allow us to join + me->last_book = b; + + LOG(OrderMan, Diag, "DynamicJoin order {} on book. BID: {}@{} ASK: {}@{}", + algo_services().order_key().value(), b.side(api::SIDE_BUY)[0].size(), + b.side(api::SIDE_BUY)[0].price(), b.side(api::SIDE_SELL)[0].size(), + b.side(api::SIDE_SELL)[0].price()); + + switch (me->status) { + case Status::WAITING_FOR_MD: { + + auto other_side = + securities::other_side(algo_services().definition().side()); + auto &other_side_top = me->last_book.side(other_side)[0]; + + if (other_side_top.size() > 0) { + // First time we get the opposite side market, we will use + // this price as the target price for the join + me->status = Status::WAITING_TO_JOIN; + me->book_at_inception = b; + LOG(OrderMan, Diag, + "JoinOrder order {} receiving first book: {} Target: {}", + algo_services().order_key().value(), + me->min_quantity_to_join.value(), other_side_top.price()); + try_to_join(); + } + } break; + case Status::JOINED: + // Nothing to do at this point + break; + case Status::WAITING_TO_JOIN: + // Check if we reached the target and join if so + try_to_join(); break; } - report_state(); } -void DynamicIcebergOrder::transition(api::orderman::OrderStatus new_status, - std::string const &msg) { - auto const &from = OrderStatus_Name(me->state.status()); - auto const &to = OrderStatus_Name(new_status); - LOG(Plugin, Info, - "Transitioning dynamic iceberg order {} from {} to {}. Msg: {}", - key().value(), from, to, msg); - me->state.set_last_msg(msg); - me->state.set_status(new_status); +// Given the current book, our target price and our min quantity +// parameter, join if appropriate +void DynamicJoin::try_to_join() { + bts_assert(me->status == Status::WAITING_TO_JOIN); + + auto my_side = algo_services().definition().side(); + auto other_side = securities::other_side(my_side); + auto &my_side_psz = me->last_book.side(my_side)[0]; + auto &opposite_at_inception_psz = me->book_at_inception.side(other_side)[0]; + + if (my_side_psz.size() && + my_side_psz.size() >= me->min_quantity_to_join.value() && + securities::is_equal_or_better( + my_side, Price(my_side_psz.price()), + Price(opposite_at_inception_psz.price()))) { + + // Time to update our child to join the market + Update child_update; + child_update.set_price(my_side_psz.price()); + child_update.set_quantity(algo_services().quantity().value()); + algo_services().update_child(me->child_key, child_update); + me->status = Status::JOINED; + + LOG(OrderMan, Diag, "DynamicJoin order {} joined: {}@{}", + algo_services().order_key().value(), + algo_services().quantity().value(), my_side_psz.price()); + + } else { + LOG(OrderMan, Diag, + "JoinOrder order {} still waiting to join. Order: {}@{} Top of " + "the book: {}@{} Target: {}@{}", + algo_services().order_key().value(), + algo_services().quantity().value(), algo_services().price().value(), + my_side_psz.size(), my_side_psz.price(), + me->min_quantity_to_join.value(), opposite_at_inception_psz.price()); + } } -void DynamicIcebergOrder::transition(api::orderman::OrderStatus new_status) { - auto const &from = OrderStatus_Name(me->state.status()); - auto const &to = OrderStatus_Name(new_status); - LOG(OrderMan, Info, "Transitioning dynamic iceberg order {} from {} to {}", - key().value(), from, to); - me->state.set_status(new_status); -} +// Our child reported a change: +void DynamicJoin::on_child_change(OrderKey, ChildState const &st) { + // Our fill quantity and price is always a reflection of our + // child's state + algo_services().update_fill_state(st.total_fills, st.last_price); - -} // namespace order_example -} // namespace bts - -DynamicOrderDescriptor get_dynamic_iceberg_order_desc() -{ - DynamicOrderDescriptor desc; - - // order type name - desc.set_dynamic_order_type("dice"); - - // show size - auto param = desc.add_param_desc(); - param->set_param_name("show_size"); - param->mutable_param_type()->set_primitive(DYNAMIC_ORDER_PRIMITIVE_UINT); - - // child order - param = desc.add_param_desc(); - param->set_param_name("child"); - param->mutable_param_type()->set_primitive(DYNAMIC_ORDER_PRIMITIVE_ORDER_DEF); - - return desc; + switch (st.status) { + case ChildStatus::WORKING: + // Child order is still working, nothing to do + return; + case ChildStatus::COMPLETED: + // Child order completed, we should also complete + algo_services().complete(); + return; + case ChildStatus::CANCELED: + // Child order unexpectedly canceled, signal an error and + // terminate + algo_services().terminate_error("Unexpected child cancel"); + return; + } } extern "C" void init_spark_plugin(bts::SparkServices &serv) { using namespace bts; - if (config::get().type() == "dev") { - serv.register_dynamic_order(get_dynamic_iceberg_order_desc(), - []() { return std::make_unique(); }); - LOG(Plugin,Info, "Initialized order_plugin_example.so"); - } + // Describe our new algo order so that Spark can generate a GUI for + // it. + DynamicOrderDescriptor join_desc; + + // Start by naming our order type + join_desc.set_dynamic_order_type("dyn join"); + + // Now add a single unsigned int parameter, Min Quantity, that will + // determine the minimum quantity that must exist in the book in + // order for us to join the market. + auto param = join_desc.add_param_desc(); + param->set_param_name("Min Quantity"); + param->mutable_param_type()->set_primitive(DYNAMIC_ORDER_PRIMITIVE_UINT); + + // Associate the descriptor with a builder function and register + // that with the Spark server. + serv.register_dynamic_algo_order( + join_desc, []() { return std::make_unique(); }); } + +} // namespace order_example +} // namespace bts diff --git a/src/server/sparkd/CMakeDeps.cmake b/src/server/sparkd/CMakeDeps.cmake index a4aceb09a..e12c685e9 100644 --- a/src/server/sparkd/CMakeDeps.cmake +++ b/src/server/sparkd/CMakeDeps.cmake @@ -1 +1 @@ -set(sources algo/AlgoDefinitionServiceServer.cpp;algo/AlgoServiceServer.cpp;cmds/AdminReport.cpp;cmds/AutoCert.cpp;cmds/Benchmark.cpp;cmds/CmdRegistry.cpp;cmds/ConfigCheck.cpp;cmds/Help.cpp;cmds/Md.cpp;cmds/PrintHedgeOrders.cpp;cmds/QuickTest.cpp;cmds/Run.cpp;cmds/RunSim.cpp;cmds/Span.cpp;cmds/Test.cpp;cmds/TestCeloxica.cpp;cmds/Web.cpp;dspark/mirage/quick_queue/quick_queue.cpp;exchange_sim/ExchangeSim.cpp;exchange_sim/ExchangeSimApplication.cpp;exchange_sim/book/Book.cpp;exchange_sim/book/ExchangeSim.proto;exchange_sim/book/Order.cpp;exchange_sim/book/OrderMatcher.cpp;exchange_sim/book/book_transform.cpp;exchange_sim/tests/test_book_transform.cpp;http/ApiGateway.cpp;http/WebServer.cpp;main.cpp;md/ChannelVolume.cpp;md/MarketDataAuxiliaryServiceServer.cpp;md/VolumeAtPriceState.cpp;md/platforms/IMDPlatform.cpp;md/platforms/celoxica/CXListener.cpp;md/platforms/celoxica/CXMain.cpp;md/platforms/celoxica/tests/cx_tests.cpp;md/platforms/ice_onixs/ICEListener.cpp;md/platforms/ice_onixs/ICEMain.cpp;md/platforms/ice_onixs/tests/ice_tests.cpp;md/platforms/mdp3_onixs/MDP3Listener.cpp;md/platforms/mdp3_onixs/MDP3Main.cpp;md/platforms/mdp3_onixs/tests/mdp3_tests.cpp;md/run_md.cpp;position/IMarginObserver.cpp;position/IPositionObserver.cpp;position/MarginServiceCore.cpp;position/PositionServiceCore.cpp;position/PositionServiceServer.cpp;position/tests/PositionTests.cpp;support/ErrorReportService.cpp;support/ShellLatencyServer.cpp;user/AdminServiceServer.cpp;user/AuthServiceServer.cpp;user/tests/admin_service_tests.cpp) \ No newline at end of file +set(sources algo/AlgoDefinitionServiceServer.cpp;cmds/AdminReport.cpp;cmds/AutoCert.cpp;cmds/Benchmark.cpp;cmds/CmdRegistry.cpp;cmds/ConfigCheck.cpp;cmds/Help.cpp;cmds/Md.cpp;cmds/PrintHedgeOrders.cpp;cmds/QuickTest.cpp;cmds/Run.cpp;cmds/RunSim.cpp;cmds/Span.cpp;cmds/Test.cpp;cmds/TestCeloxica.cpp;cmds/Web.cpp;dspark/mirage/quick_queue/quick_queue.cpp;exchange_sim/ExchangeSim.cpp;exchange_sim/ExchangeSimApplication.cpp;exchange_sim/book/Book.cpp;exchange_sim/book/ExchangeSim.proto;exchange_sim/book/Order.cpp;exchange_sim/book/OrderMatcher.cpp;exchange_sim/book/book_transform.cpp;exchange_sim/tests/test_book_transform.cpp;http/ApiGateway.cpp;http/WebServer.cpp;main.cpp;md/ChannelVolume.cpp;md/MarketDataAuxiliaryServiceServer.cpp;md/VolumeAtPriceState.cpp;md/platforms/IMDPlatform.cpp;md/platforms/celoxica/CXListener.cpp;md/platforms/celoxica/CXMain.cpp;md/platforms/celoxica/tests/cx_tests.cpp;md/platforms/ice_onixs/ICEListener.cpp;md/platforms/ice_onixs/ICEMain.cpp;md/platforms/ice_onixs/tests/ice_tests.cpp;md/platforms/mdp3_onixs/MDP3Listener.cpp;md/platforms/mdp3_onixs/MDP3Main.cpp;md/platforms/mdp3_onixs/tests/mdp3_tests.cpp;md/run_md.cpp;position/IMarginObserver.cpp;position/IPositionObserver.cpp;position/MarginServiceCore.cpp;position/PositionServiceCore.cpp;position/PositionServiceServer.cpp;position/tests/PositionTests.cpp;support/ErrorReportService.cpp;support/ShellLatencyServer.cpp;user/AdminServiceServer.cpp;user/AuthServiceServer.cpp;user/tests/admin_service_tests.cpp) \ No newline at end of file diff --git a/src/server/sparkd/algo/AlgoServiceServer.cpp b/src/server/sparkd/algo/AlgoServiceServer.cpp deleted file mode 100644 index e444a82a9..000000000 --- a/src/server/sparkd/algo/AlgoServiceServer.cpp +++ /dev/null @@ -1,244 +0,0 @@ -//#include "AlgoServiceServer.h" -//#include "lib/api/service_helpers/AlgoServiceUtils.h" -//#include "lib/api/public/ServiceContext.h" -// -//#include "lib/persistence/SqliteStore.h" -//#include "lib/logging/logging.h" -//#include "lib/utils/bts_assert.h" -//#include "lib/utils/PBUtils.h" -//#include "lib/utils/TimeStamp.h" -// -//#include -//#include -//#include -//#include -//#include -// -//namespace bts { -//namespace orderman { -// -//using namespace std; -//using namespace bts::api::orderman; -// -//const string& algo_key(const CompositeAlgoRecord& row) { -// return row.key(); -//} -//const string& algo_template_key(const AlgoTemplateRecord& row) { -// return row.key(); -//} -// -//struct AlgoServiceServer::PImpl{ -// const std::string template_table_name, -// algo_table_name; -// std::unique_ptr store; -// bts::api::ServiceContext& context; -// AlgoServiceBase::AlgosStatefulPublisher algo_publisher; -// AlgoServiceBase::Algo_templatesStatefulPublisher template_publisher; -// PImpl(bts::api::ServiceContext& context, -// const AlgoServiceBase::AlgosStatefulPublisher& algo_publisher, -// const AlgoServiceBase::Algo_templatesStatefulPublisher& template_publisher) -// : -// template_table_name("templates"), -// algo_table_name("composite_algos"), -// store(new bts::persistence::SqliteStore("algo")), -// context(context), -// algo_publisher(algo_publisher), -// template_publisher(template_publisher){ -// } -//}; -// -//AlgoServiceServer::AlgoServiceServer(bts::api::ServiceContext& context) -//: -//AlgoServiceBase (context), -//me(new PImpl(context, -// bts::api::StatefulPublisher(make_algos_publisher(), algo_key, true), -// bts::api::StatefulPublisher(make_algo_templates_publisher(), algo_template_key, true))) -//{ -// _init_publish_algos(); -// _init_publish_templates(); -//} -//AlgoServiceServer::~AlgoServiceServer(){} -// -//void AlgoServiceServer::create_composite_algo( -// const CompositeAlgoCreateRequest& request, -// const api::Response& response){ -// CompositeAlgoCreateResult result; -// result.set_success(true); -// if (!_has_algo(request.new_algo().name())){ -// CompositeAlgoRecord new_algo_rec; -// new_algo_rec.set_key(request.new_algo().name()); -// new_algo_rec.mutable_common()->CopyFrom(_new_common(request.user_id())); -// new_algo_rec.mutable_algo_definition()->CopyFrom(request.new_algo()); -// if(_store_and_publish_algo(new_algo_rec)) -// result.mutable_record()->CopyFrom(new_algo_rec); -// else{ -// result.set_success(false); -// result.set_err_msg("Could not store algo"); -// } -// } -// else{ -// result.set_success(false); -// result.set_err_msg("Algo with this name already exists"); -// } -// response(result); -//} -// -//void AlgoServiceServer::create_template( -// const TemplateCreateRequest& request, -// const api::Response& response){ -// TemplateCreateResult result; -// result.set_success(true); -// string key = template_key(request.new_template()); -// const AlgoTemplateRecord* ex_rec = _find_template(key); -// if(ex_rec == nullptr){ -// AlgoTemplateRecord new_record; -// new_record.set_key(key); -// new_record.mutable_common()->CopyFrom(_new_common(request.user_id())); -// new_record.mutable_algo_template()->CopyFrom(request.new_template()); -// if(_store_and_publish_template(true,new_record)) -// result.mutable_record()->CopyFrom(new_record); -// else{ -// result.set_success(false); -// result.set_err_msg("Could not store algo"); -// } -// } -// else{ -// result.set_success(false); -// result.set_err_msg("Template already exists"); -// result.mutable_record()->CopyFrom(*ex_rec); -// } -// response(result); -//} -// -//void AlgoServiceServer::update_template( -// const TemplateUpdateRequest& request, -// const api::Response& response){ -// AlgoServiceReply result; -// result.set_success(true); -// const AlgoTemplateRecord* ex_rec = _find_template(request.key()); -// if(ex_rec == nullptr){ -// result.set_success(false); -// result.set_err_msg("Could not locate template"); -// } -// else{ -// AlgoTemplateRecord mrec = AlgoTemplateRecord(*ex_rec); -// mrec.mutable_algo_template()->CopyFrom(request.updated_template()); -// const AlgoTemplateRecord updated_rec = mrec; -// if(!_store_and_publish_template(false,updated_rec)){ -// result.set_success(false); -// result.set_err_msg("Could not serialize template"); -// } -// // TODO: need to make sure -// // a. template's algo is not changed -// // b. template is consistent with the algo -// } -// response(result); -//} -// -//void AlgoServiceServer::remove_template( -// const AlgoServiceRemoveRequest& request, -// const api::Response& response){ -// AlgoServiceReply result; -// result.set_success(true); -// const AlgoTemplateRecord* ex_rec = _find_template(request.key()); -// if(ex_rec == nullptr){ -// result.set_success(false); -// result.set_err_msg("Could not locate template"); -// } -// else{ -// set keys; -// keys.insert(request.key()); -// me->store->remove(me->template_table_name,keys); -// me->template_publisher.erase(request.key()); -// me->template_publisher.flush(); -// } -// response(result); -//} -// -//PersistenceRecordCommon AlgoServiceServer::_new_common(uint32_t user_id){ -// PersistenceRecordCommon rv; -// rv.set_is_active(true); -// rv.set_creator_user_id(user_id); -// return rv; -//} -// -//// algo helper functions -//void AlgoServiceServer::_init_publish_algos(){ -// map> all_data = me->store->retrieve_all(); -// auto table=all_data.find(me->algo_table_name); -// if(table!=all_data.end()){ -// for (const auto& p : table->second){ -// CompositeAlgoRecord algo; -// if(algo.ParseFromString(p.second)) -// me->algo_publisher.add_or_update(algo); -// else -// LOG(Gen, Error, "AlgoServiceServer._load_algos " -// "could not load {}", table->first); -// } -// me->algo_publisher.flush(); -// } -//} -// -//bool AlgoServiceServer::_has_algo(const std::string& key){ -// const auto& algo_map = me->algo_publisher.state_data(); -// return algo_map.find(key) != algo_map.end(); -//} -// -//bool AlgoServiceServer::_store_and_publish_algo ( -// const CompositeAlgoRecord& rec){ -// string ser; -// if(rec.SerializeToString(&ser)){ -// me->store->insert(me->algo_table_name, -// rec.algo_definition().name(), -// ser); -// me->algo_publisher.add_or_update(rec); -// me->algo_publisher.flush(); -// return true; -// } -// else -// return false; -//} -// -//void AlgoServiceServer::_init_publish_templates(){ -// map> all_data = me->store->retrieve_all(); -// auto table=all_data.find(me->template_table_name); -// if(table!=all_data.end()){ -// for (const auto& p : table->second){ -// AlgoTemplateRecord t_record; -// if(t_record.ParseFromString(p.second)) -// me->template_publisher.add_or_update(t_record); -// else -// LOG(Gen, Error, "AlgoServiceServer._load_templates " -// "could not load template {}", table->first); -// } -// me->template_publisher.flush(); -// } -//} -// -//const AlgoTemplateRecord* AlgoServiceServer::_find_template( -// const std::string& key){ -// const auto& template_map = me->template_publisher.state_data(); -// const auto it = template_map.find(key); -// if(it != template_map.end()) -// return &(it->second); -// return nullptr; -//} -// -//bool AlgoServiceServer::_store_and_publish_template ( -// bool insert, -// const AlgoTemplateRecord& rec){ -// string ser; -// if(rec.SerializeToString(&ser)){ -// if(insert) -// me->store->insert(me->template_table_name,rec.key(),ser); -// else -// me->store->update(me->template_table_name,rec.key(),ser); -// me->template_publisher.add_or_update(rec); -// me->template_publisher.flush(); -// return true; -// } -// else -// return false; -//} -// -//}} diff --git a/src/server/sparkd/algo/AlgoServiceServer.h b/src/server/sparkd/algo/AlgoServiceServer.h deleted file mode 100644 index 079a7a36d..000000000 --- a/src/server/sparkd/algo/AlgoServiceServer.h +++ /dev/null @@ -1,54 +0,0 @@ -//#pragma once -// -//#include -//#include "lib/api/services/AlgoService.server.pb.h" -//#include "lib/utils/bts_no_copy.h" -//#include "lib/persistence/IStore.h" -//#include "lib/api/public/ServiceContext.h" -//#include "lib/api/services/OrderService.pb.h" -//#include "lib/api/services/OrderService.client.pb.h" -// -//namespace bts { -//namespace orderman { -// -//class AlgoServiceServer : public api::orderman::AlgoServiceBase -//{ -//private: -// struct PImpl; -// std::unique_ptr me; -//public: -// AlgoServiceServer(bts::api::ServiceContext& context); -// ~AlgoServiceServer(); -// -// void create_composite_algo( -// const bts::api::orderman::CompositeAlgoCreateRequest& request, -// const api::Response& reply) override; -// -// void create_template( -// const bts::api::orderman::TemplateCreateRequest& request, -// const api::Response& reply) override; -// -// void update_template( -// const bts::api::orderman::TemplateUpdateRequest& request, -// const api::Response& reply) override; -// -// void remove_template( -// const bts::api::orderman::AlgoServiceRemoveRequest& request, -// const api::Response& reply) override; -//private: -// bts::api::orderman::PersistenceRecordCommon _new_common(uint32_t user_id); -// // loads algos from the db and publises them -// void _init_publish_algos(); -// bool _has_algo(const std::string& name); -// bool _store_and_publish_algo ( -// const bts::api::orderman::CompositeAlgoRecord& rec); -// // template helpers -// // loads templates from the db and publises them -// void _init_publish_templates(); -// const bts::api::orderman::AlgoTemplateRecord* _find_template( -// const std::string& key); -// bool _store_and_publish_template ( -// bool insert, -// const bts::api::orderman::AlgoTemplateRecord& rec); -//}; -//}} diff --git a/src/server/sparkd/cmds/QuickTest.cpp b/src/server/sparkd/cmds/QuickTest.cpp index 2f0437d52..ebc012dbe 100644 --- a/src/server/sparkd/cmds/QuickTest.cpp +++ b/src/server/sparkd/cmds/QuickTest.cpp @@ -1,27 +1,58 @@ #include "QuickTest.h" #include "ICmd.h" #include "lib/tracing/PerfLog.h" +#include "lib/orderman/orders/algo/IAlgoServices.h" #include namespace bts { namespace cmd { +using namespace bts::orderman; -struct PerfLogEntry { - utils::TimeStamp ts; - const char *channel; - const char *entry_kind; - const char *txt_1; - uint64_t uint64_1; - pthread_t thread_id; - utils::TimeStamp ts2; - uint32_t sn; - uint32_t uint32_1; +struct Proxy : public IAlgoServices { + api::orderman::OrderDefinition def; + api::Security sec; + + api::orderman::OrderDefinition const &definition() const { return def; } + api::Security const &security() const { return sec; } + OrderKey order_key() const { return OrderKey(0); } + OrderKey parent_order_key() const { return OrderKey(0); } + api::Security const *lookup_security(SecurityKey) const { return nullptr; } + bool is_attaching() const { return false; } + ChildTemplate &make_child_template(api::orderman::OrderDefinition const &, + size_t) { + ChildTemplate *p = nullptr; + return *p; + } + Price price() const { return Price(0); } + Quantity quantity() const { return Quantity(0); } + Quantity total_fills() const { return Quantity(0); } + void subscribe_book(SecurityKey){}; + void unsubscribe_book(SecurityKey) {} + void subscribe_child_change(OrderKey) {} + void unsubscribe_child_change(OrderKey) {} + void subscribe_timer() {} + void unsubscribe_timer() {} + OrderKey launch_child(ChildTemplate &, Price, Quantity, bool) { return {}; } + OrderKey launch_child(api::orderman::OrderDefinition const &, Price, + Quantity, bool) { + return {}; + } + void update_child(OrderKey , api::orderman::Update const &) {} + void cancel_child(OrderKey) {} + void detach_child(OrderKey) {} + void detach_all_children() {} + void cancel(std::string const &) {} + void terminate_error(std::string const &) {} + void complete() {} + void update_fill_state(Quantity , Price ) {} }; - + int QuickTest::execute(std::vector const &) { - std::cout << sizeof(pthread_t) << "\n"; - std::cout << sizeof(PerfLogEntry) << "\n"; + Proxy p; + auto t = &(p.make_child_template(api::orderman::OrderDefinition(),2)); + auto k = p.launch_child(*t,Price(1),Quantity(2),false); + std::cout << k.value() << "\n"; return 0; } diff --git a/src/server/sparkd/cmds/Run.cpp b/src/server/sparkd/cmds/Run.cpp index f1df545c4..3c9b1ec1c 100644 --- a/src/server/sparkd/cmds/Run.cpp +++ b/src/server/sparkd/cmds/Run.cpp @@ -33,7 +33,6 @@ #include "server/sparkd/support/ShellLatencyServer.h" #include "server/sparkd/user/AdminServiceServer.h" #include "server/sparkd/user/AuthServiceServer.h" -#include "server/sparkd/algo/AlgoServiceServer.h" #include "server/sparkd/algo/AlgoDefinitionServiceServer.h" #include @@ -85,6 +84,10 @@ int Run::execute(std::vector const &) { md::auxiliary::MarketDataAuxiliaryServiceServer md_aux_server(sc); //orderman::AlgoServiceServer algo_server(sc); bts::api::orderman::algo::AlgoDefinitionServiceServer algo_definition_server(sc); + + + + position::PositionServiceServer position_service(sc); metrics::ShellLatencyServer shell_latency_service( sc, stats, utils::Dispatcher::background()); diff --git a/src/server/sparkd/exchange_sim/ExchangeSim.cpp b/src/server/sparkd/exchange_sim/ExchangeSim.cpp index b20310dda..11001dfa9 100644 --- a/src/server/sparkd/exchange_sim/ExchangeSim.cpp +++ b/src/server/sparkd/exchange_sim/ExchangeSim.cpp @@ -31,8 +31,8 @@ auto cfg = "ConnectionType=acceptor\n" "SocketAcceptPort=$EXCHANGE_SIM_FIX_PORT\n" "SocketReuseAddress=Y\n" - "StartTime=07:50:00\n" - "EndTime=07:49:00\n" + "StartTime=06:02:00\n" + "EndTime=06:01:00\n" "FileLogPath=$BTS_DATA_PATH/exchange_sim/log\n" "FileStorePath=$BTS_DATA_PATH/exchange_sim/store\n" "HeartBtInt=30\n" diff --git a/src/server/sparkd/exchange_sim/ExchangeSimApplication.cpp b/src/server/sparkd/exchange_sim/ExchangeSimApplication.cpp index d9a2cd472..aa37f7b98 100644 --- a/src/server/sparkd/exchange_sim/ExchangeSimApplication.cpp +++ b/src/server/sparkd/exchange_sim/ExchangeSimApplication.cpp @@ -6,24 +6,26 @@ #include "lib/config/protos/ExchangeSimCfg.pb.h" #include "lib/domain_model/Security.h" #include "lib/logging/logging.h" +#include "lib/md/MBOProcessor.h" #include "lib/md/MDProducer.h" #include "lib/md/Shm/FixedSecurity.h" #include "lib/md/Shm/MDStructure.h" #include "lib/md/get_symbols.h" -#include "lib/md/MBOProcessor.h" +#include "lib/orderman/orderman_utils/fix_order_codec.h" +#include "lib/persistence/SqliteStore.h" #include "lib/utils/Dispatcher.h" #include "lib/utils/datetime.h" #include "server/sparkd/exchange_sim/book/Order.h" #include "server/sparkd/exchange_sim/book/OrderMatcher.h" #include "server/sparkd/exchange_sim/book/book_transform.h" -#include "lib/persistence/SqliteStore.h" -#include "lib/orderman/orderman_utils/fix_order_codec.h" #include #include #include #include +#include #include + #include namespace bts { @@ -99,19 +101,17 @@ struct ExchangeSimApplication::MDConsumerRec { utils::TimeStamp last_read; }; -inline FIX::OrderID exchange_key(const std::string& clOrdID) { +inline FIX::OrderID exchange_key(const std::string &clOrdID) { return FIX::OrderID(clOrdID.substr(3)); } struct ExchangeSimApplication::PImpl { - PImpl(md::MBOWriter* mbo) - : producer(co2::PLATFORM_SIM), - md_sn(1), + PImpl(md::MBOWriter *mbo) + : producer(co2::PLATFORM_SIM), md_sn(1), timer(utils::Dispatcher::background(), 200, [=]() { producer.heartbeat(); }), do_merge_with_md(config::get().merge_with_md()), - store(new persistence::SqliteStore("ex_sim_orders")), - lock(), + store(new persistence::SqliteStore("ex_sim_orders")), lock(), mbo(mbo) {} IDGenerator m_generator; @@ -124,10 +124,11 @@ struct ExchangeSimApplication::PImpl { bool do_merge_with_md; std::unique_ptr store; std::mutex lock; - md::MBOWriter* mbo; + md::MBOWriter *mbo; }; -ExchangeSimApplication::ExchangeSimApplication(md::MBOWriter* mbo) : me(new PImpl(mbo)) { +ExchangeSimApplication::ExchangeSimApplication(md::MBOWriter *mbo) + : me(new PImpl(mbo)) { auto previous_book = me->store->retrieve_all(); auto all = me->store->retrieve_all()["books"]; @@ -202,7 +203,8 @@ void ExchangeSimApplication::onMessage(const FIX42::NewOrderSingle &message, LOG(ExSim, Info, "Got new order: {}", clOrdID.getString()); try { - if (timeInForce != FIX::TimeInForce_DAY && timeInForce != FIX::TimeInForce_IMMEDIATE_OR_CANCEL) + if (timeInForce != FIX::TimeInForce_DAY && + timeInForce != FIX::TimeInForce_IMMEDIATE_OR_CANCEL) throw std::logic_error("Unsupported TIF, use Day or IOC"); auto &matcher = me->matchers[sec_desc]; @@ -250,18 +252,19 @@ void ExchangeSimApplication::onMessage(const FIX42::NewOrderSingle &message, *order.mutable_create_time() = utils::pb::pb_now(); *order.mutable_last_update_time() = utils::pb::pb_now(); - updateOrder(order, FIX::OrdStatus_NEW); + send_execution_report(order, FIX::OrdStatus_NEW); std::vector updates; matcher.add_new(order, &updates); for (auto const &o : updates) fillOrder(o); - if (updates.empty() && timeInForce == FIX::TimeInForce_IMMEDIATE_OR_CANCEL) { + if (updates.empty() && + timeInForce == FIX::TimeInForce_IMMEDIATE_OR_CANCEL) { auto order_cpy = order; order_cpy.set_open_quantity(0); - updateOrder(order_cpy, FIX::OrdStatus_CANCELED); + send_execution_report(order_cpy, FIX::OrdStatus_CANCELED); matcher.cancel(clOrdID); } - + update_md(sec_desc); } catch (std::exception &e) { rejectOrder(senderCompID, senderSubID, targetCompID, clOrdID, sec_desc, @@ -301,16 +304,23 @@ void ExchangeSimApplication::onMessage( clOrdID); throw std::logic_error("Unknown order"); } else { - auto order_cpy = *order; - order_cpy.set_price(price); - order_cpy.set_quantity(orderQty); - *order_cpy.mutable_last_update_time() = utils::pb::pb_now(); - updateOrder(order_cpy, FIX::OrdStatus_REPLACED); + if (order->executed_quantity() >= orderQty) { + auto order_cpy = *order; + order_cpy.set_open_quantity(0); + send_execution_report(order_cpy, FIX::OrdStatus_CANCELED); + matcher.cancel(clOrdID); + } else { + auto order_cpy = *order; + order_cpy.set_price(price); + order_cpy.set_quantity(orderQty); + *order_cpy.mutable_last_update_time() = utils::pb::pb_now(); + send_execution_report(order_cpy, FIX::OrdStatus_REPLACED); - std::vector updates; - matcher.update(clOrdID, Price(price), Quantity(orderQty), &updates); - for (auto const &o : updates) - fillOrder(o); + std::vector updates; + matcher.update(clOrdID, Price(price), Quantity(orderQty), &updates); + for (auto const &o : updates) + fillOrder(o); + } update_md(sec_desc); } } catch (std::exception &e) { @@ -324,7 +334,13 @@ void ExchangeSimApplication::onMessage(const FIX42::OrderCancelRequest &message, FIX::OrigClOrdID origClOrdID; FIX::SecurityDesc sec_desc; FIX::Side side; + FIX::SenderCompID senderCompID; + FIX::TargetCompID targetCompID; + FIX::SenderSubID senderSubID; + message.getHeader().get(senderCompID); + message.getHeader().get(senderSubID); + message.getHeader().get(targetCompID); message.get(origClOrdID); message.get(sec_desc); message.get(side); @@ -336,11 +352,21 @@ void ExchangeSimApplication::onMessage(const FIX42::OrderCancelRequest &message, if (!order) { LOG(ExSim, Info, "Receive cancel for unknown order {}", origClOrdID.getString()); - throw std::logic_error("Unknown order"); + + FIX42::OrderCancelReject rej; + rej.set(FIX::ClOrdID(origClOrdID.getString())); + rej.set(FIX::Text("Unknown order")); + rej.getHeader().set(FIX::TargetSubID(senderSubID.getValue())); + try { + FIX::Session::sendToTarget(rej, targetCompID, senderCompID); + LOG(ExSim, Info, "Rejected cancel for order {}", + origClOrdID.getString()); + } catch (FIX::SessionNotFound &) { + } } else { auto order_cpy = *order; order_cpy.set_open_quantity(0); - updateOrder(order_cpy, FIX::OrdStatus_CANCELED); + send_execution_report(order_cpy, FIX::OrdStatus_CANCELED); matcher.cancel(origClOrdID); update_md(sec_desc); } @@ -349,16 +375,16 @@ void ExchangeSimApplication::onMessage(const FIX42::OrderCancelRequest &message, } void ExchangeSimApplication::rejectOrder(const Order &order) { - updateOrder(order, FIX::OrdStatus_REJECTED); + send_execution_report(order, FIX::OrdStatus_REJECTED); } void ExchangeSimApplication::fillOrder(const Order &order) { - updateOrder(order, order.open_quantity() == 0 - ? FIX::OrdStatus_FILLED - : FIX::OrdStatus_PARTIALLY_FILLED); + send_execution_report(order, order.open_quantity() == 0 + ? FIX::OrdStatus_FILLED + : FIX::OrdStatus_PARTIALLY_FILLED); } -void ExchangeSimApplication::updateOrder(const Order &order, char status) { +void ExchangeSimApplication::send_execution_report(const Order &order, char status) { FIX::TargetCompID targetCompID(order.owner()); FIX::SenderCompID senderCompID(order.target()); FIX::TargetSubID(order.sender_sub_id()); @@ -464,8 +490,8 @@ void ExchangeSimApplication::update_md(std::string const &sec_desc) { auto book = matcher.get_book(); - LOG(ExSim, Diag, "Current book {}:\n {}", sec_desc,book); - + LOG(ExSim, Diag, "Current book {}:\n {}", sec_desc, book); + auto price_factor = pow(10, handle.security().display_factor); const auto cmax = md::COCONUT_MAX_DEPTH; @@ -486,17 +512,19 @@ void ExchangeSimApplication::update_md(std::string const &sec_desc) { return md::PriceSize_from_double( bs.first.value() * price_factor, bs.second.value()); }); - handle.update_direct(utils::TimeStamp::now(), bids_temp, asks_temp, me->md_sn++); + handle.update_direct(utils::TimeStamp::now(), bids_temp, asks_temp, + me->md_sn++); auto new_trades = matcher.get_new_trades(); for (auto &t : new_trades) { handle.add_trade( utils::TimeStamp::now(), - md::PriceSize_from_double(t.price.value() * price_factor,t.quantity.value()), + md::PriceSize_from_double( + t.price.value() * price_factor, t.quantity.value()), datetime::ll_now(), - t.bid_aggressor ? co2::AGGRESSOR_SIDE_BUY - : ( t.ask_aggressor ? co2::AGGRESSOR_SIDE_SELL - : co2::AGGRESSOR_SIDE_NONE) ); + t.bid_aggressor ? co2::AGGRESSOR_SIDE_BUY + : (t.ask_aggressor ? co2::AGGRESSOR_SIDE_SELL + : co2::AGGRESSOR_SIDE_NONE)); } // publish mbo @@ -505,16 +533,16 @@ void ExchangeSimApplication::update_md(std::string const &sec_desc) { // get the list of trades auto ob = matcher.get_order_book(nullptr); auto snap = mbo->allocate_snapshot(); - for (const auto& order : ob.order()) { + for (const auto &order : ob.order()) { auto ek = exchange_key(order.clordid()); - md::SnapshotOrder sno { - md::ExchangeOrderKey(std::atoll(ek.getString().c_str())), - md::IntPrice_from_double(order.price() * price_factor), - (int)order.open_quantity() }; + md::SnapshotOrder sno{ + md::ExchangeOrderKey(std::atoll(ek.getString().c_str())), + md::IntPrice_from_double(order.price() * + price_factor), + (int)order.open_quantity()}; if (order.side() == api::SIDE_BUY) { snap->bids.push_back(sno); - } - else if (order.side() == api::SIDE_SELL) { + } else if (order.side() == api::SIDE_SELL) { snap->asks.push_back(sno); } } @@ -564,16 +592,18 @@ void ExchangeSimApplication::on_new_security(api::Security const &s) { } } -void ExchangeSimApplication::on_settlement(md::Security const& sec, md::IntPrice price) { +void ExchangeSimApplication::on_settlement(md::Security const &sec, + md::IntPrice price) { auto sec_desc = get_sim_sec_desc(sec); auto iter = me->md_producer_handles.find(sec_desc); if (iter != me->md_producer_handles.end()) { auto &handle = iter->second; - handle.update_settlement(utils::TimeStamp::now(), price, datetime::today()); + handle.update_settlement(utils::TimeStamp::now(), price, + datetime::today()); } } -void ExchangeSimApplication::on_high(md::Security const& sec, md::Price price) { +void ExchangeSimApplication::on_high(md::Security const &sec, md::Price price) { auto sec_desc = get_sim_sec_desc(sec); auto iter = me->md_producer_handles.find(sec_desc); if (iter != me->md_producer_handles.end()) { @@ -582,7 +612,7 @@ void ExchangeSimApplication::on_high(md::Security const& sec, md::Price price) { } } -void ExchangeSimApplication::on_low(md::Security const& sec, md::Price price) { +void ExchangeSimApplication::on_low(md::Security const &sec, md::Price price) { auto sec_desc = get_sim_sec_desc(sec); auto iter = me->md_producer_handles.find(sec_desc); if (iter != me->md_producer_handles.end()) { @@ -591,7 +621,7 @@ void ExchangeSimApplication::on_low(md::Security const& sec, md::Price price) { } } -void ExchangeSimApplication::on_open(md::Security const& sec, md::Price price) { +void ExchangeSimApplication::on_open(md::Security const &sec, md::Price price) { auto sec_desc = get_sim_sec_desc(sec); auto iter = me->md_producer_handles.find(sec_desc); if (iter != me->md_producer_handles.end()) { @@ -600,7 +630,8 @@ void ExchangeSimApplication::on_open(md::Security const& sec, md::Price price) { } } -void ExchangeSimApplication::on_close(md::Security const& sec, md::Price price) { +void ExchangeSimApplication::on_close(md::Security const &sec, + md::Price price) { auto sec_desc = get_sim_sec_desc(sec); auto iter = me->md_producer_handles.find(sec_desc); if (iter != me->md_producer_handles.end()) { @@ -610,20 +641,19 @@ void ExchangeSimApplication::on_close(md::Security const& sec, md::Price price) } void ExchangeSimApplication::on_depth( - md::Security const &sec, - md::PriceSize bids[md::COCONUT_MAX_DEPTH], + md::Security const &sec, md::PriceSize bids[md::COCONUT_MAX_DEPTH], md::PriceSize asks[md::COCONUT_MAX_DEPTH], - std::array* implied_bids, - std::array* implied_asks) { + std::array *implied_bids, + std::array *implied_asks) { std::lock_guard l(me->lock); if (sec.has_synthetic()) - return ; + return; if (!me->do_merge_with_md) - return; - + return; + auto it = me->md_consumer_recs.find(sec.glbx().security_desc()); bts_assert(it != me->md_consumer_recs.end()); @@ -647,13 +677,14 @@ void ExchangeSimApplication::on_depth( // we generate a set of orders that we apply to our order book merge_with_order_book(it->second.security.glbx().security_desc(), previous_md_book, current_md_book); - + // pass on implied market unchanged if (implied_bids || implied_asks) { auto iter = me->md_producer_handles.find(get_sim_sec_desc(sec)); if (iter != me->md_producer_handles.end()) { auto &handle = iter->second; - handle.update_implied(utils::TimeStamp::now(), *implied_bids, *implied_asks); + handle.update_implied(utils::TimeStamp::now(), *implied_bids, + *implied_asks); } } } @@ -665,9 +696,9 @@ void ExchangeSimApplication::merge_with_order_book(std::string const &sec_desc, auto src_book = matcher.get_book(); auto transform = compute_book_transform(src, dest); + LOG(ExSim, Diag, "Book transformation for {}\n source:\n {} dest:\n{}", + sec_desc, src, dest); - LOG(ExSim, Diag, "Book transformation for {}\n source:\n {} dest:\n{}", sec_desc,src,dest); - for (auto const &op : transform) { LOG(ExSim, Diag, "Adding synthetic book operation for {}. {} {} {}@{}", diff --git a/src/server/sparkd/exchange_sim/ExchangeSimApplication.h b/src/server/sparkd/exchange_sim/ExchangeSimApplication.h index d5771e88d..64077befe 100644 --- a/src/server/sparkd/exchange_sim/ExchangeSimApplication.h +++ b/src/server/sparkd/exchange_sim/ExchangeSimApplication.h @@ -80,7 +80,7 @@ private: // Order functionality void processOrder( const Order& ); // void processCancel( const std::string& id, const std::string& symbol, Order::Side ); - void updateOrder( const Order&, char status ); + void send_execution_report( const Order&, char status ); void rejectOrder( const Order& order ); // void acceptOrder( const Order& order ); void fillOrder( const Order& order ); diff --git a/src/server/sparkd/exchange_sim/book/OrderMatcher.cpp b/src/server/sparkd/exchange_sim/book/OrderMatcher.cpp index 13f165d26..1f1c4b78c 100644 --- a/src/server/sparkd/exchange_sim/book/OrderMatcher.cpp +++ b/src/server/sparkd/exchange_sim/book/OrderMatcher.cpp @@ -109,7 +109,8 @@ void OrderMatcher::update(std::string const &clordid, Price price, Quantity qty, if (order_cpy.quantity() != qty.value()) { order_cpy.set_quantity(qty.value()); - order_cpy.set_open_quantity(qty.value()); + bts_assert(qty.value() > order_cpy.executed_quantity()); + order_cpy.set_open_quantity(qty.value()-order_cpy.executed_quantity()); } if (order->side() == api::SIDE_BUY) { diff --git a/src/server/sparkd/support/ShellLatencyServer.cpp b/src/server/sparkd/support/ShellLatencyServer.cpp index ccdb3e4ca..eb5657b87 100644 --- a/src/server/sparkd/support/ShellLatencyServer.cpp +++ b/src/server/sparkd/support/ShellLatencyServer.cpp @@ -36,7 +36,7 @@ void ShellLatencyServer::report( reply(bts::api::VoidMessage()); // look up or create the metric - auto key = request.host_name() + "-" + request.version(); + auto key = request.host_name() + "-" + request.version() + "-" + request.user(); auto iter = _metrics.find(key); std::shared_ptr metric; // report at least 1ms because the metric will not report anything if it's 0 @@ -44,8 +44,8 @@ void ShellLatencyServer::report( if (iter == _metrics.end()) { // create metric auto metric = - std::make_shared("spark_shell_latency", - std::vector