Compare commits

..
Author SHA1 Message Date
Michael Harding 108c1cec39 spark_sdk update 2.0.0-beta2 2019-05-03 19:31:17 +00:00
98 changed files with 636 additions and 1623 deletions

No files matched your search

+4 -21
View File
@@ -22,9 +22,9 @@ namespace mbts.ui {
AddBoxesGeometryKey = nameof(AddBoxesGeometryKey),
AddFileGeometryKey = nameof(AddFileGeometryKey),
AddFileThinGeometryKey = nameof(AddFileThinGeometryKey),
AttachAlgosKey = nameof(AttachAlgosKey),
AttachAlgosGeometryKey = nameof(AttachAlgosGeometryKey),
CheckMarkGeometryKey = nameof(CheckMarkGeometryKey),
DetachAlgosKey = nameof(DetachAlgosKey),
DetachAlgosGeometryKey = nameof(DetachAlgosGeometryKey),
DiskGeometryKey = nameof(DiskGeometryKey),
DiskFileGeometryKey = nameof(DiskFileGeometryKey),
DocumentGeometryKey = nameof(DocumentGeometryKey),
@@ -37,14 +37,11 @@ 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),
@@ -121,7 +118,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 AttachAlgos => create_icon(AttachAlgosGeometryKey);
public static ImageSource Beaker { get { return load_resource_and_freeze("Beaker"); } }
public static ImageSource Book { get { return load_resource_and_freeze("Book"); } }
@@ -146,7 +143,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 DetachAlgos => create_icon(DetachAlgosGeometryKey);
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"); } }
@@ -167,7 +164,6 @@ namespace mbts.ui {
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);
@@ -196,19 +192,6 @@ 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);
+52 -12
View File
@@ -5,14 +5,6 @@
xmlns:mbts="clr-namespace:mbts.ui"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
>
<sys:String x:Key="{x:Static mbts:Icons.AttachAlgosKey}">
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
</sys:String>
<sys:String x:Key="{x:Static mbts:Icons.DetachAlgosKey}">
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
</sys:String>
<!--AddBoxes (the icon is free to use if we include this information in our credit section)
Source: https://www.flaticon.com/authors/gregor-cresnar
Ttile: Add free icon
@@ -48,6 +40,58 @@
</sys:String>
</x:Array>
<!--File (the icon is free to use if we include this information in our credit section)
Source: https://www.flaticon.com/authors/freepik
Ttile: Unlink free icon
Credit: Icon made by Chanut from www.flaticon.com-->
<x:Array x:Key="{x:Static mbts:Icons.AttachAlgosGeometryKey}" Type="sys:String">
<sys:String>
M51.173,3.801c-5.068-5.068-13.315-5.066-18.384,0l-9.192,9.192c-0.781,0.781-0.781,2.047,0,2.828
c0.781,0.781,2.047,0.781,2.828,0l9.192-9.192c1.691-1.69,3.951-2.622,6.363-2.622c2.413,0,4.673,0.932,6.364,2.623
s2.623,3.951,2.623,6.364c0,2.412-0.932,4.672-2.623,6.363L36.325,31.379c-3.51,3.508-9.219,3.508-12.729,0
c-0.781-0.781-2.047-0.781-2.828,0s-0.781,2.048,0,2.828c2.534,2.534,5.863,3.801,9.192,3.801s6.658-1.267,9.192-3.801
l12.021-12.021c2.447-2.446,3.795-5.711,3.795-9.192C54.968,9.512,53.62,6.248,51.173,3.801z
</sys:String>
<sys:String>
M27.132,40.57l-7.778,7.778c-1.691,1.691-3.951,2.623-6.364,2.623c-2.412,0-4.673-0.932-6.364-2.623
c-3.509-3.509-3.509-9.219,0-12.728L17.94,24.306c1.691-1.69,3.951-2.622,6.364-2.622c2.412,0,4.672,0.932,6.363,2.622
c0.781,0.781,2.047,0.781,2.828,0s0.781-2.047,0-2.828c-5.067-5.067-13.314-5.068-18.384,0L3.797,32.793
c-2.446,2.446-3.794,5.711-3.794,9.192c0,3.48,1.348,6.745,3.795,9.191c2.446,2.447,5.711,3.795,9.191,3.795
c3.481,0,6.746-1.348,9.192-3.795l7.778-7.778c0.781-0.781,0.781-2.047,0-2.828S27.913,39.789,27.132,40.57z
</sys:String>
</x:Array>
<!--File (the icon is free to use if we include this information in our credit section)
Source: https://www.flaticon.com/authors/freepik
Ttile: Disconnected chains free icon
Credit: Icon made by Chanut from www.flaticon.com-->
<x:Array x:Key="{x:Static mbts:Icons.DetachAlgosGeometryKey}" Type="sys:String">
<sys:String>
M462.557,77.627c-14.323-25.556-41.488-41.423-70.889-41.423c-13.835,0-27.54,3.585-39.602,10.364
l-152.557,85.635l17.55,31.279l152.565-85.635c6.747-3.78,14.371-5.779,22.069-5.779c16.428,0,31.596,8.852,39.594,23.11
c5.909,10.535,7.356,22.752,4.072,34.408c-3.268,11.656-10.876,21.346-21.411,27.255l-138.291,77.604
c-2.634-16.851-10.494-32.392-22.793-44.699c-21.687-21.663-56.063-29.328-84.935-18.964l-12.485,4.495l12.128,33.734
l12.534-4.471c16.127-5.869,35.319-1.496,47.406,10.567c6.974,6.982,11.388,15.826,12.786,25.41
c-0.585-0.138-1.171-0.285-1.731-0.447c-11.681-3.284-21.354-10.9-27.271-21.476l-6.519-11.518l-31.303,17.59l6.56,11.518
c10.6,18.915,27.93,32.571,48.836,38.44c0.723,0.187,1.455,0.39,2.187,0.561c-1.105,1.398-2.284,2.731-3.536,3.983
l-114.32,114.328c-8.551,8.543-19.931,13.241-32.035,13.241c-12.112,0-23.492-4.698-32.027-13.241
c-8.535-8.543-13.233-19.907-13.233-32.027c0-12.112,4.698-23.483,13.233-32.018l99.291-99.282l-25.369-25.369l-99.282,99.282
C8.446,319.427,0,339.806,0,361.468c0,21.679,8.446,42.049,23.776,57.396c15.339,15.339,35.709,23.768,57.388,23.768
s42.049-8.429,57.388-23.768l114.345-114.32c8.372-8.405,14.81-18.566,18.842-29.71c6.625-1.764,12.924-4.3,18.777-7.6
l140.99-79.115c18.875-10.608,32.514-27.946,38.375-48.828C475.749,118.4,473.148,96.493,462.557,77.627z
</sys:String>
<sys:String>
M173.171,141.769c4.503-0.821,7.511-5.145,6.69-9.657l-17.103-94.942
c-0.821-4.519-5.162-7.527-9.665-6.722c-4.511,0.821-7.527,5.145-6.706,9.673l17.111,94.925
C164.311,139.575,168.644,142.574,173.171,141.769z
</sys:String>
<sys:String>
M43.561,191.776l94.934-17.119c4.519-0.821,7.527-5.145,6.706-9.657
c-0.821-4.528-5.145-7.543-9.649-6.722L40.61,175.405c-4.503,0.797-7.519,5.145-6.698,9.657
C34.717,189.582,39.058,192.589,43.561,191.776z
</sys:String>
</x:Array>
<!--File (the icon is free to use if we include this information in our credit section)
Source: https://www.flaticon.com/authors/chanut
Ttile: Cancel free icon
@@ -290,10 +334,6 @@
M0,0L25.194,16 0,32z
</sys:String>
<sys:String x:Key="{x:Static mbts:Icons.RubberStampGeometryKey}">
M1.8950181,29.607025L24.423994,29.607025 24.423994,31.103027C24.423994,31.601013,24.025009,32,23.526993,32L2.7920208,32C2.2929976,32,1.8950181,31.601013,1.8950181,31.103027z M0,19.838013L26.218001,19.838013 26.218001,27.813019 0,27.813019z M12.960014,0C16.549,0 19.538988,2.9909973 19.538988,6.57901 19.538988,8.0750122 19.041002,9.3710022 18.243,10.46701L18.043995,10.766022C17.345997,11.863007 16.647999,12.76001 16.647999,12.76001 15.052999,15.651001 15.253011,17.745026 15.253011,17.745026L10.667015,17.745026C10.667015,17.745026 10.866997,15.651001 9.2719967,12.76001 9.2719967,12.76001 8.5739996,11.863007 7.8760016,10.766022L7.6759898,10.46701 7.5769908,10.368011C6.7790176,9.3710022 6.3810074,7.9750061 6.3810074,6.57901 6.3810074,2.9909973 9.2719967,0 12.960014,0z
</sys:String>
<!--File (the icon is free to use if we include this information in our credit section)
Source: https://www.flaticon.com/authors/smashicons
Ttile: File free icon
@@ -204,15 +204,13 @@ namespace mbts.spark {
}
}
void _show_order_book(Side side) {
var ob_settings = bts.shell.orderbook.OrderBookStartupData.Default;
ob_settings.filters = new bts.shell.orderbook.FilterStates {
statuses = new[] { OrderStatus.Working },
sides = new[] { side },
security_criteria = new SecurityCriteria(security)
};
_bus.post(SparkTags.ShowOrderBookTag, ob_settings);
}
void _show_order_book(Side side) =>
_bus.post(SparkTags.ShowOrderBookTag, new bts.shell.orderbook.OrderBookStartupData(
new bts.shell.orderbook.FilterStates {
statuses = new[] { OrderStatus.Working },
sides = new[] { side },
security_criteria = new SecurityCriteria(security)
}));
void _show_order_ticket(MarketViewView.Columns col) {
var order = _orders_model.factory.order(security);
@@ -1,6 +1,5 @@
using bts.api;
using bts.collections;
using bts.utils;
using mbts.persist;
using mbts.spark.filters;
using mbts.ui;
@@ -23,6 +22,7 @@ namespace mbts.spark {
readonly OrdersModel _orders_model;
IWindowSettingsManager<GridSettings> _settings_manager;
public MarketViewVM(IBus bus, OrdersModel orders_model, IObservable<StartupData> state, IWindowSettingsManager<GridSettings> settings_manager )
: this(bus, orders_model, state, state.SelectManyInSeries(s => s.security_criteria.subscribe_md(bus)), settings_manager) { }
@@ -58,12 +58,12 @@ namespace mbts.spark {
add_col(Columns.SessionHigh, "High", r => r.format_price(r.session_high), nameof(Row.session_high), DefaultColumnWidths.Price, session_high_filter, DataGridFilterKnownTemplates.DoubleMinMax, h_alignment: System.Windows.HorizontalAlignment.Right);
add_col(Columns.SecurityKey, "Security Key", r => r.security_key.ToString(), nameof(Row.security_key), DefaultColumnWidths.SecurityKey, security_key_filter, DataGridFilterKnownTemplates.Regex);
add_col(Columns.MarketDescription, "Market Description", r => r.security.market_description(), nameof(Row.market_description), DefaultColumnWidths.SecurityKey, market_description_filter, DataGridFilterKnownTemplates.Regex);
add_col(Columns.ClearedAlias, "Cleared Alias", r => r.security.cleared_alias(), nameof(Row.cleared_alias), DefaultColumnWidths.SecurityKey, cleared_alias_filter, DataGridFilterKnownTemplates.Regex);
add_col(Columns.ProductDescription, "Product Description", r => r.security.product_name(), nameof(Row.product_description), DefaultColumnWidths.SecurityKey, product_description_filter, DataGridFilterKnownTemplates.Regex);
add_col(Columns.HubAlias, "Hub Alias", r => r.security.hub_alias(), nameof(Row.hub_alias), DefaultColumnWidths.SecurityKey, hub_alias_filter, DataGridFilterKnownTemplates.Regex);
add_col(Columns.StripName, "Strip Name", r => r.security.strip_name(), nameof(Row.strip_name), DefaultColumnWidths.SecurityKey, strip_name_filter, DataGridFilterKnownTemplates.Regex);
add_col(Columns.MicCode, "Mic Code", r => r.security.mic_code(), nameof(Row.mic_code), DefaultColumnWidths.SecurityKey, mic_code_filter, DataGridFilterKnownTemplates.Regex);
add_col(Columns.MarketDescription, "Market Description", r => r.md.security.HasIce ? r.md.security.Ice.MarketDescription : string.Empty, nameof(Row.market_description), DefaultColumnWidths.SecurityKey, market_description_filter, DataGridFilterKnownTemplates.Regex);
add_col(Columns.ClearedAlias, "Cleared Alias", r => r.md.security.HasIce ? r.md.security.Ice.ClearedAlias : string.Empty, nameof(Row.cleared_alias), DefaultColumnWidths.SecurityKey, cleared_alias_filter, DataGridFilterKnownTemplates.Regex);
add_col(Columns.ProductDescription, "Product Description", r => r.md.security.HasIce ? r.md.security.Ice.ProductName : string.Empty, nameof(Row.product_description), DefaultColumnWidths.SecurityKey, product_description_filter, DataGridFilterKnownTemplates.Regex);
add_col(Columns.HubAlias, "Hub Alias", r => r.md.security.HasIce ? r.md.security.Ice.HubAlias : string.Empty, nameof(Row.hub_alias), DefaultColumnWidths.SecurityKey, hub_alias_filter, DataGridFilterKnownTemplates.Regex);
add_col(Columns.StripName, "Strip Name", r => r.md.security.HasIce ? r.md.security.Ice.StripName : string.Empty, nameof(Row.strip_name), DefaultColumnWidths.SecurityKey, strip_name_filter, DataGridFilterKnownTemplates.Regex);
add_col(Columns.MicCode, "Mic Code", r => r.md.security.HasIce ? r.md.security.Ice.MicCode : string.Empty, nameof(Row.mic_code), DefaultColumnWidths.SecurityKey, mic_code_filter, DataGridFilterKnownTemplates.Regex);
//
void add_col(Columns col_key, string header, Func<Row, string> get_text, string prop, double width, IDataGridColumnFilter filter, string filter_template, bool is_animatable = false, Color? font_color = null, System.Windows.HorizontalAlignment h_alignment = System.Windows.HorizontalAlignment.Left) =>
columns.Add(new RenderTextColumn<Row, Columns>(col_key, get_text, filter, filter_template) {
@@ -180,40 +180,6 @@ namespace mbts.spark {
return grid_settings_manager.create();
}
public static IComparer<Row> get_column_comparer(Columns column) {
switch (column) {
case Columns.Security: return wrap(r => r.security);
case Columns.SecurityKey: return wrap(r => r.security.Id);
case Columns.Volume: return wrap(r => r.volume);
case Columns.Last: return wrap(r => r.last_price);
case Columns.LastSize: return wrap(r => r.last_size);
case Columns.Position: return wrap(r => r.position);
case Columns.WorkingBids: return wrap(r => r.working_bid_volume);
case Columns.BidImpliedSize: return wrap(r => r.bid_implied_size);
case Columns.BidDirectSize: return wrap(r => r.bid_direct_size);
case Columns.BidMergedSize: return wrap(r => r.bid_merged_size);
case Columns.Bid: return wrap(r => r.bid_price);
case Columns.Ask: return wrap(r => r.ask_price);
case Columns.AskMergedSize: return wrap(r => r.ask_merged_size);
case Columns.AskDirectSize: return wrap(r => r.ask_direct_size);
case Columns.AskImpliedSize: return wrap(r => r.ask_implied_size);
case Columns.WorkingAsks: return wrap(r => r.working_ask_volume);
case Columns.Settlement: return wrap(r => r.settlement);
case Columns.DayChange: return wrap(r => r.day_change);
case Columns.SessionLow: return wrap(r => r.session_low);
case Columns.SessionHigh: return wrap(r => r.session_high);
case Columns.MarketDescription: return wrap(r => r.market_description);
case Columns.ClearedAlias: return wrap(r => r.security.cleared_alias());
case Columns.ProductDescription: return wrap(r => r.security.product_name());
case Columns.HubAlias: return wrap(r => r.security.hub_alias());
case Columns.StripName: return wrap(r => r.security.strip_name());
case Columns.MicCode: return wrap(r => r.security.mic_code());
default: return null;
}
IComparer<Row> wrap<T>(Func<Row, T> selector) =>
Comparer<T>.Default.wrap(selector);
}
#region Filters
public IDataGridColumnPersistentFilter<Row, string> security_filter { get; }
public IDataGridColumnPersistentFilter<Row, DoubleMinMaxState> bid_price_filter { get; } = new DoubleMinMax<Row>(r => r.bid_price, nameof(Row.bid_price));
@@ -2,7 +2,6 @@
using bts.api;
using bts.shell;
using bts.spark;
using bts.utils;
using mbts.persist;
using mbts.ui;
using mbts.ui.settings;
@@ -12,12 +11,11 @@ using mbts.utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reactive.Disposables;
using System.Reactive.Linq;
using System.Windows;
namespace mbts.spark {
class MarketViewWindow : SparkWindow<MarketViewWindowFactory.StartupData>, ISharedWindow, ISlowMeasureContentSize {
class MarketViewWindow : SparkWindow<MarketViewWindowFactory.StartupData>, ISharedWindow {
const string _window_type = "MarketView", _window_type_display_name = "Market View";
readonly OrdersModel _orders_model;
readonly AllowOnce _init_guard = new AllowOnce("MarketView");
@@ -27,9 +25,6 @@ namespace mbts.spark {
MarketViewWindowFactory.StartupData _state;
IReadOnlyList<SparkCommand> _commands;
IDisposable _subscriptions;
SecurityCriteria
_selected_security_criteria_backing,
_sorted_selected_security_criteria_backing;
public MarketViewWindow(MarketViewWindowFactory factory, IBus bus, OrdersModel orders_model, MarketViewWindowFactory.StartupData state, WindowSettingsManager<GridSettings> settings_manager)
: base("Market View", bus, factory, SparkCommands.ShowMarketView.icon) {
@@ -55,91 +50,23 @@ namespace mbts.spark {
public string thread_id { get; }
SecurityCriteria _selected_security_criteria {
get {
if (_selected_security_criteria_backing == null) {
if (_sorted_selected_security_criteria_backing != null) {
_selected_security_criteria_backing = _sorted_selected_security_criteria_backing;
} else if (_vm != null)
_selected_security_criteria_backing = new SecurityCriteria(_vm.selected_rows.Select(r => r.security));
}
return _selected_security_criteria_backing;
}
}
SecurityCriteria _sorted_selected_security_criteria {
get {
if (_sorted_selected_security_criteria_backing == null) {
if (_vm != null) {
var sorting_criteria = _vm.rows_view.get_sorting_criteria(_vm.columns);
var comp_builder = new ComparerBuilder<MarketViewVM.Row>();
foreach (var sc in sorting_criteria) {
if (_vm.columns.TryGetFirst(col => string.Equals(col.id, sc.col_name, StringComparison.CurrentCultureIgnoreCase), out var match)) {
if (match is ui.controls.DIYGrid.IKeyedColumn<MarketViewView.Columns> kcol) {
var col_comp = MarketViewVM.get_column_comparer(kcol.key);
if (col_comp != null) {
comp_builder.add(sc.is_ascending ? col_comp : col_comp.reverse());
} else {
Log.Ui.warn($"{_window_type} is unable to find the row comparer for the '{sc.col_name}' column.");
}
} else {
Log.Ui.warn($"{_window_type} is unable find a column with id '{sc.col_name}.'");
}
}
}
var comp = comp_builder.to_comparer();
_sorted_selected_security_criteria_backing = new SecurityCriteria(_vm.selected_rows.Ordered(comp).Select(r => r.security));
}
}
return _sorted_selected_security_criteria_backing;
}
}
bool _has_selected_rows() => _vm != null && _vm.selected_rows.Count > 0;
public void thread_init() {
_init_guard.check_access();
Log.notnull(_state);
var state_src = Observable.FromEvent<Action<MarketViewWindowFactory.StartupData>, MarketViewWindowFactory.StartupData>(cb => _state_changed += cb, cb => _state_changed -= cb).StartWith(_state);
_vm = new MarketViewVM(_bus, _orders_model, state_src, _settings_manager);
_view = new MarketViewView { DataContext = _vm };
_view._grid.Sorting += on_grid_sorting;
/// The 'CanExecute' plumbing for the cmds below is designed to avoid potentially costly .ToList() operations on the selected_rows/securities.
/// Some of the cmds post ITags with data that is, or has, a SecurityCriteria member; the SecurityCriteria constructor creates a new List of the specified securities.
/// For these commands, the objective is to evaluate 'CanExecute' without instantiating the SecurityCriteria (or more importantly, without creating a new List).
// show time and sales
var show_tas_cmd = new DelegateCommand(() => {
var sc = _selected_security_criteria;
if (sc.is_defined())
_bus.post(SparkTags.ShowTimeAndSalesTag, sc);
}, _has_selected_rows);
var show_tas_actual_cmd = SparkCommands.ShowTimeAndSales;
var show_tas_cmd_wrapper = new SparkCommandCommand(show_tas_actual_cmd.title, show_tas_actual_cmd.icon, show_tas_cmd);
// show fills
var show_fills_cmd = new DelegateCommand(() => {
var sc = _selected_security_criteria;
_bus.post(SparkTags.ShowFillsTag, new FillsWindowFactory.StartupData(
new FillsWindowFactory.FilterStates {
security = sc.is_defined() ? sc : _state.security_criteria
}));
});
var show_fills_actual_cmd = SparkCommands.ShowFills();
var show_fills_cmd_wrapper = new SparkCommandCommand(show_fills_actual_cmd.title, show_fills_actual_cmd.icon, show_fills_cmd, SparkCommands.KeyGestures.ShowFills);
// show synthetic create
var show_synth_create_cmd = new DelegateCommand(() => {
var sc = _sorted_selected_security_criteria;
if (sc.is_defined())
_bus.post(SparkTags.ShowSyntheticCreateTag, sc);
}, () => _vm.selected_rows.Count > 0 && _vm.selected_rows.Count <= 24);
var show_synth_create_actual_cmd = SparkCommands.ShowSyntheticCreate();
var show_synth_create_cmd_wrapper = new SparkCommandCommand(show_synth_create_actual_cmd.title, show_synth_create_actual_cmd.icon, show_synth_create_cmd, SparkCommands.KeyGestures.ShowSyntheticCreate);
var update_securities_cmd = SparkCommands.change_securities_callback(_window_type_display_name);
_commands = new List<SparkCommand> {
SparkCommands.ShowLadders(SparkCommands.KeyGestures.ShowLadder).complete(_vm.selected_security_mds_observable(), smds => smds.Count > 0),
SparkCommands.ShowOrderTicketFromSecurity(SparkCommands.KeyGestures.ShowOrderTicket).complete(_vm.current_security_md, md => md.HasValue, ConvertUtils.ValueOrDefault),
show_fills_cmd_wrapper,
show_tas_cmd_wrapper,
show_synth_create_cmd_wrapper,
SparkCommands.ShowFills(SparkCommands.KeyGestures.ShowFills).complete(_vm.selected_securities_observable(), _ => true,
secs => new FillsWindowFactory.StartupData(new FillsWindowFactory.FilterStates {
security = secs.Count > 0 ? new SecurityCriteria(secs) : _state.security_criteria
})
),
SparkCommands.ShowTimeAndSales.complete(_vm.selected_securities_observable(), _ => true, secs => secs.Count > 0 ? new SecurityCriteria(secs) : _state.security_criteria),
SparkCommands.ShowSyntheticCreate(SparkCommands.KeyGestures.ShowSyntheticCreate).complete(_vm.sorted_selected_securities_observable(), secs => secs.Count > 0 && secs.Count <= 24, secs => new SecurityCriteria(secs)),
SparkCommands.change_securities_command(() => (update_securities_cmd, _state.security_criteria)),
// wrap the grid settings view factory in a dialogCommand here since the vm is destroyed/recreated when the security criteria changes
SparkCommands.window_settings_command(new DialogCommand(() => {
@@ -160,27 +87,8 @@ namespace mbts.spark {
return dialog;
}))
};
//
_vm.selection_changed += on_selection_changed;
_subscriptions = new CompositeDisposable(_bus.subscribe(update_securities_cmd.tag).OnDispatcher().Subscribe(c =>
_state_changed?.Invoke(_state = new MarketViewWindowFactory.StartupData(c, _vm.get_filter_states(), _vm.grid_settings_manager.create())))) {
() => {
_vm.selection_changed -= on_selection_changed;
_view._grid.Sorting -= on_grid_sorting;
}
};
void on_selection_changed((IEnumerable<MarketViewVM.Row> removed, IEnumerable<MarketViewVM.Row> added) change) {
// invalidate selected security criteria
_selected_security_criteria_backing = null;
_sorted_selected_security_criteria_backing = null;
show_tas_cmd.RaiseCanExecuteChanged();
show_fills_cmd.RaiseCanExecuteChanged();
show_synth_create_cmd.RaiseCanExecuteChanged();
}
void on_grid_sorting(object sender, ui.controls.DIYGridSortingEventArgs e) =>
_sorted_selected_security_criteria_backing = null;
_subscriptions = _bus.subscribe(update_securities_cmd.tag).OnDispatcher().Subscribe(c =>
_state_changed?.Invoke(_state = new MarketViewWindowFactory.StartupData(c, _vm.get_filter_states(), _vm.grid_settings_manager.create())));
}
public override void Dispose() {
@@ -12,9 +12,6 @@
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="/Modules/Spreader/ExecutionStrategyEditor.xaml"/>
</ResourceDictionary.MergedDictionaries>
<Style TargetType="ScrollViewer">
<Setter Property="u:ScrollViewerCorrector.FixNestedScrolling" Value="False"/>
</Style>
</ResourceDictionary>
</Window.Resources>
<Grid>
@@ -68,13 +68,12 @@ namespace mbts.spark {
rs => rs.HasValue, select_row_strategy_tuple
), SparkCommands.ShowLadder(SparkCommands.KeyGestures.ShowLadder).complete(
vm_connectable_builder.create(vm => vm.current_security_md), md => md.HasValue, ConvertUtils.ValueOrDefault
), SparkCommands.ShowOrders.complete(() => {
var ob_settings = bts.shell.orderbook.OrderBookStartupData.Default;
ob_settings.filters = new bts.shell.orderbook.FilterStates {
security_criteria = new SecurityCriteria(_vm.value.row_vms.Select(r => r.security))
};
return ob_settings;
}), SparkCommands.window_settings_command(new DialogCommand(() => {
), SparkCommands.ShowOrders.complete(() => new bts.shell.orderbook.OrderBookStartupData {
filters = new bts.shell.orderbook.FilterStates {
security_criteria = new SecurityCriteria(_vm.value.row_vms.Select(r => r.security))
}
}
), SparkCommands.window_settings_command(new DialogCommand(() => {
var vm = new WindowSettingsDialogVM<GridSettings, SimpleGridSettingsVM>(
_settings_manager,
us => us.synthetic_management_grid,
@@ -168,13 +168,12 @@ namespace mbts.spark {
void _show_ladder() =>
_bus.post(SparkTags.ShowLadderTag, md);
void _show_order_book() {
var ob_settings = bts.shell.orderbook.OrderBookStartupData.Default;
ob_settings.filters = new bts.shell.orderbook.FilterStates {
security_criteria = new SecurityCriteria(security)
};
_bus.post(SparkTags.ShowOrderBookTag, ob_settings);
}
void _show_order_book() =>
_bus.post(SparkTags.ShowOrderBookTag, new bts.shell.orderbook.OrderBookStartupData {
filters = new bts.shell.orderbook.FilterStates {
security_criteria = new SecurityCriteria(security)
}
});
}
}
}
@@ -36,23 +36,4 @@ namespace mbts.spark {
public static bool operator ==(AlgoData a, AlgoData b) => a.Equals(b);
public static bool operator !=(AlgoData a, AlgoData b) => !a.Equals(b);
}
struct AlgoDataVM : IEquatable<AlgoDataVM> {
public readonly AlgoData data;
public AlgoDataVM(AlgoData data) =>
this.data = data;
public AlgoDisplayGroup group => data.key.display_group();
public override string ToString() =>
data.name;
public static AlgoDataVM from_data(AlgoData data) =>
new AlgoDataVM(data);
public bool Equals(AlgoDataVM other) => data == other.data;
public override bool Equals(object obj) => obj is AlgoDataVM other && Equals(other);
public override int GetHashCode() => data.GetHashCode();
}
}
@@ -1,76 +1,9 @@
using bts.api.orderman;
using bts.persist.algo;
using bts.utils;
using ProtoBuf;
using System;
namespace mbts.spark {
[ProtoContract]
struct AlgoID : IEquatable<AlgoID> {
[ProtoMember(1)]
readonly CustomOrderDefinition.CustomOneofCase? _factory_key;
[ProtoMember(2)]
readonly string _dynamic_key;
[ProtoMember(3)]
readonly uint? _persisted_key;
public AlgoID(CustomOrderDefinition.CustomOneofCase factory_key) {
_factory_key = factory_key;
_dynamic_key = null;
_persisted_key = null;
}
public AlgoID(string dynamic_key) {
_factory_key = null;
_dynamic_key = dynamic_key;
_persisted_key = null;
}
public AlgoID(uint persisted_key) {
_factory_key = null;
_dynamic_key = null;
_persisted_key = persisted_key;
}
public static AlgoID from_order_def(OrderDefinitionImmutable order_def) {
switch (order_def.CustomDef.CustomCase) {
case CustomOrderDefinition.CustomOneofCase.Composite: return new AlgoID(order_def.CustomDef.Composite.AlgoTemplateKey);
case CustomOrderDefinition.CustomOneofCase.Dynamic: return new AlgoID(order_def.CustomDef.Dynamic.DynamicOrderType);
default: return new AlgoID(order_def.CustomDef.CustomCase);
}
}
public static AlgoID from_algo_key(AlgoKey key) {
switch (key.mode) {
case AlgoKey.Mode.Factory:
if (key.factory.structure.structure.Count > 0)
return new AlgoID((CustomOrderDefinition.CustomOneofCase)key.factory.structure.structure[0]);
break;
case AlgoKey.Mode.Persisted:
return new AlgoID(key.persisted.id_uint);
}
return new AlgoID(CustomOrderDefinition.CustomOneofCase.None);
}
public bool Equals(AlgoID other) =>
_factory_key == other._factory_key &&
_dynamic_key == other._dynamic_key &&
_persisted_key == other._persisted_key;
public override bool Equals(object obj) =>
obj is AlgoID && Equals(obj);
public override int GetHashCode() =>
EqualityComparer.aggregate_hash(
_factory_key?.GetHashCode() ?? 0,
_dynamic_key?.GetHashCode() ?? 0,
_persisted_key?.GetHashCode() ?? 0);
public static bool operator ==(AlgoID a, AlgoID b) => a.Equals(b);
public static bool operator !=(AlgoID a, AlgoID b) => !a.Equals(b);
}
/// TODO: Remove <see cref="AlgoKey"/>, and redirect references to <see cref="AlgoID"/>.
struct AlgoKey : IEquatable<AlgoKey> {
readonly AlgoPersistedKey? _persisted_key;
readonly AlgoNameStructureKey? _factory_key;
@@ -150,4 +83,4 @@ namespace mbts.spark {
InvalidOperationException _unexpected_mode_ex() => new InvalidOperationException($"Unexpected Mode '{mode}.'");
}
}
}
@@ -70,9 +70,6 @@ namespace mbts.spark {
public static CustomOrderDefinitionImmutable build_algo(this AlgoStructureKey structure_key, DynamicOrderHelper dynamic_helper) =>
parsei(structure_key.structure, dynamic_helper);
public static CustomOrderDefinition.CustomOneofCase order_type(this AlgoStructureKey structure_key) =>
structure_key.structure.Count > 0 ? (CustomOrderDefinition.CustomOneofCase)structure_key.structure[0] : CustomOrderDefinition.CustomOneofCase.None;
public static AlgoStructureKey structure_key(CustomOrderDefinitionImmutable algo, IMaskIndexInt32<string> dynamic_type_index) =>
new AlgoStructureKey(to_array(algo, dynamic_type_index));
@@ -70,7 +70,7 @@ namespace mbts.spark {
is_hidden.GetHashCode(),
abbreviation == null ? 0 : abbreviation.GetHashCode(),
badge_color?.GetHashCode() ?? 0,
_favorite_templates == null ? 0 : EqualityComparer.aggregate_hash_limited(_favorite_templates));
EqualityComparer.aggregate_hash_limited(_favorite_templates));
public static bool operator ==(AlgoDefinitionMetadata a, AlgoDefinitionMetadata b) => a.Equals(b);
public static bool operator !=(AlgoDefinitionMetadata a, AlgoDefinitionMetadata b) => !a.Equals(b);
@@ -1,36 +1,23 @@
using bts.api.core;
using bts.api.orderman;
using bts.utils;
using mbts.collections;
using mbts.ui.utilities;
using mbts.utils;
using System;
using System.Collections.Generic;
using System.Linq;
namespace mbts.spark {
static class AlgoCollectionHelper {
public static readonly IComparer<AlgoDefinitionVM> algo_definition_vm_comparer =
new ComparerBuilder<AlgoDefinitionVM>(
new[] {
new [] {
Comparer<AlgoDefinitionVM>.Create(_CompareUtils.compare_groups),
Comparer<AlgoDefinitionVM>.Create(_CompareUtils.compare_names)
}).to_comparer().to_safe();
public static readonly IComparer<AlgoData> algo_data_comparer =
new ComparerBuilder<AlgoData>(
new[] {
Comparer<AlgoData>.Create(_CompareUtils.compare_groups),
Comparer<AlgoData>.Create(_CompareUtils.compare_names)
}
).to_comparer();
public static readonly IComparer<AlgoDataVM> algo_data_vm_comparer =
algo_data_comparer.wrap<AlgoData, AlgoDataVM>(vm => vm.data);
public static readonly IComparer<IAlgoVM> algo_vm_comparer =
new ComparerBuilder<IAlgoVM>(
new[] {
new [] {
Comparer<IAlgoVM>.Create(_CompareUtils.compare_groups),
Comparer<IAlgoVM>.Create(_CompareUtils.compare_names)
}).to_comparer().to_safe();
@@ -59,34 +46,6 @@ namespace mbts.spark {
}
}
public static void commit_all(this IEnumerable<AlgoParamRowVM> algo_param_rows) =>
algo_param_rows.Select(r => r.param).commit_all();
public static void commit_all(this IEnumerable<IAlgoParamVM> algo_params) {
foreach (var p in algo_params)
p.mark_committed();
}
public static void revert_all(this IEnumerable<AlgoParamRowVM> algo_param_rows) =>
algo_param_rows.Select(r => r.param).revert_all();
public static void revert_all(this IEnumerable<IAlgoParamVM> algo_params) {
foreach (var p in algo_params)
p.revert();
}
public static AlgoDisplayGroup display_group(CustomOrderDefinition.CustomOneofCase order_type) => order_type.is_bts_algo_type() ? AlgoDisplayGroup.BTS : AlgoDisplayGroup.Exchange;
public static AlgoDisplayGroup display_group(this AlgoKey key) {
switch (key.mode) {
case AlgoKey.Mode.Factory: return display_group(key.factory.structure.order_type());
case AlgoKey.Mode.Unpersisted:
case AlgoKey.Mode.Persisted:
return AlgoDisplayGroup.Studio;
}
return AlgoDisplayGroup.BTS;
}
static class _CompareUtils {
static AlgoDisplayGroup[] _sorted_groups = new[] {
AlgoDisplayGroup.Exchange,
@@ -98,18 +57,12 @@ namespace mbts.spark {
public static int compare_groups(AlgoDefinitionVM a, AlgoDefinitionVM b) =>
Array.IndexOf(_sorted_groups, a.group).CompareTo(Array.IndexOf(_sorted_groups, b.group));
public static int compare_groups(AlgoData a, AlgoData b) =>
Array.IndexOf(_sorted_groups, a.key.display_group()).CompareTo(Array.IndexOf(_sorted_groups, b.key.display_group()));
public static int compare_groups(IAlgoVM a, IAlgoVM b) =>
Array.IndexOf(_sorted_groups, a.group).CompareTo(Array.IndexOf(_sorted_groups, b.group));
public static int compare_names(AlgoDefinitionVM a, AlgoDefinitionVM b) =>
DisplayNameHelper.compare_alpha_numeric(a.name, b.name);
public static int compare_names(AlgoData a, AlgoData b) =>
DisplayNameHelper.compare_alpha_numeric(a.name, b.name);
public static int compare_names(IAlgoVM a, IAlgoVM b) =>
DisplayNameHelper.compare_alpha_numeric(a.display_name, b.display_name);
}
@@ -372,12 +372,7 @@ namespace mbts.spark {
}
public void load_many(IEnumerable<CustomOrderDefinitionImmutable> defs) {
/// don't load composite algos; we don't support recursive composites (<see cref="OrderUtils.actual(CustomOrderDefinitionImmutable)"/>)
if (defs is IList<CustomOrderDefinitionImmutable> def_list) {
def_list = def_list.WrapSelector(d => d.actual(), null);
} else {
def_list = defs.Select(d => d.actual()).ToList();
}
var def_list = defs as IList<CustomOrderDefinitionImmutable> ?? defs.ToList();
switch (def_list.Count) {
case 0: algo_root = null; break;
case 1: load_def(def_list[0]); break;
@@ -377,7 +377,7 @@
<DataTemplate>
<ComboBox
HorizontalAlignment="Stretch"
ItemsSource="{Binding Converter={x:Static usp:AlgoEditorGridView.NullableEnumParamRowItemsSourceConverter}}"
ItemsSource="{Binding param.value, Converter={StaticResource EnumItemsSourceConverter}, Mode=OneTime}"
ItemTemplate="{StaticResource NullableEnumDescriptionTemplate}"
SelectedItem="{Binding param.value, UpdateSourceTrigger=PropertyChanged}"
/>
@@ -481,14 +481,10 @@
<usp:AlgoEditorGridRowStyleSelector.DefaultStyle>
<Style TargetType="DataGridRow">
<Style.Triggers>
<MultiDataTrigger>
<MultiDataTrigger.Conditions>
<Condition Binding="{Binding param.is_dirty}" Value="{u:True}"/>
<Condition Binding="{Binding AnimateDirty, RelativeSource={RelativeSource AncestorType=usp:AlgoEditorGridView}}" Value="{u:True}"/>
</MultiDataTrigger.Conditions>
<DataTrigger Binding="{Binding param.is_dirty}" Value="{u:True}">
<Setter Property="Background" Value="#8098FB98"/>
<Setter Property="ToolTip" Value="Value has been modified."/>
</MultiDataTrigger>
</DataTrigger>
</Style.Triggers>
</Style>
</usp:AlgoEditorGridRowStyleSelector.DefaultStyle>
@@ -5,8 +5,8 @@ using mbts.ui.controls;
using mbts.ui.converters;
using mbts.ui.utility;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
@@ -19,19 +19,7 @@ namespace mbts.ui.spark {
public static readonly IValueConverter
GeneralVisualStateConverter = ValueConverter.create<bool, string>(is_read_only => is_read_only ? VisualStateNames.General.ReadOnly : VisualStateNames.General.Normal),
AlgoRootVisualStateConverter = ValueConverter.create<bool, string>(show_bbo => show_bbo ? VisualStateNames.AlgoRoot.Active : VisualStateNames.AlgoRoot.Inactive),
AlgoRootComboBoxMarginConverter = ValueConverter.create<double, Thickness>(name_col_width => new Thickness(name_col_width + 8, 0, 0, 0)),
NullableEnumParamRowItemsSourceConverter = ValueConverter.create<AlgoParamRowVM, IEnumerable>(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<T>.
tenum = tenum.GetGenericArguments().First();
}
if (tenum.IsEnum)
return Enum.GetValues(tenum);
}
return null;
});
AlgoRootComboBoxMarginConverter = ValueConverter.create<double, Thickness>(name_col_width => new Thickness(name_col_width + 8, 0, 0, 0));
public static readonly MouseButtonEventHandler PayupTicksMouseButtonHandler = (s, e) => {
if ((s as Hyperlink)?.Command is ICommand cmd) {
@@ -76,16 +64,6 @@ namespace mbts.ui.spark {
}
}
#region AnimateDirtyParams
public static readonly DependencyProperty AnimateDirtyProperty =
WPFHelper.create_dp<bool, AlgoEditorGridView>(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<bool, AlgoEditorGridView>(nameof(IsReadOnly));
@@ -19,8 +19,6 @@ namespace mbts.ui.spark {
/// TODO: remove this class and just use a <see cref="KeyedTemplateSelector"/>.
class AlgoParamTemplateSelector : DataTemplateSelector {
public static readonly Type generic_algo_param_itype = typeof(IAlgoParamVM<>);
KeyedCollection<TemplateSelectorKeyValue, string> _keyed_templates = new KeyedCollection<TemplateSelectorKeyValue, string>(tsk => tsk.Key);
public DataTemplate BoolTemplate { get; set; }
@@ -60,7 +58,7 @@ namespace mbts.ui.spark {
if (pvm is IAlgoParamVM<QuantityMeasureImmutable?>) return QuantityMeasureTemplate;
if (pvm is IAlgoParamVM<ExecutionStrategy>) return ExecutionStrategyTemplate;
if (pvm is IAlgoParamVM<Google.Protobuf.WellKnownTypes.Timestamp>) return TimestampTemplate;
var targ = ReflectionHelper.GetGenericTypeArgs(pvm.GetType(), generic_algo_param_itype).FirstOrDefault();
var targ = ReflectionHelper.GetGenericTypeArgs(pvm.GetType(), typeof(IAlgoParamVM<>)).FirstOrDefault();
if (targ != null) {
if (targ.IsEnum)
return EnumTemplate;
@@ -2,8 +2,11 @@
using bts.api;
using bts.api.core;
using bts.api.orderman;
using bts.collections;
using mbts.co2;
using System;
using System.Collections.Generic;
using System.Reactive.Linq;
using System.Threading.Tasks;
namespace mbts.spark {
@@ -13,9 +16,9 @@ namespace mbts.spark {
public LadderModel(SecurityMD source, OrdersModel ordergw, Func<OrderSecurity, bool> order_filter = null) {
security_md = source;
_order_gateway = ordergw;
orders = ordergw.on_security_working_orders_with_piq(source.security.Id);
orders = ordergw.on_security_working_orders(source.security.Id);
if (order_filter != null)
orders = orders.Filter(order_filter, o => o.order.Key);
orders = orders.Filter(o => order_filter(new OrderSecurity(source.security, o)), o => o.Key);
}
public enum CancelType { All, Bids, Asks }
@@ -24,7 +27,7 @@ namespace mbts.spark {
public SecurityImmutable security => security_md.security;
public MDConsumerHandle md => security_md.md;
public OrdersModel order_gateway => _order_gateway;
public IObservable<TableUpdate<OrderSecurity, uint>> orders { get; }
public IObservable<TableUpdate<OrderRecordImmutable, uint>> orders { get; }
public Task cancel_orders(CancelType ct) {
switch (ct) {
@@ -46,9 +46,9 @@ namespace mbts.spark {
int working_quantity;
LadderModel model => _owner.model;
Dictionary<uint, (OrderRecordImmutable order, uint? p, AlgoData? algo, AlgoDefinitionMetadata? meta)> _orders = new Dictionary<uint, (OrderRecordImmutable order, uint? p, AlgoData? algo, AlgoDefinitionMetadata? meta)>();
Dictionary<uint, (OrderRecordImmutable order, uint? p, AlgoDefinitionMetadata? meta)> _orders = new Dictionary<uint, (OrderRecordImmutable order, uint? p, AlgoDefinitionMetadata? meta)>();
public LadderOrderVM((OrderRecordImmutable, uint?, AlgoData?, AlgoDefinitionMetadata?) op, double real_price, LadderVM owner, IBus bus, IObservable<LadderSettings.BadgeStyle> bs) {
public LadderOrderVM((OrderRecordImmutable, uint?, AlgoDefinitionMetadata?) op, double real_price, LadderVM owner, IBus bus, IObservable<LadderSettings.BadgeStyle> bs) {
_owner = owner;
_bus = bus;
_bs = bs;
@@ -114,7 +114,7 @@ namespace mbts.spark {
var single_order_metadata = _owner.model.order_gateway.factory.get_metadata(single_order);
border = single_order_metadata.Color.rgb_brush();
if (_orders.TryGetValue(single_order.Key, out var opm)) {
algo_studio_abbreviation = _sanitize_abbreviation(string.IsNullOrEmpty(opm.meta?.abbreviation) ? _generate_abbreviation_for_algo_studio_algo(opm.algo) : opm.meta?.abbreviation);
algo_studio_abbreviation = opm.meta?.abbreviation ?? string.Empty;
border = opm.meta?.badge_color?.rgb_color().rgb_brush() ?? border;
}
if (single_order.order_type().is_bts_algo_type()) {
@@ -131,34 +131,6 @@ namespace mbts.spark {
_set_badge_text();
string _generate_abbreviation_for_algo_studio_algo(AlgoData? a) {
char[] delim = { ' ' };
string candidate = string.Empty;
if (a.HasValue) {
var algo_name = a.Value.name;
var words = algo_name.Split(delim);
if (words.Length == 1) {
var single_word = words[0];
if (single_word.Length > 1) {
candidate = words[0];
} else {
candidate = single_word;
}
} else {
candidate = words.Take(2).Select(w => w.Substring(0, 1)).list_string(string.Empty);
}
}
return candidate.ToUpper();
}
string _sanitize_abbreviation(string ab) {
string candidate = ab;
if (ab.Length > 2) {
candidate = candidate.Substring(0, 2);
}
return candidate.ToUpper();
}
}
private void _set_badge_text() {
@@ -166,7 +138,7 @@ namespace mbts.spark {
RaisePropertyChanged(nameof(text_lines));
}
public void add_order((OrderRecordImmutable order, uint? p, AlgoData? algo, AlgoDefinitionMetadata? meta) new_op) {
public void add_order((OrderRecordImmutable order, uint? p, AlgoDefinitionMetadata? meta) new_op) {
_orders[new_op.order.Key] = new_op;
}
@@ -146,10 +146,24 @@ namespace mbts.spark {
size_calculator = new CalculatorLogic(0, _settings_manager.subscribe_current().Select(s => s.calculator_buttons)),
bus.subscribe(SparkTags.LogActivity).OnDispatcher().Subscribe(status_update),
// we need to hook this up to model.orders which is filtered for just the security
model.orders.OnDispatcher().Subscribe(working => {
model.order_gateway.working_orders_with_piq.OnDispatcher().Subscribe(working => {
// Here we manage N orders to 1 price slot in the ladder
Dictionary<double, HashSet<uint>> orders_used_in_this_update = new Dictionary<double, HashSet<uint>>(_equality);
_cache = working.state;
// In master we originally had something similar to this snippet to restrict the foreach to just the orders
// for this ladder. In 1944, at one point we made use of model.orders, which made use of the on_security_working_orders demuxer.
// When we merged PIQ into 1944, we moved from that demuxer to working_orders_with_piq, so we reintroduce this little snippet here
// to once again restrict the processing to those working orders that match the criteria. Check with John to see if we can
// make a demuxer from working_orders_with_piq, which is an IReadOnlyDictionary; that probably won't work, but I have no doubt
// there is a better way.
var ladders_orders =
working.Values
.Where(o =>
o.order.Def.SecurityKey == security.Id &&
(o.order.HasState && o.order.State.DisplayStatus == OrderState.Types.DisplayStatus.Visible))
.ToReadOnlyDictionary(os => os.order.Key, os => os);
_cache = ladders_orders;
foreach (var os in _cache.Values) {
var wo = os.order;
@@ -166,9 +180,9 @@ namespace mbts.spark {
}
if (_slot_price_vs_orders.TryGetValue(slot_price_target, out LadderOrderVM slot_vm)) {
slot_vm.add_order((wo, os.piq, os.algo, os.meta));
slot_vm.add_order((wo, os.piq, os.meta));
} else {
slot_vm = new LadderOrderVM((wo, os.piq, os.algo, os.meta), slot_price_target, this, _bus, _settings_manager.subscribe_current().Select(s => s.badge_style));
slot_vm = new LadderOrderVM((wo, os.piq, os.meta), slot_price_target, this, _bus, _settings_manager.subscribe_current().Select(s => s.badge_style));
_slot_price_vs_orders[slot_price_target] = slot_vm;
}
@@ -312,7 +326,7 @@ namespace mbts.spark {
public uint volume_column_width { get => _volume_column_width.Value; set => _volume_column_width.set(value); }
internal LadderModel model => _model;
internal IObservable<LadderSettings> settings => _settings_manager.subscribe_current();
internal OrderRecordImmutable get_root_at_price((OrderRecordImmutable order, uint? _, AlgoData? __, AlgoDefinitionMetadata? meta) op) {
internal OrderRecordImmutable get_root_at_price((OrderRecordImmutable order, uint? _, AlgoDefinitionMetadata? meta) op) {
var order = op.order;
double p = order.price();
foreach (var o in lineage(order.ParentKey)) {
@@ -399,13 +413,12 @@ namespace mbts.spark {
}
void _show_book() {
var ob_settings = bts.shell.orderbook.OrderBookStartupData.Default;
ob_settings.filters = new bts.shell.orderbook.FilterStates {
security_criteria = new SecurityCriteria(security)
};
_bus.post(SparkTags.ShowOrderBookTag, ob_settings);
}
void _show_book() =>
_bus.post(SparkTags.ShowOrderBookTag, new bts.shell.orderbook.OrderBookStartupData {
filters = new bts.shell.orderbook.FilterStates {
security_criteria = new SecurityCriteria(security)
}
});
void _show_ticket() {
if (order_properties_vm != null)
@@ -141,8 +141,8 @@
<Setter Property="VerticalContentAlignment" Value="Top"/>
</Style>
</TabControl.ItemContainerStyle>
<!-- Column Settings Tab -->
<TabItem Header="Column Settings" VerticalAlignment="Stretch">
<!-- Fonts and Colors Tab -->
<TabItem Header="Fonts and Colors" VerticalAlignment="Stretch">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="27"/>
@@ -1,6 +1,5 @@
using bts;
using bts.api;
using bts.api.core;
using bts.api.orderman;
using bts.shell.orderbook;
using bts.utils;
@@ -28,7 +27,6 @@ using Columns = mbts.spark.OrderBookGridView.ColumnKeys;
using static mbts.ui.controls.DIYGrid;
using OrderType = bts.api.orderman.CustomOrderDefinition.CustomOneofCase;
using System.Windows.Input;
using System.Reactive.Disposables;
namespace mbts.spark {
// This interface is used to hide ColumnBase.SortDirection, and offer a SortDirection member that does NOT require a DependencyProperty lookup.
@@ -65,7 +63,6 @@ namespace mbts.spark {
partial class OrderBookVM {
public class OrderBookColumnCollection : ObservableCollection<ColumnBase>, IValueFactory<(FilterStates filters, IReadOnlyList<SortingCriteria> sorting)>, IDisposable {
readonly List<ICVOrderBookColumn> _active_comparers = new List<ICVOrderBookColumn>();
CompositeDisposable _resources = new CompositeDisposable();
public OrderBookColumnCollection(IBus bus, OrdersModel model, IObservable<(IEnumerable<SecurityImmutable> added, IEnumerable<SecurityImmutable> removed)> order_securities) {
// security
@@ -164,37 +161,12 @@ namespace mbts.spark {
nameof(OrderBookRowVM.time_in_force)),
DataGridFilterKnownTemplates.EnumValues,
_wrap_comparer(r => r.time_in_force)));
// (algo items)
var algo_items_source = model.subscribe_all_algos().SelectKeyValue(AlgoDataVM.from_data, d => AlgoID.from_algo_key(d.data.key)).OnDispatcher();
var algo_items_comp = AlgoCollectionHelper.algo_data_vm_comparer.to_non_generic();
var algo_items_group_desc = new PropertyGroupDescription(nameof(AlgoDataVM.group));
// order type
Add(order_type_column = new OrderBookOrderTypeColumn(
Columns.OrderType,
nameof(OrderBookRowVM.badge_fill),
nameof(OrderBookRowVM.display_name),
_wrap_comparer(r => r.order_type),
DiscreteValuesFilterVM.CreateTableUpdate<OrderSecurityAlgoMeta, AlgoDataVM, AlgoID>(
o => new AlgoDataVM(o.algo.GetValueOrDefault()),
o => AlgoID.from_order_def(o.order.Def),
vm => AlgoID.from_algo_key(vm.data.key), out var order_type_filter_observer, out var order_type_items_view)));
_resources.Add(algo_items_source.Subscribe(order_type_filter_observer));
order_type_items_view.CustomSort = algo_items_comp;
order_type_items_view.GroupDescriptions.Add(algo_items_group_desc);
// root algo type
Add(root_algo_type_column = new OrderBookOrderTypeColumn(
Columns.RootAlgoType,
nameof(OrderBookRowVM.root_algo_badge_fill),
nameof(OrderBookRowVM.root_algo_display_name),
_wrap_comparer(r => r.order_tuple.root_algo.value.CustomCase),
DiscreteValuesFilterVM.CreateTableUpdate<OrderSecurityAlgoMeta, AlgoDataVM, AlgoID>(
o => new AlgoDataVM(o.root_algo),
o => AlgoID.from_algo_key(o.root_algo.key),
vm => AlgoID.from_algo_key(vm.data.key), out var root_algo_type_observer, out var root_algo_type_items_view),
DefaultColumnHeaders.RootAlgoType));
_resources.Add(algo_items_source.Subscribe(root_algo_type_observer));
root_algo_type_items_view.CustomSort = algo_items_comp;
root_algo_type_items_view.GroupDescriptions.Add(algo_items_group_desc);
DiscreteValuesFilterVM.Create<OrderSecurityAlgoMeta, OrderType>(
utilities.OrderDataHelper.all_order_types,
ort => ort.order.order_type(),
nameof(OrderBookRowVM.order_type))));
// order sub type
Add(sub_type_column = new SimpleTextColumn<OrderSubType[]>(
Columns.SubType,
@@ -335,7 +307,6 @@ namespace mbts.spark {
public SimpleTextColumn<Venue[]> exchange_column { get; }
public SimpleTextColumn<TimeInForce[]> time_in_force_column { get; }
public OrderBookOrderTypeColumn order_type_column { get; }
public OrderBookOrderTypeColumn root_algo_type_column { get; }
public SimpleTextColumn<OrderSubType[]> sub_type_column { get; }
public SideColumn side_column { get; }
public SizeColumn qty_column { get; }
@@ -362,7 +333,6 @@ namespace mbts.spark {
exchanges = exchange_column.filter.get_state(),
tifs = time_in_force_column.filter.get_state(),
order_types = order_type_column.filter.get_state(),
root_algo_types = root_algo_type_column.filter.get_state(),
order_sub_types = sub_type_column.filter.get_state(),
sides = side_column.filter.get_state(),
qty = qty_column.filter.get_state(),
@@ -392,7 +362,6 @@ namespace mbts.spark {
filled_qty_column.filter.load_state(fs.qty_filled);
side_column.filter.load_state(fs.sides);
order_type_column.filter.load_state(fs.order_types);
root_algo_type_column.filter.load_state(fs.root_algo_types);
sub_type_column.filter.load_state(fs.order_sub_types);
time_in_force_column.filter.load_state(fs.tifs);
exchange_column.filter.load_state(fs.exchanges);
@@ -455,7 +424,6 @@ namespace mbts.spark {
}
public void Dispose() {
Disposable.dispose(ref _resources);
foreach (var col in this.OfType<ICVOrderBookColumn>())
(col.filter as IDisposable)?.Dispose();
Clear();
@@ -599,18 +567,16 @@ namespace mbts.spark {
public class OrderBookOrderTypeColumn : OrderTypeColumn<Columns>, ICVOrderBookColumn {
ListSortDirection? _cached_sort_direction;
public OrderBookOrderTypeColumn(Columns key, string badge_fill_binding_path, string display_name_binding_path, IComparer<OrderBookRowVM> row_comparer, IDataGridColumnPersistentFilter<OrderSecurityAlgoMeta, AlgoID[]> filter, string header = DefaultColumnHeaders.OrderType)
: base(key, new Binding(badge_fill_binding_path), new Binding(display_name_binding_path), filter, header) {
public OrderBookOrderTypeColumn(IDataGridColumnPersistentFilter<OrderSecurityAlgoMeta, OrderType[]> filter)
: base(Columns.OrderType, new Binding(nameof(OrderBookRowVM.badge_fill)), new Binding(nameof(OrderBookRowVM.display_name)), filter) {
id = key.ToString();
this.filter = filter;
font_weight_binding = RenderUtils.get_font_weight_binding();
_cached_sort_direction = SortDirection;
this.comparer = row_comparer;
}
public new IDataGridColumnPersistentFilter<OrderSecurityAlgoMeta, AlgoID[]> filter { get; }
public override string filter_template => DataGridFilterKnownTemplates.AlgoType;
public IComparer<OrderBookRowVM> comparer { get; }
public new IDataGridColumnPersistentFilter<OrderSecurityAlgoMeta, OrderType[]> filter { get; }
public IComparer<OrderBookRowVM> comparer => _wrap_comparer(r => r.order_type);
IDataGridColumnFilter<OrderSecurityAlgoMeta> ICVOrderBookColumn.filter => filter;
ListSortDirection? ICVOrderBookColumn.SortDirection { get => _cached_sort_direction; set => SortDirection = value; }
@@ -776,7 +742,7 @@ namespace mbts.spark {
// create the attach button and assign the menu to it
var attach_button = new Button() {
Name = "attach_button",
Content = new Image() { Source = Icons.AttachAlgos },
Content = "A",
HorizontalAlignment = HorizontalAlignment.Stretch,
VerticalAlignment = VerticalAlignment.Stretch,
Focusable = false,
@@ -898,7 +864,7 @@ namespace mbts.spark {
var detach_button = new Button() {
Name = "detach_button",
Content = new Image() { Source = Icons.DetachAlgos },
Content = "D",
HorizontalAlignment = HorizontalAlignment.Stretch,
VerticalAlignment = VerticalAlignment.Stretch,
Focusable = false,
@@ -18,16 +18,18 @@ namespace mbts.spark {
const string _unknown_security_price_format_string = "0.#########";
const int _unknown_security_price_num_fractional_digits = 9;
readonly OrderBookVM _owner;
Color? _root_algo_badge_color_backing;
Brush _badge_fill, _root_algo_badge_fill;
Brush _badge_fill;
IRaiseCanExecuteChangedCommand _show_order_modify_cmd, _toggle_expanded_cmd, _cancel_cmd, _detach_command, _attach_command, _update_command, _modify_order_quantity_andor_price, _revert_prospective_order_quantity_andor_price;
bool _is_parent, _is_expanded, _is_selected, _is_attachable, _is_detachable;
int _depth_level;
SecurityImmutable? _security => order_tuple.security;
// for mini-ob
uint _prospective_quantity;
double _prospective_price;
public OrderBookRowVM(OrderBookVM owner, OrderSecurityAlgoMeta order_tuple, bool is_expanded) {
_owner = owner;
this.order_tuple = order_tuple;
@@ -35,6 +37,11 @@ namespace mbts.spark {
_is_expanded = is_expanded;
prospective_quantity = this.quantity;
prospective_price = this.price;
this.invalidated += OrderBookRowVM_invalidated;
}
private void OrderBookRowVM_invalidated() {
modify_order_quantity_andor_price?.TryRaiseCanExecuteChanged();
}
//// This takes care of the case where the OB has all rows visible
@@ -45,8 +52,8 @@ namespace mbts.spark {
//// handler
public IObservable<OrderSecurityAlgoMeta> subscribe_data() {
return Observable.FromEvent<Action, OrderSecurityAlgoMeta>(
cb => () => cb(order_tuple),
cb => invalidated += cb,
cb => () => cb(order_tuple),
cb => invalidated += cb,
cb => invalidated -= cb);
}
@@ -94,14 +101,8 @@ namespace mbts.spark {
public bool is_non_terminal => order.is_non_terminal();
public bool is_attachable { get => _is_attachable; set => SetVisual(ref _is_attachable, value); }
public bool is_detachable { get => _is_detachable; set => SetVisual(ref _is_detachable, value); }
public string filled_status_desc => order.filled_status_description(security.spec_or_default());
// Root Algo
public CustomOrderDefinition.CustomOneofCase root_algo_order_type => order_tuple.root_algo.value.CustomCase;
public OrderMetadata root_algo_order_metadata => _owner.get_metadata(root_algo_order_type);
public Brush root_algo_badge_fill => _root_algo_badge_fill ?? (_root_algo_badge_fill = new SolidColorBrush(_root_algo_badge_color));
public string root_algo_display_name => order_tuple.root_algo.name;
// Tree
public bool is_parent { get => _is_parent; set => Set(ref _is_parent, value); }
public bool is_child => order.has_parent();
@@ -147,38 +148,32 @@ namespace mbts.spark {
public ICommand cancel_command => _cancel_cmd ??
(_cancel_cmd = new DelegateCommand(() => _owner.cancel_order(this), () => status == OrderStatus.Working || status == OrderStatus.Disconnected));
public ICommand modify_order_quantity_andor_price {
get {
if (_modify_order_quantity_andor_price == null) {
_modify_order_quantity_andor_price = new DelegateCommand(execute, can_execute);
invalidated += _modify_order_quantity_andor_price.RaiseCanExecuteChanged;
// impl
void execute() {
if (is_qty_dirty && is_price_dirty) {
_owner.modify_order_price_and_quantity(this, prospective_price, prospective_quantity);
} else if (is_qty_dirty) {
_owner.modify_order_quantity(this, prospective_quantity);
} else if (is_price_dirty) {
_owner.modify_order_price(this, this.prospective_price);
}
_unselect_me();
}
bool can_execute() => status == OrderStatus.Working && (is_price_dirty || is_qty_dirty);
}
return _modify_order_quantity_andor_price;
}
}
public ICommand revert_prospective_order_quantity_andor_price => _revert_prospective_order_quantity_andor_price ??
(_revert_prospective_order_quantity_andor_price = new DelegateCommand(
public ICommand modify_order_quantity_andor_price => _modify_order_quantity_andor_price ??
(_modify_order_quantity_andor_price = new DelegateCommand(
() => {
prospective_price = price;
prospective_quantity = quantity;
},
if (is_qty_dirty && is_price_dirty) {
_owner.modify_order_price_and_quantity(this, prospective_price, prospective_quantity);
} else if (is_qty_dirty) {
_owner.modify_order_quantity(this, prospective_quantity);
} else if (is_price_dirty) {
_owner.modify_order_price(this, this.prospective_price);
}
_unselect_me();
},
() => this.status == OrderStatus.Working && (is_price_dirty || is_qty_dirty)
)
);
public ICommand revert_prospective_order_quantity_andor_price => _revert_prospective_order_quantity_andor_price ??
(_revert_prospective_order_quantity_andor_price = new DelegateCommand(
() => {
prospective_price = price;
prospective_quantity = quantity;
},
() => this.status == OrderStatus.Working && (is_price_dirty || is_qty_dirty)
)
);
public ICommand detach_command => _detach_command ??
(_detach_command = new DelegateCommand(() => {
_owner.detach_orders(this);
@@ -198,18 +193,6 @@ namespace mbts.spark {
_select_me();
})
);
// private props
Color _root_algo_badge_color {
get => _root_algo_badge_color_backing ?? (_root_algo_badge_color_backing = order_tuple.root_badge_color(root_algo_order_metadata)).Value;
set {
if (_root_algo_badge_color_backing != value) {
_root_algo_badge_color_backing = value;
_root_algo_badge_fill = null;
}
}
}
#region IHierarchicalRow
bool IHierarchicalRow.is_parent => is_parent;
bool IHierarchicalRow.is_expanded => is_expanded;
@@ -279,15 +262,6 @@ namespace mbts.spark {
// display name
if (old_order_tuple.display_name() != order_tuple.display_name())
RaisePropertyChanged(nameof(display_name));
// root badge fill
if (_root_algo_badge_color_backing.HasValue) {
// only need to invalidate it if it had a value (it is lazily instantiated)
_root_algo_badge_color = order_tuple.root_badge_color(root_algo_order_metadata);
RaisePropertyChanged(nameof(root_algo_badge_fill));
}
// root display name
if (old_order_tuple.root_algo.name != order_tuple.root_algo.name)
RaisePropertyChanged(nameof(root_algo_display_name));
// status
if ((Columns.Status & dirty) != 0)
RaisePropertyChanged(nameof(status));
@@ -314,6 +288,7 @@ namespace mbts.spark {
// this will update the cancel column in the mini ob
cancel_command.TryRaiseCanExecuteChanged();
}
// always refresh attach and detach b/c
// conditionally raise invalidated
if ((dirty & ViewRefresh.invalidate_mask) != 0)
@@ -160,7 +160,7 @@ namespace mbts.spark {
security_plurality = p;
RaisePropertyChanged(nameof(security_plurality));
}),
model.on_order_tuples_with_root.OnDispatcher().Subscribe(t => {
model.on_order_tuples.OnDispatcher().Subscribe(t => {
_cached_orders = t.state;
_row_collection.update(t.added, t.changed, t.removed.Select(o => o.order.Key));
}),
@@ -249,22 +249,12 @@ namespace mbts.spark {
var mod_algo_vm = attach_vm.algo_vm.algo_root;
await Task.WhenAll(order_tups.Select(t => {
var algo = t.order.Def.CustomDef.CloneToMutable();
if (algo.CustomCase == CustomOrderDefinition.CustomOneofCase.Composite) {
algo = algo.Composite.Definition;
}
mod_algo_vm.assign_to(algo);
if (algo_template_key != 0) {
algo = new CustomOrderDefinition {
Composite = new CompositeOrderDefinition {
AlgoTemplateKey = algo_template_key,
Definition = algo
}
};
}
return _model.send_order(
t.order.Def.with(
attach_target_order_key: t.order.Key,
custom_def: algo
custom_def: algo,
algo_template_key: algo_template_key
),
double.IsNaN(price) ? t.order.price() : price,
size ?? t.order.quantity());
@@ -542,23 +532,9 @@ namespace mbts.spark {
public bool try_get_parent(OrderBookRowVM row, out OrderSecurityAlgoMeta parent) =>
_cached_orders.TryGetValue(row.parent_order_key, out parent);
public OrderRecordImmutable get_root(OrderRecordImmutable r) {
while (r.ParentKey != 0 && _cached_orders.TryGetValue(r.ParentKey, out var parent_osam)) {
r = parent_osam.order;
}
return r;
}
internal void detach_orders(OrderBookRowVM order) =>
_detach_orders_async(new[] { order }).ignore();
public OrderSecurityAlgoMeta get_ordersecurityalgometa(OrderRecordImmutable order) {
_cached_orders.TryGetValue(order.Key, out var osam);
return osam;
}
public OrderMetadata get_metadata(CustomOrderDefinition.CustomOneofCase order_type) => _model.factory.get_metadata(order_type);
public OrderMetadata get_metadata(OrderBookRowVM row) => _model.factory.get_metadata(row.order_type);
internal OrderBookRowVM get_parent(OrderBookRowVM row) => _row_collection.get_parent(row.order_key);
@@ -622,11 +598,7 @@ namespace mbts.spark {
await Task.WhenAll(update_params.Select(t => _model.update_order(t.order, new_price: price, new_size: size, new_algo: t.new_algo)));
(OrderRecordImmutable order, CustomOrderDefinitionImmutable? new_algo) update_params_factory(OrderBookRowVM row) {
var mod_algo = row.order.Def.CustomDef.CloneToMutable();
if (mod_algo.CustomCase == CustomOrderDefinition.CustomOneofCase.Composite) {
mod_algo_vm.assign_to(mod_algo.Composite.Definition);
} else {
mod_algo_vm.assign_to(mod_algo);
}
mod_algo_vm.assign_to(mod_algo);
var mod_algoi = new CustomOrderDefinitionImmutable(mod_algo);
return (row.order, OrderDataHelper.EqualsHelpers.equals(row.order.Def.CustomDef, mod_algoi) ? (CustomOrderDefinitionImmutable?)null : mod_algoi);
}
@@ -868,9 +840,10 @@ namespace mbts.spark {
revert();
}
public void revert() =>
param_rows.revert_all();
public void revert() {
foreach (var r in param_rows)
r.param.revert();
}
public IObservable<bool> subscribe_is_dirty() => _is_dirty.observe_current(true);
void _reset_ladder_vm() {
@@ -1131,4 +1104,4 @@ namespace mbts.spark {
!_algo_type_conf.TryGetValue(algo_type, out var result) || result.show_size;
}
}
}
}
@@ -27,12 +27,8 @@ namespace bts.shell.orderbook {
public Venue[] exchanges;
[ProtoMember(7)]
public TimeInForce[] tifs;
//[ProtoMember(8)]
//public CustomOrderDefinition.CustomOneofCase[] order_types;
[ProtoMember(23)]
public AlgoID[] order_types;
[ProtoMember(24)]
public AlgoID[] root_algo_types;
[ProtoMember(8)]
public CustomOrderDefinition.CustomOneofCase[] order_types;
[ProtoMember(9)]
public Side[] sides;
[ProtoMember(10)]
@@ -74,7 +70,6 @@ namespace bts.shell.orderbook {
EqualityComparer.safe_sequence_equals(exchanges, other.exchanges) &&
EqualityComparer.safe_sequence_equals(tifs, other.tifs) &&
EqualityComparer.safe_sequence_equals(order_types, other.order_types) &&
EqualityComparer.safe_sequence_equals(root_algo_types, other.root_algo_types) &&
EqualityComparer.safe_sequence_equals(sides, other.sides) &&
qty.safe_equals(other.qty) &&
price.safe_equals(other.price) &&
@@ -101,7 +96,6 @@ namespace bts.shell.orderbook {
EqualityComparer.safe_aggregate_hash(exchanges),
EqualityComparer.safe_aggregate_hash(tifs),
EqualityComparer.safe_aggregate_hash(order_types),
EqualityComparer.safe_aggregate_hash(root_algo_types),
EqualityComparer.safe_aggregate_hash(sides),
qty?.GetHashCode() ?? 0,
price?.GetHashCode() ?? 0,
@@ -134,8 +128,7 @@ namespace bts.shell.orderbook {
add_discrete_values(fs.accounts, o => o.order.account());
add_discrete_values(fs.exchanges, o => o.security?.Exchange ?? Venue.Unset);
add_discrete_values(fs.tifs, o => o.order.time_in_force());
add_discrete_values(fs.order_types, o => AlgoID.from_order_def(o.order.Def));
add_discrete_values(fs.root_algo_types, o => AlgoID.from_algo_key(o.root_algo.key));
add_discrete_values(fs.order_types, o => o.order.order_type());
add_discrete_values(fs.order_sub_types, o => o.order.sub_type());
add_discrete_values(fs.sides, o => o.order.side());
add_discrete_values(fs.statuses, o => o.order.status());
@@ -198,4 +191,4 @@ namespace bts.shell.orderbook {
}
}
}
}
}
@@ -65,10 +65,6 @@ namespace bts.shell.orderbook {
[ProtoMember(25)]
public bool use_defaults;
/// <summary>
/// Please use <see cref="Default"/> to get a new instance (the only reason the default constructor still exists is for ProtoBuf deserialization).
/// </summary>
[Obsolete]
public OrderBookStartupData() {
show_right_panel = _default_show_right_panel;
show_order_params = _default_show_order_params;
@@ -134,34 +130,31 @@ namespace bts.shell.orderbook {
}
}
static GridSettings _default_general_grid => GridSettings.Default.with(DefaultColumns.all, DefaultColumns.sorting_criterion);
public static OrderBookGridSettings default_mini_grid => new OrderBookGridSettings(GridSettings.Default.with(DefaultColumns.mini, DefaultColumns.sorting_criterion)) {
algo_tree_display_mode = AlgoTreeDisplayMode.RootAndLeafNodes
};
public static OrderBookGridSettings default_mini_grid => new OrderBookGridSettings(GridSettings.Default.with(DefaultColumns.mini, DefaultColumns.sorting_criterion));
static class DefaultColumns {
public static GridColumnSettings security => new GridColumnSettings(Columns.Security.ToString(), DIYGrid.DefaultColumnHeaders.Security, width: DIYGrid.DefaultColumnWidths.Security);
public static GridColumnSettings symbol => new GridColumnSettings(Columns.Symbol.ToString(), DIYGrid.DefaultColumnHeaders.Symbol, width: DIYGrid.DefaultColumnWidths.Symbol, horizontal_alignment: HorizontalAlignment.Left);
public static GridColumnSettings time_created => new GridColumnSettings(Columns.Time.ToString(), "Time", width: DIYGrid.DefaultColumnWidths.Time, horizontal_alignment: HorizontalAlignment.Left);
public static GridColumnSettings last_change => new GridColumnSettings(Columns.LastChange.ToString(), "Last Change", width: DIYGrid.DefaultColumnWidths.Time, horizontal_alignment: HorizontalAlignment.Left);
public static GridColumnSettings user => new GridColumnSettings(Columns.User.ToString(), DIYGrid.DefaultColumnHeaders.User, width: DIYGrid.DefaultColumnWidths.User, horizontal_alignment: HorizontalAlignment.Left);
public static GridColumnSettings account => new GridColumnSettings(Columns.Account.ToString(), DIYGrid.DefaultColumnHeaders.Account, width: DIYGrid.DefaultColumnWidths.Account, horizontal_alignment: HorizontalAlignment.Left);
public static GridColumnSettings exchange => new GridColumnSettings(Columns.Exchange.ToString(), DIYGrid.DefaultColumnHeaders.Exchange, width: DIYGrid.DefaultColumnWidths.Exchange, horizontal_alignment: HorizontalAlignment.Left);
public static GridColumnSettings symbol => new GridColumnSettings(Columns.Symbol.ToString(), DIYGrid.DefaultColumnHeaders.Symbol, width: DIYGrid.DefaultColumnWidths.Symbol, horizontal_alignment: HorizontalAlignment.Right);
public static GridColumnSettings time_created => new GridColumnSettings(Columns.Time.ToString(), "Time", width: DIYGrid.DefaultColumnWidths.Time, horizontal_alignment: HorizontalAlignment.Right);
public static GridColumnSettings last_change => new GridColumnSettings(Columns.LastChange.ToString(), "Last Change", width: DIYGrid.DefaultColumnWidths.Time, horizontal_alignment: HorizontalAlignment.Right);
public static GridColumnSettings user => new GridColumnSettings(Columns.User.ToString(), DIYGrid.DefaultColumnHeaders.User, width: DIYGrid.DefaultColumnWidths.User, horizontal_alignment: HorizontalAlignment.Right);
public static GridColumnSettings account => new GridColumnSettings(Columns.Account.ToString(), DIYGrid.DefaultColumnHeaders.Account, width: DIYGrid.DefaultColumnWidths.Account, horizontal_alignment: HorizontalAlignment.Right);
public static GridColumnSettings exchange => new GridColumnSettings(Columns.Exchange.ToString(), DIYGrid.DefaultColumnHeaders.Exchange, width: DIYGrid.DefaultColumnWidths.Exchange, horizontal_alignment: HorizontalAlignment.Right);
public static GridColumnSettings time_in_force => new GridColumnSettings(Columns.TimeInForce.ToString(), DIYGrid.DefaultColumnHeaders.TimeInForce, width: DIYGrid.DefaultColumnWidths.TimeInForce);
public static GridColumnSettings order_type => new GridColumnSettings(Columns.OrderType.ToString(), DIYGrid.DefaultColumnHeaders.OrderType, width: DIYGrid.DefaultColumnWidths.OrderType);
public static GridColumnSettings root_algo_type => new GridColumnSettings(Columns.RootAlgoType.ToString(), DIYGrid.DefaultColumnHeaders.RootAlgoType, width: DIYGrid.DefaultColumnWidths.OrderType);
public static GridColumnSettings sub_type => new GridColumnSettings(Columns.SubType.ToString(), "Sub Type", width: 80, horizontal_alignment: HorizontalAlignment.Left);
public static GridColumnSettings side => new GridColumnSettings(Columns.Side.ToString(), "B/S", width: DIYGrid.DefaultColumnWidths.Side, horizontal_alignment: HorizontalAlignment.Left);
public static GridColumnSettings sub_type => new GridColumnSettings(Columns.SubType.ToString(), "Sub Type", width: 80, horizontal_alignment: HorizontalAlignment.Right);
public static GridColumnSettings side => new GridColumnSettings(Columns.Side.ToString(), "B/S", width: DIYGrid.DefaultColumnWidths.Side, horizontal_alignment: HorizontalAlignment.Right);
public static GridColumnSettings quantity => new GridColumnSettings(Columns.Size.ToString(), "Qty", width: DIYGrid.DefaultColumnWidths.Size, horizontal_alignment: HorizontalAlignment.Right);
public static GridColumnSettings price => new GridColumnSettings(Columns.Price.ToString(), DIYGrid.DefaultColumnHeaders.Price, width: DIYGrid.DefaultColumnWidths.Price, horizontal_alignment: HorizontalAlignment.Right);
public static GridColumnSettings filled_quantity => new GridColumnSettings(Columns.Filled.ToString(), "Filled Qty", width: DIYGrid.DefaultColumnWidths.Filled, horizontal_alignment: HorizontalAlignment.Right);
public static GridColumnSettings avg_price => new GridColumnSettings(Columns.AvgFilled.ToString(), "Avg Filled", width: DIYGrid.DefaultColumnWidths.AveragePrice, horizontal_alignment: HorizontalAlignment.Right);
public static GridColumnSettings last_price => new GridColumnSettings(Columns.LastPrice.ToString(), "Last Filled", width: DIYGrid.DefaultColumnWidths.LastPrice, horizontal_alignment: HorizontalAlignment.Right);
public static GridColumnSettings status => new GridColumnSettings(Columns.Status.ToString(), "Status", width: 80, horizontal_alignment: HorizontalAlignment.Left);
public static GridColumnSettings last_message => new GridColumnSettings(Columns.LastMessage.ToString(), "Last Message", width: DIYGrid.DefaultColumnWidths.LastMessage, horizontal_alignment: HorizontalAlignment.Left);
public static GridColumnSettings security_key => new GridColumnSettings(Columns.SecurityKey.ToString(), DIYGrid.DefaultColumnHeaders.SecurityKey, is_visible: false, width: DIYGrid.DefaultColumnWidths.SecurityKey, horizontal_alignment: HorizontalAlignment.Left);
public static GridColumnSettings order_key => new GridColumnSettings(Columns.OrderKey.ToString(), DIYGrid.DefaultColumnHeaders.OrderKey, width: DIYGrid.DefaultColumnWidths.OrderKey, horizontal_alignment: HorizontalAlignment.Left);
public static GridColumnSettings parent_key => new GridColumnSettings(Columns.ParentKey.ToString(), "Parent Key", width: DIYGrid.DefaultColumnWidths.ParentKey, horizontal_alignment: HorizontalAlignment.Left);
public static GridColumnSettings attached_target_order_key => new GridColumnSettings(Columns.AttachedTargetOrderKey.ToString(), DIYGrid.DefaultColumnHeaders.AttachedTargetOrderKey, width: DIYGrid.DefaultColumnWidths.ParentKey, horizontal_alignment: HorizontalAlignment.Left);
public static GridColumnSettings status => new GridColumnSettings(Columns.Status.ToString(), "Status", width: 80, horizontal_alignment: HorizontalAlignment.Right);
public static GridColumnSettings last_message => new GridColumnSettings(Columns.LastMessage.ToString(), "Last Message", width: DIYGrid.DefaultColumnWidths.LastMessage, horizontal_alignment: HorizontalAlignment.Right);
public static GridColumnSettings security_key => new GridColumnSettings(Columns.SecurityKey.ToString(), DIYGrid.DefaultColumnHeaders.SecurityKey, is_visible: false, width: DIYGrid.DefaultColumnWidths.SecurityKey, horizontal_alignment: HorizontalAlignment.Right);
public static GridColumnSettings order_key => new GridColumnSettings(Columns.OrderKey.ToString(), DIYGrid.DefaultColumnHeaders.OrderKey, width: DIYGrid.DefaultColumnWidths.OrderKey, horizontal_alignment: HorizontalAlignment.Right);
public static GridColumnSettings parent_key => new GridColumnSettings(Columns.ParentKey.ToString(), "Parent Key", width: DIYGrid.DefaultColumnWidths.ParentKey, horizontal_alignment: HorizontalAlignment.Right);
public static GridColumnSettings attached_target_order_key => new GridColumnSettings(Columns.AttachedTargetOrderKey.ToString(), DIYGrid.DefaultColumnHeaders.AttachedTargetOrderKey, width: DIYGrid.DefaultColumnWidths.ParentKey, horizontal_alignment: HorizontalAlignment.Right);
public static IEnumerable<SortingCriteria> sorting_criterion {
get {
@@ -180,7 +173,6 @@ namespace bts.shell.orderbook {
yield return exchange;
yield return time_in_force;
yield return order_type;
yield return root_algo_type;
yield return sub_type;
yield return side;
yield return quantity;
@@ -41,8 +41,7 @@ namespace mbts.spark {
Attach = 1 << 25,
Detach = 1 << 26,
Update = 1 << 27,
Commit = 1 << 28,
RootAlgoType = 1 << 29
Commit = 1 << 28
}
public OrderBookGridView() =>
@@ -174,12 +174,9 @@
SelectionHighlight="{Binding grid_settings_manager.core_manager.selection_highlight, Mode=OneWay}"
>
<FrameworkElement.Margin>
<Binding Path="show_right_panel">
<Binding Source="{StaticResource GridSplitterWidth}">
<Binding.Converter>
<cv:ValueConverterPipe>
<cv:BooleanToObjectConverter ValueForFalse="{u:Double 0}" ValueForTrue="{StaticResource GridSplitterWidth}"/>
<cv:DoubleToThicknessConverter RightMultiplier="-1"/>
</cv:ValueConverterPipe>
<cv:DoubleToThicknessConverter RightMultiplier="-1"/>
</Binding.Converter>
</Binding>
</FrameworkElement.Margin>
@@ -579,7 +576,7 @@
</c:DIYGrid.RowTemplate>
</c:DIYGrid>
</Grid>
<StatusBar Grid.Row="1" DockPanel.Dock="Bottom" Grid.ColumnSpan="2">
<StatusBar Grid.Row="1" DockPanel.Dock="Bottom">
<StatusBarItem HorizontalAlignment="Right">
<TextBlock>
<Run Text="Orders:"/>
@@ -53,19 +53,12 @@ namespace mbts.spark {
d |= VisualStateNames.SlaveData.Data.Ladder;
return VisualStateNames.SlaveData.fmt_name(d);
});
static readonly IMultiValueConverter
_right_panel_expander_margin_converter = ValueConverter.create<bool, Visibility, Thickness>(
(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;
@@ -145,19 +138,6 @@ namespace mbts.spark {
}
}
}
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 {
+1 -1
View File
@@ -857,7 +857,7 @@ namespace mbts.spark.utilities {
int phase_mult = 1;
switch (def.CustomCase) {
case CustomOrderDefinition.CustomOneofCase.Cover:
add_component(def.Cover.HedgeTicks.GetHashCode());
add_component(def.Cover.HedgeTicks);
add_component(_get_hash(_get_cover_child(def.Cover)));
add_component(_get_hash(_get_cover_hedge(def.Cover)));
break;
@@ -153,21 +153,9 @@ namespace mbts.spark {
d => d.load_committed(),
d => d == null ? Observable.Return(false) : d.subscribe_is_definition_dirty(),
out IObserver<AlgoDefinitionVM> revert_definition_observer);
// algo params dialog skirt
set_default_algo_params_cmd = ObservantCommand.create(() => {
algo_param_rows.commit_all();
_close_algo_popup();
}, out IObserver<bool> set_default_algo_params_observer);
revert_algo_params_cmd = ObservantCommand.create(() => {
algo_param_rows.revert_all();
_close_algo_popup();
}, out IObserver<bool> revert_algo_params_observer);
var algo_params_dirty_mon = new ReactiveThresholdMonitor<AlgoParamRowVM>(r => r.param.subscribe_is_dirty());
var nullable_security_md_source = security_md_source.Select(smd => new SecurityMD?(smd)).RefCountReplay(1);
//
_dispose = new CompositeDisposable(
algo_params_dirty_mon.Subscribe(set_default_algo_params_observer, revert_algo_params_observer),
ObservableAutoWrapper.connect_item_hooks(_algo_param_rows, algo_params_dirty_mon.join),
_selected_algo_definition.subscribe_changed(_selected_algo_definition_Changed),
as_demuxer().subscribe<AlgoDefinitionTemplateVM>(nameof(selected_algo_template)).Subscribe(
undo_observer,
@@ -370,8 +358,6 @@ namespace mbts.spark {
public ICommand save_definition_cmd { get; }
public ICommand save_template_cmd { get; }
public ICommand revert_definition_cmd { get; }
public ICommand set_default_algo_params_cmd { get; }
public ICommand revert_algo_params_cmd { get; }
public ICommand undo_cmd { get; }
public ICommand redo_cmd { get; }
public ICommand undo_definition_cmd { get; }
@@ -400,22 +386,9 @@ namespace mbts.spark {
if (_model.algo_model.templates_enabled()) {
selected_algo_template.algo_root.assign_to(order.CustomDef);
} else {
var algo = new CustomOrderDefinition();
selected_algo_definition.algo_root.assign_to(algo);
switch (selected_algo_definition.key.mode) {
case AlgoKey.Mode.Persisted:
order.CustomDef = new CustomOrderDefinition {
Composite = new CompositeOrderDefinition {
AlgoTemplateKey = selected_algo_definition.key.persisted.id_uint,
Definition = algo
}
};
selected_algo_definition.algo_root.assign_to(order.CustomDef.Composite.Definition);
break;
default:
order.CustomDef = algo;
break;
}
selected_algo_definition.algo_root.assign_to(order.CustomDef);
if (selected_algo_definition.key.mode == AlgoKey.Mode.Persisted)
order.AlgoTemplateKey = selected_algo_definition.key.persisted.id_uint;
}
return order;
}
@@ -438,11 +411,6 @@ namespace mbts.spark {
static IDisposable _connect_algo_param_rows(AlgoDefinitionVM def, ObservableAggregateCollection<AlgoParamRowVM> rows) =>
AlgoParamRowsHelper.connect(def, rows, false);
void _close_algo_popup() {
if (selected_algo_definition?.algo_root is IAlgoVM a)
a.is_expanded = false;
}
int? _get_favorite_algo_index(AlgoKey key) =>
key.mode == AlgoKey.Mode.Persisted && _favorite_algos_index.TryGetValue(key, out int i) ? i : (int?)null;
+4 -23
View File
@@ -58,39 +58,21 @@ namespace bts.api.orderman {
struct OrderSecurityAlgoMeta : IEquatable<OrderSecurityAlgoMeta> {
public readonly OrderRecordImmutable order;
public readonly SecurityImmutable? security;
/// TODO: refactor <see cref="algo"/> to 'studio_algo' or something that indicates it does not bear the same relation to this order, that <see cref="root_algo"/> does to the root order.
/// The former is meant to hold studio algo information, and nothing else. Naturally, it indicates whether or not this is a studio order by being non-null (<see cref="is_studio_algo"/>).
/// The latter, however, can be any kind of algo (studio, exchange, etc.); it holds information about the root-most algo in this order's branch.
public readonly AlgoData? algo;
public readonly AlgoDefinitionMetadata? meta;
public readonly AlgoData root_algo;
public readonly AlgoDefinitionMetadata? root_meta;
public OrderSecurityAlgoMeta(OrderRecordImmutable order, SecurityImmutable? security, AlgoData? algo, AlgoDefinitionMetadata? meta, AlgoData? root_algo = null, AlgoDefinitionMetadata? root_meta = null) {
public OrderSecurityAlgoMeta(OrderRecordImmutable order, SecurityImmutable? security, AlgoData? algo, AlgoDefinitionMetadata? meta) {
this.order = order;
this.security = security;
this.algo = algo;
this.meta = meta;
if (root_algo.HasValue) {
this.root_algo = root_algo.Value;
this.root_meta = root_meta;
} else {
this.root_algo = algo ?? new AlgoData(order.Def.CustomDef);
this.root_meta = meta;
}
}
public bool is_studio_algo => algo.HasValue;
public OrderSecurityAlgoMeta with(AlgoData? root_algo, AlgoDefinitionMetadata? root_meta = null) =>
new OrderSecurityAlgoMeta(order, security, algo, meta, root_algo, root_meta);
public bool Equals(OrderSecurityAlgoMeta other) =>
order == other.order &&
security == other.security &&
algo == other.algo &&
meta == other.meta &&
root_algo == other.root_algo;
meta == other.meta;
public override bool Equals(object obj) => EqualityComparer.equals_obj(this, obj);
@@ -99,10 +81,9 @@ namespace bts.api.orderman {
order.GetHashCode(),
security?.GetHashCode() ?? 0,
algo?.GetHashCode() ?? 0,
meta?.GetHashCode() ?? 0,
root_algo.GetHashCode());
meta?.GetHashCode() ?? 0);
public static bool operator ==(OrderSecurityAlgoMeta a, OrderSecurityAlgoMeta b) => a.Equals(b);
public static bool operator !=(OrderSecurityAlgoMeta a, OrderSecurityAlgoMeta b) => !a.Equals(b);
}
}
}
@@ -3,13 +3,13 @@
namespace mbts.spark {
static partial class OrderTypeVMFactory {
class CoverOrderVM : OrderTypeVMBase<CoverOrderDefinition, CoverOrderDefinitionImmutable> {
readonly Property<uint?> _hedge_ticks;
readonly Property<int?> _hedge_ticks;
public CoverOrderVM(AlgoKey key, string display_name, AlgoEditingPermissions editing_permissions)
: base(key, display_name, editing_permissions) =>
_hedge_ticks = add_nullable_property(nameof(hedge_ticks), CoverOrderDefinition.HedgeTicksFieldNumber, 1u, true);
_hedge_ticks = add_nullable_property(nameof(hedge_ticks), CoverOrderDefinition.HedgeTicksFieldNumber, 1, true);
public uint? hedge_ticks { get => _hedge_ticks.Value; set => _hedge_ticks.set(value); }
public int? hedge_ticks { get => _hedge_ticks.Value; set => _hedge_ticks.set(value); }
protected override void validate() =>
assert(hedge_ticks.HasValue, nameof(hedge_ticks), "Invalid hedge ticks.");
@@ -58,9 +58,6 @@ namespace mbts.spark {
public static IAlgoVM dynamic(AlgoKey key, string display_name, string dynamic_type, AlgoEditingPermissions editing_permissions) => new DynamicOrderVM(key, dynamic_type, display_name, editing_permissions);
public static IAlgoVM create(AlgoData def_data, AlgoEditingPermissions editing_permissions = default_editing_permissions, bool is_expanded = false) {
if (def_data.value.CustomCase == AlgoType.Composite) {
def_data = new AlgoData(def_data.value.Composite.Definition, def_data.name, def_data.key);
}
var vm = create(def_data.key, def_data.name, def_data.value.CustomCase, editing_permissions, is_expanded);
vm.load_from(def_data.value);
return vm;
@@ -238,11 +235,8 @@ namespace mbts.spark {
!string.IsNullOrEmpty(display_name) && key.Key == (Key.A + display_name[0] - 'A');
public void load_from(AlgoDefi value) {
if (value.CustomCase != order_type) {
value = value.actual();
if (value.CustomCase != order_type)
return;
}
if (value.CustomCase != order_type)
return;
using (_def_change_notifier.defer_execution()) {
var algom = _descriptor.Accessor.GetValue(value.CloneToMutable()) as TMutable ?? new TMutable();
var security_src = Observable.Create<SecurityImmutable?>(o => {
@@ -274,11 +268,8 @@ namespace mbts.spark {
}
public virtual async Task<AlgoDefi?> load_from_async(AlgoDefi defi) {
if (defi.CustomCase != order_type) {
defi = defi.actual();
if (defi.CustomCase != order_type)
return null;
}
if (defi.CustomCase != order_type)
return null;
using (_def_change_notifier.defer_execution()) {
// TODO: each level of the order hierarchy could load in parallel
await on_load_from_async(defi);
@@ -1057,4 +1048,4 @@ namespace mbts.spark {
}
#endregion
}
}
}
@@ -5,13 +5,16 @@ using TopDefi = bts.api.orderman.TopOrderDefinitionImmutable;
namespace mbts.spark {
static partial class OrderTypeVMFactory {
class TopOrderVM : OrderTypeVMBase<TopDef, TopDefi> {
readonly Property<uint?> _watch_level_tick_offset;
readonly Property<QuantityMeasureImmutable?> _top_threshold;
public TopOrderVM(AlgoKey key, string display_name, AlgoEditingPermissions editing_permissions)
: base(key, display_name, editing_permissions) {
_watch_level_tick_offset = add_nullable_property(nameof(watch_level_tick_offset), TopDef.WatchLevelTickOffsetFieldNumber, 0u);
_top_threshold = add_property<QuantityMeasure, QuantityMeasureImmutable>(nameof(top_threshold), TopDef.TopThresholdFieldNumber, new QuantityMeasureImmutable(new QuantityMeasure { Ratio = 1.0, Absolute = 1 }));
}
public uint? watch_level_tick_offset { get => _watch_level_tick_offset.Value; set => _watch_level_tick_offset.set(value); }
public QuantityMeasureImmutable? top_threshold { get => _top_threshold.Value; set => _top_threshold.set(value); }
}
}
+7 -26
View File
@@ -82,21 +82,6 @@ namespace mbts.spark {
public static string dynamic_order_type_display_name(this OrderRecordImmutable order) =>
order.HasDef && order.Def.HasCustomDef && order.Def.CustomDef.HasDynamic ? order.Def.CustomDef.Dynamic.DynamicOrderType : string.Empty;
public static uint algo_template_key(this OrderRecordImmutable order) =>
order.HasDef && order.Def.HasCustomDef && order.Def.CustomDef.CustomCase == CustomOrderDefinition.CustomOneofCase.Composite ?
order.Def.CustomDef.Composite.AlgoTemplateKey : 0u;
/// <summary>
/// If the definitions is a <see cref="CompositeOrderDefinition"/>, returns the underlying algo, otherwise returns <paramref name="custom_def"/> iteself.
/// </summary>
/// <param name="custom_def">The definition to for which the underlying algo will be returned.</param>
/// <returns>The first non-composite algo definition in the specified <see cref="CustomOrderDefinition"/>.</returns>
public static CustomOrderDefinitionImmutable actual(this CustomOrderDefinitionImmutable custom_def) {
while (custom_def.CustomCase == CustomOrderDefinition.CustomOneofCase.Composite)
custom_def = custom_def.Composite.Definition;
return custom_def;
}
public static OrderSubType sub_type(this OrderRecordImmutable order) =>
order.HasDef ? order.Def.SubType : OrderSubType.None;
@@ -140,7 +125,7 @@ namespace mbts.spark {
display_name(order_tuple.order, order_tuple.algo);
public static string display_name(OrderRecordImmutable order, AlgoData? algo) {
if (algo.HasValue) {
if (!order.has_parent() && algo.HasValue) {
return algo.Value.name;
} else if (order.HasDef && order.Def.HasCustomDef) {
return order.Def.CustomDef.HasDynamic ?
@@ -244,19 +229,15 @@ namespace mbts.spark {
badge_fill(order_sam.order, order_sam.meta, order_meta);
public static Brush badge_fill(OrderRecordImmutable order, AlgoDefinitionMetadata? algo_meta, OrderMetadata order_meta) {
if (algo_meta?.badge_color is Color c) {
return c.to_brush();
} else {
return order_meta.Color.rgb_brush();
/// TODO: figure out why <see cref="OrderDefinition.AlgoTemplateKey"/> is propagated to all descendant-algos (should really just belong to the algo-node/CustomDef that is the root of the AlgoTemplate).
/// In the meantime, the following 'has-no-parent' conditional will suffice as a workaround so child-algos will be colored properly (according to their own <see cref="CustomOrderDefinition.CustomOneofCase"/>).
if (!order.has_parent()) {
if (algo_meta?.badge_color is Color c)
return c.to_brush();
}
return order_meta.Color.rgb_brush();
}
public static Color root_badge_color(this OrderSecurityAlgoMeta order_sam, OrderMetadata root_order_meta) =>
order_sam.root_meta?.badge_color is Color c ? c : root_order_meta.Color.rgb_color();
public static Brush root_badge_fill(this OrderSecurityAlgoMeta order_sam, OrderMetadata root_order_meta) =>
new SolidColorBrush(root_badge_color(order_sam, root_order_meta));
public static string order_collection_summary(double best_price, int best_price_volume, int total_volume, ContractSpecificationImmutable spec) {
if (total_volume == 0)
return string.Empty;
+20 -29
View File
@@ -18,6 +18,7 @@ using System.ComponentModel.Composition;
using System.Linq;
using System.Reactive.Concurrency;
using System.Reactive.Linq;
using System.Reactive.Subjects;
using System.Threading.Tasks;
using OrderUpdate = bts.api.core.TableUpdate<(bts.api.SecurityImmutable? sec, bts.api.orderman.OrderRecordImmutable order), uint>;
using OrderUpdatePiq = bts.api.core.TableUpdate<bts.api.orderman.OrderSecurity, uint>;
@@ -36,8 +37,7 @@ namespace mbts.spark {
readonly ErrorReporter _error;
readonly DynamicOrderHelper _dynamic_helper;
readonly OrderActivitySummarizer _activity;
readonly TableUpdateDemuxer<OrderRecordImmutable, uint, uint> _security_orders_demuxer;
readonly TableUpdateDemuxer<OrderSecurity, uint, uint> _security_working_orders_with_piq_demuxer;
readonly TableUpdateDemuxer<OrderRecordImmutable, uint, uint> _security_orders_demuxer, _security_working_orders_demuxer;
readonly TableUpdateDemuxer<PositionUnitImmutable, int, uint> _security_positions_demuxer;
IDisposable _dispose;
static readonly bool _piq_enabled = Configuration.get<bts.config.toggles.PlacementInQueue>().enabled;
@@ -82,7 +82,7 @@ namespace mbts.spark {
_activity = new OrderActivitySummarizer(bus, on_orders);
_security_orders_demuxer = new TableUpdateDemuxer<OrderRecordImmutable, uint, uint>(o => o.Key, o => o.security_key());
_security_working_orders_with_piq_demuxer = new TableUpdateDemuxer<OrderSecurity, uint, uint>(o => o.order.Key, o => o.order.security_key());
_security_working_orders_demuxer = new TableUpdateDemuxer<OrderRecordImmutable, uint, uint>(o => o.Key, o => o.security_key());
_security_positions_demuxer = new TableUpdateDemuxer<PositionUnitImmutable, int, uint>(o => o.RecordId, p => p.SecurityId);
var algo_meta_join = algo_model.definitions.LeftJoin<AlgoData, AlgoDefinitionMetadata, (AlgoData algo, AlgoDefinitionMetadata? meta), AlgoKey>(
algo_model.metadata_service.subscribe_metadata().Table(m => m.id),
@@ -95,7 +95,7 @@ namespace mbts.spark {
algo_meta_join,
t => t.order.Key,
am => am.algo.key,
t => new AlgoKey(new bts.persist.algo.AlgoPersistedKey(t.order.algo_template_key())),
t => new AlgoKey(new bts.persist.algo.AlgoPersistedKey(t.order.Def.AlgoTemplateKey)),
(os, okey, am, mkey) => new OrderSecurityAlgoMeta(os.order, os.sec, am.algo, am.meta),
(os, okey, mkey) => new OrderSecurityAlgoMeta(os.order, os.sec, null, null),
ot => ot.order.Key);
@@ -114,13 +114,13 @@ namespace mbts.spark {
(osam, _) => new OrderSecurity(osam.security, osam.order, null, osam.algo, osam.meta),
osp => osp.order.Key)
.Cache();
// order tuples with root
on_order_tuples_with_root = on_order_tuples.RootDependent(
o => o.order.Key,
o => o.order.ParentKey,
(osam, root_osam) => osam.with(root_osam.algo ?? new AlgoData(root_osam.order.Def.CustomDef), root_osam.meta)
).Cache();
// fills
working_orders_with_piq =
on_order_tuples_with_piq.Scan(
ImmutableDictionary<uint, OrderSecurity>.Empty,
(workers, table) => _update_working_orders(workers, table))
.Replay(1).RefCount();
var on_fills =
_service.subscribei_fills()
.Naggle(interval, scheduler)
@@ -152,9 +152,10 @@ namespace mbts.spark {
.Cache();
_dispose = Disposable.Create(
on_orders.Select(t => t.order, o => o.Key).Subscribe(_security_orders_demuxer),
on_order_tuples_with_piq
.Filter(os => os.order.is_active() && os.order.State.DisplayStatus == OrderState.Types.DisplayStatus.Visible, key => key.order.Key)
.Subscribe(_security_working_orders_with_piq_demuxer),
on_orders
.Filter(order => order.order.is_active() && order.order.HasState && order.order.State.DisplayStatus == OrderState.Types.DisplayStatus.Visible, key => key.order.Key)
.Select(t => t.order, o => o.Key)
.Subscribe(_security_working_orders_demuxer),
on_positions.Subscribe(_security_positions_demuxer),
_bus.subscribe(SparkTags.CreateOrder).Subscribe(a => send_order(a.definition, a.price, a.size).ignore()),
_bus.subscribe(SparkTags.RecreateOrder).Subscribe(a => a.ForEach(x => send_order(x.definition, x.price, x.size).ignore())),
@@ -171,19 +172,19 @@ namespace mbts.spark {
public IObservable<OrderUpdate> on_orders { get; }
public IObservable<OrderUpdatePiq> on_order_tuples_with_piq { get; }
public IObservable<TableUpdate<OrderSecurityAlgoMeta, uint>> on_order_tuples { get; }
public IObservable<TableUpdate<OrderSecurityAlgoMeta, uint>> on_order_tuples_with_root { get; }
public IObservable<TableUpdate<KeyValuePair<uint, bool>, uint>> on_orders_can_detach { get; }
public IObservable<TableUpdate<KeyValuePair<uint, bool>, uint>> on_orders_can_attach { get; }
public IObservable<IIncrementalUpdate<SecurityImmutable, uint>> on_order_securities { get; }
public IObservable<TableUpdate<FillTuple, string>> on_fill_tuples { get; }
public IObservable<IReadOnlyDictionary<uint,OrderSecurity>> working_orders { get; }
public IObservable<IReadOnlyDictionary<uint, OrderSecurity>> working_orders_with_piq { get; }
public IObservable<TableUpdate<PositionUnitImmutable, int>> on_positions { get; }
public AdminModel admin_model { get; }
public IAlgoStudioModel algo_model { get; }
public IObservable<TableUpdate<OrderSecurity, uint>> on_security_working_orders_with_piq(uint security) =>
_security_working_orders_with_piq_demuxer.subscribe(security);
public IObservable<TableUpdate<OrderRecordImmutable, uint>> on_security_working_orders(uint security) =>
_security_working_orders_demuxer.subscribe(security);
public IObservable<TableUpdate<OrderRecordImmutable, uint>> on_security_orders(uint security) =>
_security_orders_demuxer.subscribe(security);
@@ -227,9 +228,9 @@ namespace mbts.spark {
// order already filled to completion
return false;
}
var size = new_size ?? order.quantity();
var size = new_size ?? (uint)order.working_quantity();
var price = new_price ?? order.price();
if (size == order.quantity() && price == order.price() && !new_algo.HasValue) {
if (size == order.working_quantity() && price == order.price() && !new_algo.HasValue) {
// no parameters would be changed by this update
return false;
}
@@ -436,16 +437,6 @@ namespace mbts.spark {
return rod;
}).Select(r => r.last_update);
public static IObservable<TableUpdate<AlgoData, AlgoKey>> subscribe_all_algos(this OrdersModel orders_model) =>
orders_model.algo_model.definitions.MergeTable(Observable.Return(
new TableUpdate<AlgoData, AlgoKey>(
ImmutableDictionary<AlgoKey, AlgoData>.Empty.AddRange(orders_model.factory.default_algos(OrderDataHelper.all_order_types)),
Array.Empty<AlgoData>(),
Array.Empty<Change<AlgoData>>(),
Array.Empty<AlgoData>(),
d => d.key
).as_snapshot()));
public static async Task<OrderRecordImmutable?> order_from_key(this OrdersModel orders_model, uint order_key) {
(var tu, var success) = await orders_model.on_orders.FirstAsyncTask(t => t.state.ContainsKey(order_key), TimeSpan.FromSeconds(3));
if (success && tu.state.TryGetValue(order_key, out var rec)) {
-30
View File
@@ -81,42 +81,12 @@
</Compile>
</ItemGroup>
<ItemGroup>
<None Update="Modules\Trading\AlgoStudio\View\AlgoEditorGridView\AlgoEditorGridView.xaml">
<Generator>MSBuild:Compile</Generator>
</None>
<None Update="Modules\Trading\AlgoStudio\View\AlgoEditorView.xaml">
<Generator>MSBuild:Compile</Generator>
</None>
<None Update="Modules\Trading\Ladder\View\LadderSettingsDialog.xaml">
<Generator>MSBuild:Compile</Generator>
</None>
<None Update="Modules\Trading\Ladder\View\LadderSettingsView.xaml">
<Generator>MSBuild:Compile</Generator>
</None>
<None Update="Modules\Trading\Ladder\View\LadderView.xaml">
<Generator>MSBuild:Compile</Generator>
</None>
<None Update="Modules\Trading\Ladder\View\MiniLadderView.xaml">
<Generator>MSBuild:Compile</Generator>
</None>
<None Update="Modules\Trading\OrderBook\MiniOrderBook\MiniOrderBookView.xaml">
<Generator>MSBuild:Compile</Generator>
</None>
<None Update="Modules\Trading\OrderBook\MiniOrderBook\OrderBookView.xaml">
<Generator>MSBuild:Compile</Generator>
</None>
<None Update="Modules\Trading\OrderBook\View\OrderBookGridView.xaml">
<Generator>MSBuild:Compile</Generator>
</None>
<None Update="Modules\Trading\OrderBook\View\OrderBookToolBar.xaml">
<Generator>MSBuild:Compile</Generator>
</None>
<None Update="Modules\Trading\OrderBook\View\OrderBookView.xaml">
<Generator>MSBuild:Compile</Generator>
</None>
<None Update="Modules\Trading\OrderBook\View\OrderParamsPanel.xaml">
<Generator>MSBuild:Compile</Generator>
</None>
<None Update="view\Controls\DIYGrid\Settings\SimpleGridSettingsDialog.xaml">
<Generator>MSBuild:Compile</Generator>
</None>
@@ -188,7 +188,7 @@ namespace mbts.collections {
}
public IObservableCollection<T> items { get; }
public ObservableCollectionEx<T> selected_items { get; } = new ObservableCollectionEx<T>();
public ObservableCollection<T> selected_items { get; } = new ObservableCollection<T>();
public IEnumerable<TKey> selected_keys => selected_items.Select(_key_selector);
public bool try_select(TKey key) {
@@ -33,12 +33,6 @@ namespace mbts.ui {
public ObservantCommand(Action execute) : base(_ => execute()) { }
public ObservantCommand(Action<object> execute) : base(execute) { }
public static ICommand create(Action execute, out IObserver<bool> observer) {
var cmd = new ObservantCommand(execute);
observer = cmd;
return cmd;
}
public static ICommand create<T>(Action<T> execute, Func<T, bool> get_can_execute, out IObserver<T> observer) {
T param = default;
bool can_execute = false;
@@ -54,16 +54,19 @@ namespace System.Reflection
/// <summary>
/// Gets the generic type arguments of the generic class, or interface implemented by the current Type.
/// </summary>
/// <param name="type">The type that implements or is derived from the generic type (<paramref name="generic_def"/>).</param>
/// <param name="generic_def">The generic type definition which the current type implements (if an interface) or is derived from (if a class).</param>
/// <param name="type">The type that implements or is derived from the generic type (imp_generic_def).</param>
/// <param name="imp_generic_def">The generic type definition which the current type implements (if an interface) or is derived from (if a class).</param>
/// <returns>The generic type arguments of the generic type definition implemented or derived from by the current type.</returns>
/// <exception cref="System.InvalidOperationException">
/// The parameter generic_def does not represent a generic type definition. That is, System.Type.IsGenericTypeDefinition returns false.
/// </exception>
public static Type[] GetGenericTypeArgs(Type type, Type generic_def) =>
!generic_def.IsGenericTypeDefinition ? throw MyExceptions.not_generic_type_definition(generic_def) :
(generic_def.IsInterface ? _get_generic_interface_type_args(type, generic_def) : _get_generic_type_args(type, generic_def)) ??
throw MyExceptions.does_not_implement_or_derive_from(type, generic_def);
public static Type[] GetGenericTypeArgs(Type type, Type generic_def) {
if (!generic_def.IsGenericTypeDefinition) throw MyExceptions.not_generic_type_definition(generic_def);
Type[] rv = null;
rv = generic_def.IsInterface ? _get_generic_interface_type_args(type, generic_def) : _get_generic_type_args(type, generic_def);
if (rv == null) throw MyExceptions.does_not_implement_or_derive_from(type, generic_def);
else return rv;
}
public static IDisposable detect_property_changes<T>(T obj, Action<string> on_prop_changed, params string[] props) where T : class {
var snapshot = props.ToDictionary(p => p, p => {
@@ -11,6 +11,4 @@ namespace bts.shell
{
Task<Size> MeasureContentSize();
}
interface ISlowMeasureContentSize : IMeasureContentSize { }
}
+2 -10
View File
@@ -205,15 +205,10 @@ namespace mbts.ui.shell {
return new Property<T>(this, exp.Member.Name, default_value);
}
// WILL invoke the get_value delegate
protected DelegateProperty<T> backing<T>(string name, Func<T> get_value, params string[] invalidating_props) {
return new DelegateProperty<T>(this, name, get_value, invalidating_props);
}
// will NOT invoke the get_value delegate
protected DelegateProperty<T> backing<T>(string name, Func<T> get_value, T default_value, params string[] invalidating_props) =>
new DelegateProperty<T>(this, name, get_value, default_value, invalidating_props);
protected PropertyAutoWrapper<TModel, TView> backing<TModel, TView>(string name, TModel initial_model, Func<TModel, TView> convert) =>
new PropertyAutoWrapper<TModel, TView>(this, name, initial_model, convert, EqualityComparer<TModel>.Default);
@@ -278,10 +273,7 @@ namespace mbts.ui.shell {
protected class DelegateProperty<T> : Property<T> {
public DelegateProperty(ViewModelBase owner, string name, Func<T> get_value, params string[] invalidating_props)
: this(owner, name, get_value, get_value(), invalidating_props) { }
public DelegateProperty(ViewModelBase owner, string name, Func<T> get_value, T default_value, params string[] invalidating_props)
: base(owner, name, default_value) {
: base(owner, name, get_value()) {
_get_value = get_value;
if (invalidating_props != null && invalidating_props.Length > 0) {
var iprop_set = new HashSet<string>(invalidating_props);
@@ -290,7 +282,7 @@ namespace mbts.ui.shell {
refresh();
};
}
}
}
readonly Func<T> _get_value;
@@ -116,8 +116,7 @@ namespace mbts.ui.controls {
HubAlias = "Hub Alias",
StripName = "Strip Name",
MicCode = "Mic Code",
PositionInQueue = "PIQ",
RootAlgoType = "Root Algo"
PositionInQueue = "PIQ"
;
}
@@ -8,15 +8,16 @@ namespace mbts.ui.controls {
internal class OrderTypeColumn<TColKey> : FrameworkElementColumnBase<TColKey>, IFilterableColumn {
readonly BindingBase _badge_fill_binding, _display_name_binding;
public OrderTypeColumn(TColKey key, BindingBase badge_fill_binding, Binding display_name_binding, IDataGridColumnFilter filter, string header = DefaultColumnHeaders.OrderType) : base(key) {
public OrderTypeColumn(TColKey key, BindingBase badge_fill_binding, Binding display_name_binding, IDataGridColumnFilter filter) : base(key) {
_badge_fill_binding = badge_fill_binding;
_display_name_binding = display_name_binding;
this.filter = filter;
Header = header;
Header = DefaultColumnHeaders.OrderType;
Width = DefaultColumnWidths.OrderType;
}
public IDataGridColumnFilter filter { get; }
public virtual string filter_template => DataGridFilterKnownTemplates.DiscreteValues;
public string filter_template => DataGridFilterKnownTemplates.DiscreteValues;
public BindingBase font_weight_binding { get; set; }
public override FrameworkElement view_factory() {
@@ -36,7 +37,6 @@ namespace mbts.ui.controls {
bind(FontSizeProperty, nameof(font_size));
bind(ForegroundProperty, nameof(font_brush));
bind(HorizontalAlignmentProperty, nameof(horizontal_alignment));
bind(OrderTypeItem.WidthProperty, nameof(ActualWidth));
return v;
//
void bind(DependencyProperty dp, string path) =>
@@ -211,9 +211,7 @@ namespace mbts.ui.controls {
ActiveSelectionHighlightKey = nameof(ActiveSelectionHighlightKey),
InactiveSelectionHighlightKey = nameof(InactiveSelectionHighlightKey),
SelectionStrokeKey = nameof(SelectionStrokeKey);
public const double
DefaultRowHeight = 17,
DefaultColumnHeaderHeight = 30;
public const double DefaultRowHeight = 17;
public static readonly Thickness
DefaultCellPadding = new Thickness(4, 2, 4, 2),
AnimatableCellPadding = new Thickness(8, 2, 4, 2);
@@ -75,7 +75,7 @@
<Setter Property="CommandParameter" Value="{Binding RelativeSource={RelativeSource Self}}"/>
<Setter Property="CommandTarget" Value="{Binding RelativeSource={RelativeSource AncestorType=bts:DIYGrid}}"/>
<Setter Property="HorizontalContentAlignment" Value="Center"/>
<Setter Property="Height" Value="{x:Static bts:DIYGrid.DefaultColumnHeaderHeight}"/>
<Setter Property="Height" Value="30"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type GridViewColumnHeader}">
@@ -56,7 +56,6 @@ namespace mbts.spark.filters {
static class DataGridFilterKnownTemplates {
public const string
AlgoType = "AlgoTypeTemplate",
DoubleMinMax = "DoubleMinMaxTemplate",
IntMinMax = "IntMinMaxTemplate",
UIntMinMax = "UIntMinMaxTemplate",
@@ -1,19 +1,13 @@
using bts.api.core;
using bts.collections;
using bts.utils;
using bts.collections;
using mbts.collections;
using mbts.ui.shell;
using mbts.ui.utilities;
using mbts.ui.utility;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Linq;
using System.Reactive.Linq;
using System.Windows.Data;
namespace mbts.spark.filters {
static class DiscreteValuesFilterVM {
@@ -64,14 +58,6 @@ namespace mbts.spark.filters {
IEqualityComparer<TValue> equality_comparer = null,
IComparer<TValue> comparer = null
) => new DynamicItemsFilter<TRow, TValue, TState>(items, get_row_val, get_state, load_state, prop_name, equality_comparer ?? EqualityComparer<TValue>.Default, comparer);
public static IDataGridColumnPersistentFilter<TRow, TKey[]> CreateTableUpdate<TRow, TValue, TKey>(
Func<TRow, TValue> factory, Func<TRow, TKey> row_key, Func<TValue, TKey> key, out IObserver<TableUpdate<TValue, TKey>> items_observer, out ListCollectionView<TValue> items_view) where TKey : struct, IEquatable<TKey> {
var filter = new TableUpdateItemsFilter<TRow, TValue, TKey, TKey[]>(factory, row_key, key, keys => keys, keys => keys.ToArray());
items_observer = filter;
items_view = filter.items_view;
return filter;
}
#endregion
#region Implementation (private)
@@ -252,67 +238,6 @@ namespace mbts.spark.filters {
}
}
}
class TableUpdateItemsFilter<TRow, TValue, TKey, TState> : FilterVMBase<TRow, TValue, TState>, IObserver<TableUpdate<TValue, TKey>> where TKey : struct, IEquatable<TKey> {
readonly ObservableKeyedCollection<TValue, TKey> _items;
readonly KeyedMultiSelector<TValue, TKey> _selection_model;
readonly Func<TValue, TKey> _key;
readonly Func<TRow, TValue> _factory;
readonly Func<TRow, TKey> _row_key;
readonly Func<TState, IEnumerable<TKey>> _load_state;
readonly Func<IEnumerable<TKey>, TState> _get_state;
readonly IEqualityComparer<TValue> _comparer;
readonly HashSet<TKey> _selected_keys = new HashSet<TKey>();
ListCollectionView<TValue> _items_view;
public TableUpdateItemsFilter(Func<TRow, TValue> factory, Func<TRow, TKey> row_key, Func<TValue, TKey> key, Func<TState, IEnumerable<TKey>> load_state, Func<IEnumerable<TKey>, TState> get_state)
: base(factory, null) {
_factory = factory;
_row_key = row_key;
_key = key;
_load_state = load_state;
_get_state = get_state;
_comparer = EqualityComparer.Create(_key);
_items = new ObservableKeyedCollection<TValue, TKey>(_key);
_selection_model = new KeyedMultiSelector<TValue, TKey>(_items, _key);
}
public ObservableCollection<TValue> items => _items;
public ListCollectionView<TValue> items_view => _items_view ?? (_items == null ? null : (_items_view = new ListCollectionView<TValue>(_items)));
public IObservableCollectionEx<TValue> selected_items => _selection_model?.selected_items;
void IObserver<TableUpdate<TValue, TKey>>.OnCompleted() { }
void IObserver<TableUpdate<TValue, TKey>>.OnError(Exception error) { }
void IObserver<TableUpdate<TValue, TKey>>.OnNext(TableUpdate<TValue, TKey> table) {
foreach (var v in table.removed)
_items.Remove(_key(v));
foreach (var ch in table.changes)
_items.Replace(_key(ch.Old), ch.New);
foreach (var v in table.added)
_items.Add(v);
}
public override TState get_state() => _get_state(_selection_model.selected_items.Select(_key));
protected override bool _get_active() => _selection_model.selected_items.Count > 0;
protected override void _apply() {
_selected_keys.SetItems(selected_items.Select(_key));
base._apply();
}
protected override void _clear() {
_destroy_snapshot();
_selection_model.selected_items.Clear();
_close();
_raise_filter_changed();
}
protected override bool _filter(TValue value) => _selected_keys.Contains(_key(value));
protected override void _load_state_internal(TState state) {
foreach (var k in _load_state(state).empty_if_null())
_selection_model.try_select(k);
}
}
#endregion
[Browsable(false)]
@@ -14,7 +14,7 @@ namespace mbts.spark.filters {
protected FilterVMBase(Func<TRow, TValue> get_row_val, string prop_name) {
_get_row_val = get_row_val;
this.prop_name = prop_name;
_active = backing(nameof(active), () => HasErrors ? new bool?() : _get_active(), false);
_active = backing(nameof(active), () => HasErrors ? new bool?() : _get_active());
_snapshot = _get_snapshot();
apply = new DelegateCommand(_apply);
cancel = new DelegateCommand(_cancel);
@@ -6,7 +6,6 @@
xmlns:msp="clr-namespace:mbts.spark"
xmlns:sys="clr-namespace:System;assembly=mscorlib">
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="/view/Resources/ComboBoxes.xaml"/>
<ResourceDictionary Source="/view/Controls/DataGridEx/Filters/Views/DoubleMinMaxFilterControl.xaml"/>
<ResourceDictionary Source="/view/Controls/DataGridEx/Filters/Views/IntMinMaxFilterControl.xaml"/>
<ResourceDictionary Source="/view/Controls/DataGridEx/Filters/Views/UIntMinMaxFilterControl.xaml"/>
@@ -147,25 +146,6 @@
/>
</usp:FilterContentControl>
</DataTemplate>
<DataTemplate x:Key="AlgoTypeTemplate">
<usp:FilterContentControl
ApplyCommandParameter="{Binding}"
ApplyCommand="{x:Static c:DataGridFilterProperties.CommitCommand}"
ClearCommandParameter="{Binding}"
ClearCommand="{x:Static c:DataGridFilterProperties.ClearCommand}"
>
<c:ListBoxEx
ItemsSource="{Binding items_view}"
Selection="{Binding selected_items}"
SelectionMode="Multiple"
ItemContainerStyle="{StaticResource ListBoxItemCheckBoxStyle}"
>
<c:ListBoxEx.GroupStyle>
<GroupStyle ContainerStyle="{StaticResource ComboBox.DelineatedGroupContainerStyle}"/>
</c:ListBoxEx.GroupStyle>
</c:ListBoxEx>
</usp:FilterContentControl>
</DataTemplate>
<DataTemplate x:Key="YesNoTemplate">
<usp:FilterContentControl
ApplyCommandParameter="{Binding}"
@@ -532,7 +532,7 @@
<VisualState Name="{StaticResource CannotEditValuesState}">
<VisualState.Storyboard>
<Storyboard>
<BooleanAnimationUsingKeyFrames Storyboard.TargetName="PART_HedgeTicks_TickUpDownNullableUInt" Storyboard.TargetProperty="(UIElement.IsEnabled)">
<BooleanAnimationUsingKeyFrames Storyboard.TargetName="PART_HedgeTicks_TickUpDownNullableInt" Storyboard.TargetProperty="(UIElement.IsEnabled)">
<DiscreteBooleanKeyFrame KeyTime="0" Value="False"/>
</BooleanAnimationUsingKeyFrames>
</Storyboard>
@@ -556,7 +556,7 @@
<TextBlock VerticalAlignment="Center">Hedge Ticks</TextBlock>
<c:HelpButton Margin="{StaticResource Margin.LP1}" ToolTip="This is the number of ticks to offset the hedge."/>
</StackPanel>
<c:TickUpDownNullableUInt x:Name="PART_HedgeTicks_TickUpDownNullableUInt" Grid.Column="2" HorizontalAlignment="Stretch" Value="{Binding hedge_ticks}"/>
<c:TickUpDownNullableInt x:Name="PART_HedgeTicks_TickUpDownNullableInt" Grid.Column="2" HorizontalAlignment="Stretch" Value="{Binding hedge_ticks}"/>
<uag:AlgoPickerNodeView
x:Name="PART_Hedge_AlgoPickerNodeView"
Grid.Row="2"
@@ -233,22 +233,6 @@
<TextBlock Text="{Binding Definition.name, RelativeSource={RelativeSource TemplatedParent}, StringFormat='{}Save \&apos;{0}\&apos;'}"/>
</MenuItem.ToolTip>
</MenuItem>
<MenuItem
x:Name="PART_SetDefaults_MenuItem"
Command="{TemplateBinding SetDefaultsCommand}"
Style="{StaticResource AlgoMenuItem}"
>
<MenuItem.Header>
<Image Source="{x:Static u:Icons.RubberStamp}"/>
</MenuItem.Header>
<MenuItem.ToolTip>
<TextBlock>
Make current paramaters the local defaults
<LineBreak/>
<Italic>These values will be lost when the ladder closes.</Italic>
</TextBlock>
</MenuItem.ToolTip>
</MenuItem>
<MenuItem
x:Name="PART_Undo_MenuItem"
Command="{TemplateBinding UndoCommand}"
@@ -307,11 +291,13 @@
CommandParameter="{Binding Definition, RelativeSource={RelativeSource TemplatedParent}}"
HorizontalContentAlignment="Center"
Style="{StaticResource AlgoMenuItem}"
ToolTip="Revert parameters to the local defaults."
>
<MenuItem.Header>
<Image Source="{x:Static u:Icons.UndoCircular}"/>
</MenuItem.Header>
<MenuItem.ToolTip>
<TextBlock Text="{Binding Definition.name, RelativeSource={RelativeSource TemplatedParent}, StringFormat='{}Undo changes to \&apos;{0}\&apos;'}"/>
</MenuItem.ToolTip>
</MenuItem>
<MenuItem
x:Name="PART_IsFavorite_MenuItem"
@@ -124,8 +124,8 @@ namespace mbts.ui.spark.algo {
public static readonly DependencyProperty ShowRevertDefinitionProperty =
WPFHelper.create_dp<bool, AlgoTemplateToolBar>(
nameof(ShowRevertDefinition),
VisualStateNames.RevertDefinition.apply/*,
coerce_require_persisted*/);
(o, v) => VisualStateNames.RevertDefinition.apply(o._vsm, v),
coerce_require_persisted);
public bool ShowRevertDefinition { get => (bool)GetValue(ShowRevertDefinitionProperty); set => SetValue(ShowRevertDefinitionProperty, value); }
#endregion
@@ -156,7 +156,7 @@ namespace mbts.ui.spark.algo {
(o, v) => {
o.CoerceValue(ShowRenameDefinitionProperty);
o.CoerceValue(ShowSaveDefinitionProperty);
//o.CoerceValue(ShowRevertDefinitionProperty);
o.CoerceValue(ShowRevertDefinitionProperty);
o.CoerceValue(ShowUndoRedoButtonsProperty);
});
@@ -214,12 +214,6 @@ namespace mbts.ui.spark.algo {
public ICommand SaveDefinitionCommand { get => GetValue(SaveDefinitionCommandProperty) as ICommand; set => SetValue(SaveDefinitionCommandProperty, value); }
#endregion
#region SetDefaults
public static readonly DependencyProperty SetDefaultsCommandProperty =
WPFHelper.create_dp<ICommand, AlgoTemplateToolBar>(nameof(SetDefaultsCommand));
public ICommand SetDefaultsCommand { get => GetValue(SetDefaultsCommandProperty) as ICommand; set => SetValue(SetDefaultsCommandProperty, value); }
#endregion
#region Revert
public static readonly DependencyProperty RevertCommandProperty =
WPFHelper.create_dp<ICommand, AlgoTemplateToolBar>(nameof(RevertCommand));
@@ -441,7 +435,7 @@ namespace mbts.ui.spark.algo {
public static class VisualStateNames {
public static void apply_all(AlgoTemplateToolBar toolbar) {
UndoRedo.apply(toolbar._vsm, toolbar.ShowUndoRedoButtons);
RevertDefinition.apply(toolbar, toolbar.ShowRevertDefinition);
RevertDefinition.apply(toolbar._vsm, toolbar.ShowRevertDefinition);
RenameDefinition.apply(toolbar._vsm, toolbar.ShowRenameDefinition);
SaveDefinition.apply(toolbar._vsm, toolbar.ShowSaveDefinition);
TemplatesDropDown.apply(toolbar._vsm, toolbar.ShowTemplatesDropDown);
@@ -463,8 +457,8 @@ namespace mbts.ui.spark.algo {
Active = $"{GroupName}{VisualStates.Active}",
Inactive = $"{GroupName}{VisualStates.Inactive}";
public static void apply(AlgoTemplateToolBar owner, bool active) =>
owner.Dispatcher.InvokeAsync(() => owner._vsm.set_state(GroupName, active ? Active : Inactive));
public static void apply(VisualStateModel vsm, bool active) =>
vsm.set_state(GroupName, active ? Active : Inactive);
}
public static class RenameDefinition {
public const string GroupName = nameof(RenameDefinition);
@@ -150,8 +150,7 @@
UndoDefinitionCommand="{Binding undo_definition_cmd}"
RedoDefinitionCommand="{Binding redo_definition_cmd}"
ShowUndoRedoButtons="{DynamicResource {x:Static sp:AlgoStudioWindow.ShowAlgoToolBarUndoRedoDefinitionKey}}"
SetDefaultsCommand="{Binding set_default_algo_params_cmd}"
RevertDefinitionCommand="{Binding revert_algo_params_cmd}"
RevertDefinitionCommand="{Binding revert_definition_cmd}"
ShowRevertDefinition="{DynamicResource {x:Static sp:AlgoStudioWindow.ShowAlgoToolBarRevertDefinitionKey}}"
SaveCommand="{Binding save_template_cmd}"
SaveDefinitionCommand="{Binding save_definition_cmd}"
@@ -203,7 +202,6 @@
x:Name="ParamGridView"
Grid.Row="1"
Margin="12,8,12,12"
AnimateDirty="False"
CanUserChangeAlgoRoot="False"
AlgoParamRows="{Binding algo_param_rows}"
Visibility="Visible"
@@ -17,6 +17,10 @@
<cv:KeyValue Key="{x:Static Ratio, MemberType={u:Nested sp:QuantityMeasure.QuantityOneofCase}}" Value="{u:True}"/>
<cv:KeyValue Key="{x:Static Absolute, MemberType={u:Nested sp:QuantityMeasure.QuantityOneofCase}}" Value="{u:False}"/>
</cv:ValueMap>
<cv:ValueMap x:Key="QuantityCaseVisualStateConverter" Default="{x:Null}">
<cv:KeyValue Key="{x:Static Absolute, MemberType={u:Nested sp:QuantityMeasure.QuantityOneofCase}}" Value="{x:Static Absolute, MemberType={u:Nested uag:QuantityMeasureControl.VisualStateNames.QuantityCase}}"/>
<cv:KeyValue Key="{x:Static Ratio, MemberType={u:Nested sp:QuantityMeasure.QuantityOneofCase}}" Value="{x:Static Ratio, MemberType={u:Nested uag:QuantityMeasureControl.VisualStateNames.QuantityCase}}"/>
</cv:ValueMap>
<!--Component Styles-->
<Style x:Key="AbsoluteTickUpDownStyle" TargetType="c:TickUpDownUInt">
<Setter Property="MinWidth" Value="{StaticResource TickUpDownMinWidth}"/>
@@ -48,20 +52,13 @@
<u:StateManager.Groups>
<u:StateGroupsManager AttachToMembers="True">
<u:StateDefinitionCollection>
<u:StateDefinition State="{Binding Path='(u:StateDefinition.Group).(u:StateGroupsManager.Target).(Grid.TemplatedParent).(uag:QuantityMeasureControl.QuantityCase)', RelativeSource={RelativeSource Self}, Converter={x:Static uag:QuantityMeasureControl.QuantityCaseVisualStateConverter}}"/>
<u:StateDefinition State="{Binding Path='(u:StateDefinition.Group).(u:StateGroupsManager.Target).(Grid.TemplatedParent).(uag:QuantityMeasureControl.QuantityCase)', RelativeSource={RelativeSource Self}, Converter={StaticResource QuantityCaseVisualStateConverter}}"/>
</u:StateDefinitionCollection>
</u:StateGroupsManager>
</u:StateManager.Groups>
<VisualStateManager.VisualStateGroups>
<VisualStateGroup Name="{x:Static GroupName, MemberType={u:Nested uag:QuantityMeasureControl.VisualStateNames.QuantityCase}}">
<VisualState/>
<VisualState Name="{x:Static None, MemberType={u:Nested uag:QuantityMeasureControl.VisualStateNames.QuantityCase}}">
<Storyboard>
<ObjectAnimationUsingKeyFrames Storyboard.TargetName="PART_Absolute_TickUpDown" Storyboard.TargetProperty="(UIElement.Visibility)">
<DiscreteObjectKeyFrame KeyTime="0" Value="{x:Static Visibility.Visible}"/>
</ObjectAnimationUsingKeyFrames>
</Storyboard>
</VisualState>
<VisualState Name="{x:Static Absolute, MemberType={u:Nested uag:QuantityMeasureControl.VisualStateNames.QuantityCase}}">
<Storyboard>
<ObjectAnimationUsingKeyFrames Storyboard.TargetName="PART_Absolute_TickUpDown" Storyboard.TargetProperty="(UIElement.Visibility)">
@@ -116,20 +113,13 @@
<u:StateManager.Groups>
<u:StateGroupsManager AttachToMembers="True" OverrideTarget="True" Target="{Binding Path='(Border.TemplatedParent)', Source={u:DirectReference Border}}">
<u:StateDefinitionCollection>
<u:StateDefinition State="{Binding Path='(u:StateDefinition.Group).(u:StateGroupsManager.Target).(uag:QuantityMeasureControl.QuantityCase)', RelativeSource={RelativeSource Self}, Converter={x:Static uag:QuantityMeasureControl.QuantityCaseVisualStateConverter}}"/>
<u:StateDefinition State="{Binding Path='(u:StateDefinition.Group).(u:StateGroupsManager.Target).(uag:QuantityMeasureControl.QuantityCase)', RelativeSource={RelativeSource Self}, Converter={StaticResource QuantityCaseVisualStateConverter}}"/>
</u:StateDefinitionCollection>
</u:StateGroupsManager>
</u:StateManager.Groups>
<VisualStateManager.VisualStateGroups>
<VisualStateGroup Name="{x:Static GroupName, MemberType={u:Nested uag:QuantityMeasureControl.VisualStateNames.QuantityCase}}">
<VisualState/>
<VisualState Name="{x:Static None, MemberType={u:Nested uag:QuantityMeasureControl.VisualStateNames.QuantityCase}}">
<Storyboard>
<ObjectAnimationUsingKeyFrames Storyboard.TargetName="PART_Absolute_TickUpDown" Storyboard.TargetProperty="(UIElement.Visibility)">
<DiscreteObjectKeyFrame KeyTime="0" Value="{x:Static Visibility.Visible}"/>
</ObjectAnimationUsingKeyFrames>
</Storyboard>
</VisualState>
<VisualState Name="{x:Static Absolute, MemberType={u:Nested uag:QuantityMeasureControl.VisualStateNames.QuantityCase}}">
<Storyboard>
<ObjectAnimationUsingKeyFrames Storyboard.TargetName="PART_Absolute_TickUpDown" Storyboard.TargetProperty="(UIElement.Visibility)">
@@ -1,12 +1,10 @@
using bts.spark;
using mbts.ui.controls;
using mbts.ui.converters;
using mbts.ui.utilities;
using mbts.ui.utility;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Input;
namespace mbts.ui.spark.algo {
@@ -14,10 +12,6 @@ namespace mbts.ui.spark.algo {
/// Interaction logic for QuantityMeasure.xaml
/// </summary>
class QuantityMeasureControl : Control {
// converters
public static readonly IValueConverter QuantityCaseVisualStateConverter =
ValueConverter.create<QuantityMeasure.QuantityOneofCase, string>(VisualStateNames.QuantityCase.fmt_state_name);
// defaults
static readonly QuantityMeasureImmutable _default_quantity_measure = new QuantityMeasureImmutable(new QuantityMeasure { Absolute = 0 });
static uint _default_absolute => _default_quantity_measure.QuantityCase == bts.spark.QuantityMeasure.QuantityOneofCase.Ratio ? _default_quantity_measure.Absolute : default;
@@ -179,12 +173,8 @@ namespace mbts.ui.spark.algo {
public const string GroupName = nameof(QuantityCase);
public static readonly string
None = fmt_state_name(bts.spark.QuantityMeasure.QuantityOneofCase.None),
Absolute = fmt_state_name(bts.spark.QuantityMeasure.QuantityOneofCase.Absolute),
Ratio = fmt_state_name(bts.spark.QuantityMeasure.QuantityOneofCase.Ratio);
public static string fmt_state_name(bts.spark.QuantityMeasure.QuantityOneofCase quantity_case) =>
$"{GroupName}{quantity_case}";
Absolute = $"{GroupName}{nameof(Absolute)}",
Ratio = $"{GroupName}{nameof(Ratio)}";
}
}
}
@@ -1,23 +0,0 @@
using bts.api;
using mbts.spark;
using System;
using System.Windows;
using System.Windows.Input;
namespace mbts.ui.spark {
static class RoutedSparkCommands {
public static RoutedCommand LaunchAlgoStudioCommand = new RoutedCommand();
public static readonly ExecutedRoutedEventHandler
LaunchAlgoStudioExecuted = _executed(SparkTags.ShowAlgoStudioTag);
public static readonly CanExecuteRoutedEventHandler
LaunchAlgoStudioCanExecute = (s, e) => e.CanExecute = true;
static ExecutedRoutedEventHandler _executed<T>(ITag<T> tag) =>
(sender, e) => {
if (sender is FrameworkElement el && el.TryFindResource("Bus") is IBus bus)
bus.post(tag, ConvertUtils.try_convert<T>(e.Parameter));
};
}
}
@@ -30,12 +30,6 @@ namespace mbts.ui {
static void _on_preview_mouse_wheel(object sender, MouseWheelEventArgs e) {
if (!e.Handled && sender is ScrollViewer sv && !_reentrancy_list.Contains(e)) {
if (e.Source is GridViewColumnHeader && Window.GetWindow(sv) == null) {
// This is a hack specifically for the DIYGrid filter popup (namely, the DiscreteValues ListBox-based template - it doesn't scroll otherwise)...i really, really hate this bug.
// The end of the cycle approaches, so unf there is not time to dig deeper into this and find a cleaner fix.
// - John, 05/06/2019
return;
}
var preview_event_arg = new MouseWheelEventArgs(e.MouseDevice, e.Timestamp, e.Delta) {
RoutedEvent = UIElement.PreviewMouseWheelEvent,
Source = sender
@@ -171,9 +171,6 @@ namespace mbts.ui.shell
var shell_window = document.ViewModel.Model;
var mcs = shell_window as bts.shell.IMeasureContentSize;
if (mcs != null) {
if (shell_window is ISlowMeasureContentSize) {
Show();
}
var size =
shell_window is ISlowWindow || shell_window is ISharedWindow ?
await await document.ViewModel.Dispatcher.InvokeAsync(() => mcs.MeasureContentSize()) :
@@ -1,5 +1,4 @@
using bts.api;
using bts.collections;
using mbts.ui;
using mbts.ui.controls;
using mbts.ui.shell;
@@ -70,7 +69,6 @@ namespace mbts.spark
_current_row = backing(nameof(current_row), default(TRow));
readonly Property<TRow> _current_row;
public event Action<(IEnumerable<TRow> removed, IEnumerable<TRow> added)> selection_changed;
public new TRow current_row { get => _current_row.Value; set => _current_row.Value = value ?? selected_rows.FirstOrDefault(); }
public override IObservable<TRow> current_row_observable => _current_row.Select(v => v.newval);
@@ -79,10 +77,35 @@ namespace mbts.spark
RowSelectionHelper.apply_changes(selected_rows, e);
if (selected_rows.Count == 0) _current_row.Value = null;
else if (_current_row.Value == null) _current_row.Value = selected_rows[0];
selection_changed?.Invoke((e.RemovedItems.OfTypeSafe<TRow>(), e.AddedItems.OfTypeSafe<TRow>()));
}
}
abstract class SecurityGrid<TRow, TRowModel, TCol> : SecurityGridBase<TRow, TRowModel>, IHandleCellSelection where TRow : class, ISecurityRow
{
protected SecurityGrid(IObservable<IEnumerable<TRowModel>> row_models, IEnumerable<SortingCriteria> sorting_criteria)
: this(RXCollection.Create(row_models), sorting_criteria) { }
protected SecurityGrid(IObservable<IEnumerable<TRowModel>> row_models, IEqualityComparer<TRowModel> comparer, IEnumerable<SortingCriteria> sorting_criteria)
: this(RXCollection.Create(row_models, comparer), sorting_criteria) { }
protected SecurityGrid(IRXCollection<TRowModel> row_models, IEnumerable<SortingCriteria> sorting_criteria) : base(row_models, sorting_criteria) =>
_current_cell = backing<DataGridCellInfo>(nameof(current_cell));
readonly Property<DataGridCellInfo> _current_cell;
IDictionary<TRow, HashSet<TCol>> _selection_map = new Dictionary<TRow, HashSet<TCol>>();
public DataGridCellInfo current_cell {
get => _current_cell.Value;
set { if (value.IsValid) _current_cell.Value = value; }
}
public override TRow current_row => _current_cell.Value.Item as TRow ?? selected_rows.FirstOrDefault();
public override IObservable<TRow> current_row_observable => _current_cell.Select(v => v.newval.Item as TRow);
public IDictionary<TRow, HashSet<TCol>> get_selection_map() => new Dictionary<TRow, HashSet<TCol>>(_selection_map);
void IHandleCellSelection.cell_selection_changed(IList<DataGridCellInfo> added, IList<DataGridCellInfo> removed) =>
CellSelectionMapper.apply_changes(_selection_map, added, removed, selected_rows);
}
static class SecurityGridExtensions
{
public static IObservable<SecurityMD?> current_security_md_observable<TRow, TRowModel>(this SecurityGridBase<TRow, TRowModel> security_grid, IBus bus)
@@ -99,14 +122,23 @@ namespace mbts.spark
where TRow : class, ISecurityRow =>
security_grid.selected_securities.ObserveSelf();
public static IObservable<IReadOnlyList<SecurityImmutable>> sorted_selected_securities_observable<TRow, TRowModel>(this SecurityGridBase<TRow, TRowModel> security_grid)
where TRow : class, ISecurityRow =>
security_grid.selected_rows
.ObserveSelf()
.Select(rows =>
rows.Select(
row => (security: row.security, row_index: security_grid.rows_view.indexOf(row))
)
.OrderBy(sec_vs_index => sec_vs_index.row_index)
.Select(sec_vs_index => sec_vs_index.security)
.ToReadOnlyList()
);
public static IObservable<IReadOnlyList<SecurityMD>> selected_security_mds_observable<TRow, TRowModel>(this SecurityMDGrid<TRow, TRowModel> security_md_grid)
where TRow : class, ISecurityMDRow =>
Observable.Create<IReadOnlyList<SecurityMD>>(o => {
var sec_md_list = security_md_grid.selected_rows.WrapSelectorRO(r => r.md);
o.OnNext(sec_md_list);
security_md_grid.selection_changed += on_selection_changed;
return Disposable.Create(() => security_md_grid.selection_changed += on_selection_changed);
void on_selection_changed((IEnumerable<TRow> removed, IEnumerable<TRow> added) change) => o.OnNext(sec_md_list);
});
security_md_grid.selected_rows.ObserveSelf(true).Select(rows => rows.Select(r => r.md).ToReadOnlyList());
}
}
@@ -21,4 +21,16 @@ namespace mbts.spark
public IObservable<SecurityMD?> current_security_md =>
current_row_observable.Select(r => r?.md).DistinctUntilChanged(EqualityComparer.CreateNullable<SecurityMD, uint>(md => md.security.Id));
}
abstract class SecurityMDGrid<TRow, TRowModel, TCol> : SecurityGrid<TRow, TRowModel, TCol> where TRow : class, ISecurityMDRow
{
protected SecurityMDGrid(IObservable<IEnumerable<TRowModel>> row_models, IEnumerable<SortingCriteria> sorting_criteria)
: base(row_models, sorting_criteria) { }
protected SecurityMDGrid(IObservable<IEnumerable<TRowModel>> row_models, IEqualityComparer<TRowModel> comparer, IEnumerable<SortingCriteria> sorting_criteria)
: base(row_models, comparer, sorting_criteria) { }
public IObservable<SecurityMD?> current_security_md =>
current_row_observable.Select(r => r?.md).DistinctUntilChanged(EqualityComparer.CreateNullable<SecurityMD, uint>(md => md.security.Id));
}
}
@@ -2,15 +2,7 @@
using System.Collections.Generic;
namespace mbts.spark {
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;
static class SecurityDataHelper {
public static class EqualityComparer {
public static readonly IEqualityComparer<SecurityMD> MDComparer = bts.utils.EqualityComparer.Create<SecurityMD>(Equals, GetHashCode);
public static bool Equals(SecurityMD x, SecurityMD y) => x.security.Id == y.security.Id;
-13
View File
@@ -206,8 +206,6 @@ namespace bts.api.core {
}
public class TableUpdate<T, TKey> where TKey : IEquatable<TKey> {
// warning: this does not have a key_extractor
public static readonly TableUpdate<T, TKey> empty = new TableUpdate<T, TKey>(ImmutableDictionary<TKey, T>.Empty, Array.Empty<T>(), Array.Empty<Change<T>>(), Array.Empty<T>(), null);
readonly ImmutableDictionary<TKey, T> _state;
@@ -256,7 +254,6 @@ 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<T>(kv.Value, new_val));
builder[kv.Key] = new_val;
}
} else {
removed.Add(kv.Value);
@@ -430,16 +427,6 @@ namespace bts.api.core {
}
public static class ObservableUpdateExtensions {
public static IEnumerable<T> Old<T>(this IEnumerable<Change<T>> changes) {
foreach (var ch in changes)
yield return ch.Old;
}
public static IEnumerable<T> New<T>(this IEnumerable<Change<T>> changes) {
foreach (var ch in changes)
yield return ch.New;
}
internal static bool has_changes<T, TKey>(this TableUpdate<T, TKey> table) where TKey : IEquatable<TKey> =>
table.added.Any() || table.changes.Any() || table.removed.Any();
@@ -27,9 +27,6 @@ namespace System.Collections.Generic {
public static IEnumerable<T> Intersect<T, TKey>(this IEnumerable<T> enumerable, IEnumerable<TKey> second, Func<T, TKey> key_selector) =>
enumerable.Where(t => second.Contains(key_selector(t)));
public static IEnumerable<T> OfTypeSafe<T>(this IEnumerable source) =>
source == null ? Enumerable.Empty<T>() : source.OfType<T>();
public static T[] ToLArray<T>(this IEnumerable<T> enumerable) =>
enumerable.ToList().ToArray();
@@ -75,7 +75,6 @@ namespace bts.collections {
yield return v;
}
}
// update
public void update(IEnumerable<T> added, IEnumerable<T> changed, IEnumerable<TKey> removed) {
foreach (var k in removed) {
+3 -124
View File
@@ -2,121 +2,10 @@
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<TableUpdate<T, TKey>> RootDependent<T, TKey>(
this IObservable<TableUpdate<T, TKey>> source,
Func<T, TKey> key,
Func<T, TKey> parent_key,
Func<T, T, T> with_root)
where TKey : IEquatable<TKey> =>
RootDependent(source, key, parent_key, with_root, v => v, EqualityComparer<T>.Default, default).SelectKeyValue(kv => kv.Value, key);
// TODO: unit tests
public static IObservable<TableUpdate<KeyValuePair<TKey, TResult>, TKey>> RootDependent<T, TKey, TResult>(
this IObservable<TableUpdate<T, TKey>> source,
Func<T, TKey> key,
Func<T, TKey> parent_key,
Func<T, T, TResult> get_result,
Func<T, TResult> get_result_no_parent,
IEqualityComparer<TResult> result_comparer,
TKey no_parent_key)
where TKey : IEquatable<TKey> =>
Observable.Create<TableUpdate<KeyValuePair<TKey, TResult>, TKey>>(observer => {
var value_comparer = EqualityComparer.Create<KeyValuePair<TKey, TResult>, TResult>(kv => kv.Value, result_comparer);
var state = DictionaryHelper.empty<TKey, T>();
var output = TableUpdate<KeyValuePair<TKey, TResult>, TKey>.mk_empty(kv => kv.Key);
var parent_to_children = new SetMap<TKey, T>();
return source.Subscribe(update);
//
void update(TableUpdate<T, TKey> 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<T> children)) {
foreach (var child in children) {
var ck = key(child);
builder.add_or_update(new KeyValuePair<TKey, TResult>(ck, get_result_no_parent(child)));
foreach (var d in descendents(ck))
builder.add_or_update(new KeyValuePair<TKey, TResult>(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<TKey, TResult>(key(d), get_result(d, v)));
} else {
result = get_result(v, root);
}
builder.add_or_update(new KeyValuePair<TKey, TResult>(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<TKey, TResult>(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<TKey, TResult>(key(d), get_result(d, v)));
} else {
result = get_result(v, root);
}
}
builder.add_or_update(new KeyValuePair<TKey, TResult>(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<T> descendents(TKey k) {
if (parent_to_children.try_lookup(k, out ISet<T> children)) {
foreach (var child in children) {
yield return child;
foreach (var d in descendents(key(child)))
yield return d;
}
}
}
});
public static IObservable<TableUpdate<T, TKey>> MergeTable<T, TKey>(this IObservable<TableUpdate<T, TKey>> source, IObservable<TableUpdate<T, TKey>> other) where TKey : IEquatable<TKey> =>
source.AggregateLatest(other, _Merge<T, TKey>.source_change_del, _Merge<T, TKey>.other_change_del, () => TableUpdate<T, TKey>.empty, TableUpdate<T, TKey>.empty, TableUpdate<T, TKey>.empty);
public static IObservable<TableUpdate<KeyValuePair<TKey, TResult>, TKey>> ParentDependent<T, TKey, TResult>(
this IObservable<TableUpdate<T, TKey>> source,
Func<T, TKey> key,
@@ -135,6 +24,7 @@ namespace bts.utils {
Func<T, TResult> get_result_no_parent,
IEqualityComparer<TResult> result_comparer,
TKey no_parent_key)
where TResult : IEquatable<TResult>
where TKey : IEquatable<TKey> =>
Observable.Create<TableUpdate<KeyValuePair<TKey, TResult>, TKey>>(observer => {
var value_comparer = EqualityComparer.Create<KeyValuePair<TKey, TResult>, TResult>(kv => kv.Value, result_comparer);
@@ -175,23 +65,12 @@ namespace bts.utils {
}
var result = builder.to_table_checked(value_comparer);
if (result.has_changes())
observer.OnNext(output = result);
observer.OnNext(output = builder.to_table());
}
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<T, TKey> where TKey : IEquatable<TKey> {
public static readonly Func<TableUpdate<T, TKey>, Change<TableUpdate<T, TKey>>, TableUpdate<T, TKey>, TableUpdate<T, TKey>> source_change_del = _source_changed_impl;
public static readonly Func<TableUpdate<T, TKey>, TableUpdate<T, TKey>, Change<TableUpdate<T, TKey>>, TableUpdate<T, TKey>> other_change_del = _other_changed_impl;
static TableUpdate<T, TKey> _source_changed_impl(TableUpdate<T, TKey> target, Change<TableUpdate<T, TKey>> source_change, TableUpdate<T, TKey> other_table) =>
TableUpdate<T, TKey>.update(target, source_change.New.added, source_change.New.changes, source_change.New.removed, source_change.New.key_extractor);
static TableUpdate<T, TKey> _other_changed_impl(TableUpdate<T, TKey> target, TableUpdate<T, TKey> source_table, Change<TableUpdate<T, TKey>> other_change) =>
TableUpdate<T, TKey>.update(target, other_change.New.added, other_change.New.changes, other_change.New.removed, other_change.New.key_extractor);
}
}
}
}
+1 -1
View File
@@ -1 +1 @@
set(sources api/apicore.proto;api/apigateway.proto;api/apioptions.proto;api/core/ApiClientInterop.cpp;api/core/ApiServerInterop.cpp;api/public/ApiServer.cpp;api/public/ClientChannel.cpp;api/public/QuickbusClientChannel.cpp;api/public/ServerChannel.cpp;api/public/ServiceContext.cpp;api/service_helpers/AdminServiceUtils.cpp;api/service_helpers/AlgoServiceUtils.cpp;api/services/AdminService.proto;api/services/AlgoDefinitionService.proto;api/services/AlgoService.proto;api/services/ApiUnitTestService.proto;api/services/AuthService.proto;api/services/ErrorReportService.proto;api/services/HelloService.proto;api/services/MBOService.proto;api/services/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.cLine truncated
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.cLine truncated
+3 -5
View File
@@ -57,9 +57,6 @@ 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;
@@ -67,6 +64,7 @@ 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;
@@ -168,7 +166,7 @@ message TriggerOrderDefinition {
}
message CoverOrderDefinition {
CustomOrderDefinition hedge = 1;
uint32 hedge_ticks = 2;
int32 hedge_ticks = 2;
CustomOrderDefinition child = 3;
}
message OffsetOrderDefinition {
@@ -194,7 +192,7 @@ message PricerOrderDefinition {
CustomOrderDefinition child = 3;
}
message CompositeOrderDefinition {
uint32 algo_template_key = 1;
string name = 1;
CustomOrderDefinition definition = 2;
}
message DynamicOrderDefinition {
+1 -1
View File
@@ -68,7 +68,7 @@ message LadderKnobs {
optional uint32 max_open_ladders = 4 [default = 75];
optional uint32 security_timeout_secs = 5 [default = 60];
optional bool open_algo_popup_on_select = 6 [default = false];
optional bool use_algo_param_grid = 7 [default = true];
optional bool use_algo_param_grid = 7 [default = false];
}
message ShellPingOptions {
+6 -7
View File
@@ -61,8 +61,13 @@ inline Price improve_price(api::Side side, Price p, Price offset) {
return Price(0);
}
inline Price worsen_price(api::Side side, Price p,
double tick_size,uint32_t offset_ticks) {
return improve_price(side, p, Price(tick_size*offset_ticks));
}
inline Price worsen_price(api::Side side, Price p, Price offset) {
return improve_price(other_side(side), p, offset);
return improve_price(other_side(side), p, offset);
}
inline bool is_same(Price p1, Price p2) {
@@ -73,12 +78,6 @@ 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());
}
+24 -25
View File
@@ -3,7 +3,6 @@
#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"
@@ -17,24 +16,22 @@ struct CompositeOrder::PImpl {
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) {
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();
*child_def.mutable_custom_def() = def.custom_def();
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 &) {
const PreActivationOrderServices &) {
me->state = rec.state();
// Infer internal status from persisted external status
@@ -64,25 +61,24 @@ void CompositeOrder::on_init_recovered(OrderRecord const &rec,
}
OrderOpResult CompositeOrder::on_activate(Price p, Quantity q,
OrderServices &services) {
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;
return {};
// Terminal states
case ORDER_STATUS_ERROR:
case ORDER_STATUS_REJECTED_BY_SPARK:
case ORDER_STATUS_COMPLETED:
case ORDER_STATUS_CANCELED:
break;
return {};
// It should not be possible to reach these
case ORDER_STATUS_DISCONNECTED:
@@ -91,20 +87,21 @@ OrderOpResult CompositeOrder::on_activate(Price p, Quantity q,
case OrderStatus_INT_MIN_SENTINEL_DO_NOT_USE_:
case OrderStatus_INT_MAX_SENTINEL_DO_NOT_USE_:
bts_assert(false);
break;
return {};
}
services.report_state(me->state);
bts_assert(false);
return {};
}
OrderOpResult CompositeOrder::on_update(Price p, Quantity q) {
if (!me->child_order.empty())
if (is_working())
me->child_order.update(p, q);
return {};
}
OrderOpResult CompositeOrder::on_update(api::orderman::Update const &u) {
if (!me->child_order.empty()) {
if (is_working()) {
Update child_update;
child_update.set_price(u.price());
child_update.set_quantity(u.quantity());
@@ -113,28 +110,23 @@ OrderOpResult CompositeOrder::on_update(api::orderman::Update const &u) {
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);
*child_update.mutable_custom()
->mutable_composite()
->mutable_definition() = cupdate;
}
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);
}
if (is_working())
me->child_order.detach();
return {};
}
OrderOpResult CompositeOrder::on_cancel() {
if (!me->child_order.empty())
if (is_working())
me->child_order.cancel();
return {};
}
@@ -144,6 +136,13 @@ void CompositeOrder::on_child_order_update(
me->services->report_state(st);
}
bool CompositeOrder::is_working() const {
return
me->state.status() == ORDER_STATUS_WORKING ||
me->state.status() == ORDER_STATUS_PENDING_WORKING ||
me->state.status() == ORDER_STATUS_DISCONNECTED ;
}
void CompositeOrder::on_attached(api::orderman::OrderDefinition const &) {}
} // namespace orderman
+1
View File
@@ -25,6 +25,7 @@ class CompositeOrder : public Order {
struct PImpl;
std::unique_ptr<PImpl> me;
void on_child_order_update(OrderKey, api::orderman::OrderState const &);
bool is_working() const;
};
} // namespace orderman
} // namespace bts
@@ -458,21 +458,10 @@ void AlgoWrapperOrder::detach_child(OrderKey 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,
@@ -494,14 +483,13 @@ void AlgoWrapperOrder::update_fill_state(Quantity q, Price p) {
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
@@ -510,10 +498,19 @@ void AlgoWrapperOrder::terminate_error(std::string const &msg) {
terminate(ORDER_STATUS_ERROR, msg);
}
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::complete() {
if (!is_working())
return;
ReportStateGuard _(*this);
terminate(ORDER_STATUS_COMPLETED);
}
@@ -39,7 +39,7 @@ OrderOpResult IcebergAlgo::do_before_launch(IBeforeLaunchAlgoServices &serv) {
return OrderOpResult{ORDER_ERROR_INVALID_ORDER_DEFINITON,
"Order must have either a child order definition "};
if (iceberg.show_quantity() <= 0)
if (iceberg.show_quantity() == 0)
return OrderOpResult{ORDER_ERROR_INVALID_ORDER_DEFINITON,
"Show quantity must be greater than 0"};
@@ -24,10 +24,8 @@ struct LeanAlgo::PImpl {
Price observed_price = Price(os::nan());
OrderKey child_key = null_order_key();
ChildTemplate *child_template = nullptr;
md::PriceSize last_opp_inside = md::PriceSize();
md::PriceSize last_opp_inside=md::PriceSize();
Book curr_book;
Price out_price = Price(os::nan());
Quantity out_qty = Quantity(0);
};
LeanAlgo::LeanAlgo() : me(new PImpl()) {}
@@ -40,7 +38,8 @@ 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());
bts_assert(def.custom_def().has_lean());
// validate that lean is properly formed
if (serv.is_attaching()) {
}
else {
@@ -54,7 +53,6 @@ OrderOpResult LeanAlgo::do_before_launch(IBeforeLaunchAlgoServices &serv) {
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:{}",
@@ -62,7 +60,7 @@ void LeanAlgo::do_launch(IAlgoServices& algo) {
algo.price(),algo.quantity());
algo.subscribe_book(SecurityKey(algo.definition().security_key()));
}
void LeanAlgo::do_launch_attached(IAlgoServices&algo, OrderKey k, ChildState st) {
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()));
@@ -85,7 +83,6 @@ void LeanAlgo::do_update(const api::orderman::Update &update) {
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:
@@ -170,19 +167,17 @@ 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) ||
return securities::is_better(_opp_side(),
price,
me->initial_observed_price) ||
static_cast<uint32_t>(std::abs(
securities::price_diff_to_ticks(price.value(),
me->initial_observed_price.value(),
me->tick_size))) <= _max_chase_ticks();
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));
Price LeanAlgo::_chase_limit() const{
return securities::worsen_price(_opp_side(),me->initial_observed_price,
me->tick_size,_max_chase_ticks());
}
LeanAlgo::MarketChange LeanAlgo::_market_change() const{
md::PriceSize opp_inside=_opp_inside_market();
@@ -203,14 +198,15 @@ void LeanAlgo::_analyze_and_act() {
me->last_opp_inside=_opp_inside_market();
switch(market_change){
case MarketChange::NO_MARKET:
_go_furthest_possible();
// go to the limit and park there
_try_cross();
break;
case MarketChange::SIZE_CHANGE:
_try_cross(me->observed_price);
_try_cross();
break;
case MarketChange::AWAY:
me->observed_price = Price(_opp_inside_market().price());
_go_furthest_possible();
_try_cross();
break;
case MarketChange::TOWARD:
_on_toward_me();
@@ -220,17 +216,16 @@ void LeanAlgo::_analyze_and_act() {
void LeanAlgo::_on_toward_me() {
switch (_on_toward_behaviour()) {
case LeanOrderDefinition_OnToward_CANCEL:
LOG(OrderMan, Info,
LOG(OrderMan, Diag,
"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,
LOG(OrderMan, Diag,
"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,
@@ -238,12 +233,12 @@ void LeanAlgo::_on_toward_me() {
"towards order",
algo().order_key().value(), _opp_inside_market().price());
me->observed_price = Price(_opp_inside_market().price());
_try_cross(me->observed_price);
_try_cross();
break;
case LeanOrderDefinition_OnToward_NO_CHANGE:
LOG(OrderMan, Diag, "LeanAlgo {} ignoring opposite move towards order",
LOG(OrderMan, Diag, "LeanAlgo {} ignoring opposite move towards order.",
algo().order_key().value());
_try_cross(me->observed_price);
_try_cross();
break;
default:
bts_assert(false);
@@ -254,63 +249,29 @@ void LeanAlgo::_on_toward_me() {
// 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)){
bool LeanAlgo::_try_cross() {
if(_within_chase_band(me->observed_price)){
Quantity level_qty, cumm_qty;
SpreaderUtils::find_qty_at_price_level(me->curr_book,
_opp_side(),
price,
me->observed_price,
me->tick_size,
level_qty,
cumm_qty);
Quantity trigger_quantity = _cross_threshold();
if(cumm_qty.value()<trigger_quantity.value()){
_modify_price_price_qty(price,algo().quantity());
if(cumm_qty.value()<trigger_quantity.value()){
Update child_update;
child_update.set_price(me->observed_price.value()),
child_update.set_quantity(algo().quantity().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;
}
void LeanAlgo::_go_furthest_possible(){
if(!_try_cross(me->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);
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
@@ -34,13 +34,10 @@ class LeanAlgo : public IAlgoOrder {
api::Side _opp_side() const;
bool _within_chase_band(Price price) const;
Price _chase_limit() const;
MarketChange _market_change() const;
MarketChange _market_change() const;
void _analyze_and_act();
bool _try_cross(Price);
void _go_furthest_possible();
bool _try_cross();
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<PImpl> me;
@@ -4,7 +4,7 @@
#include "lib/orderman/orders/queue_holder/QueueHolderOrderState.h"
namespace bts {
namespace trace {struct CorID;}
namespace trace {class CorID;}
namespace api {namespace orderman {class OrderDefinition;class OrderRecord;}}
namespace orderman {class PreActivationOrderServices; class OrderServices;}
namespace orderman {class OrderStateUpdateEvent;}
@@ -42,4 +42,4 @@ public:
// 8. time event called by the infrastructure
virtual void on_time(const TimeStamp&) = 0;
};
}}
}}
+16 -16
View File
@@ -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,10 +67,10 @@ $ cd spark_sdk
### Development
Algo Orders typically implement the IAlgoOrder interface to respond to events and use the IAlgoServices 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/md_publisher_example.cpp](examples/md_publisher_example.cpp) to look at how to build a custom market data producer
Look at [examples/order_plugin_example.cpp](examples/order_plugin_example.cpp) to look at how to create custom algos.
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:
Regular → Executable
View File
File mode changed.
@@ -6,25 +6,25 @@
#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/orderman/orderman_utils/fix_order_codec.h"
#include "lib/persistence/SqliteStore.h"
#include "lib/md/MBOProcessor.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 <boost/date_time/posix_time/posix_time.hpp>
#include <fmt/format.h>
#include <mutex>
#include <quickfix/fix42/ExecutionReport.h>
#include <quickfix/fix42/OrderCancelReject.h>
#include <quickfix/fix42/OrderCancelReplaceRequest.h>
#include <quickfix/fix42/OrderCancelReject.h>
#include <sstream>
@@ -101,17 +101,19 @@ 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<config::ExchangeSim>().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,11 +126,10 @@ struct ExchangeSimApplication::PImpl {
bool do_merge_with_md;
std::unique_ptr<persistence::IStore> 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"];
@@ -203,8 +204,7 @@ 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];
@@ -252,19 +252,18 @@ void ExchangeSimApplication::onMessage(const FIX42::NewOrderSingle &message,
*order.mutable_create_time() = utils::pb::pb_now();
*order.mutable_last_update_time() = utils::pb::pb_now();
send_execution_report(order, FIX::OrdStatus_NEW);
updateOrder(order, FIX::OrdStatus_NEW);
std::vector<Order> 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);
send_execution_report(order_cpy, FIX::OrdStatus_CANCELED);
updateOrder(order_cpy, FIX::OrdStatus_CANCELED);
matcher.cancel(clOrdID);
}
update_md(sec_desc);
} catch (std::exception &e) {
rejectOrder(senderCompID, senderSubID, targetCompID, clOrdID, sec_desc,
@@ -304,23 +303,16 @@ void ExchangeSimApplication::onMessage(
clOrdID);
throw std::logic_error("Unknown order");
} else {
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);
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);
std::vector<Order> updates;
matcher.update(clOrdID, Price(price), Quantity(orderQty), &updates);
for (auto const &o : updates)
fillOrder(o);
}
std::vector<Order> updates;
matcher.update(clOrdID, Price(price), Quantity(orderQty), &updates);
for (auto const &o : updates)
fillOrder(o);
update_md(sec_desc);
}
} catch (std::exception &e) {
@@ -353,20 +345,19 @@ void ExchangeSimApplication::onMessage(const FIX42::OrderCancelRequest &message,
LOG(ExSim, Info, "Receive cancel for unknown order {}",
origClOrdID.getString());
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 &) {
}
LOG(ExSim, Info, "Rejected cancel for order {}", origClOrdID.getString());
} catch (FIX::SessionNotFound &) {}
} else {
auto order_cpy = *order;
order_cpy.set_open_quantity(0);
send_execution_report(order_cpy, FIX::OrdStatus_CANCELED);
updateOrder(order_cpy, FIX::OrdStatus_CANCELED);
matcher.cancel(origClOrdID);
update_md(sec_desc);
}
@@ -375,16 +366,16 @@ void ExchangeSimApplication::onMessage(const FIX42::OrderCancelRequest &message,
}
void ExchangeSimApplication::rejectOrder(const Order &order) {
send_execution_report(order, FIX::OrdStatus_REJECTED);
updateOrder(order, FIX::OrdStatus_REJECTED);
}
void ExchangeSimApplication::fillOrder(const Order &order) {
send_execution_report(order, order.open_quantity() == 0
? FIX::OrdStatus_FILLED
: FIX::OrdStatus_PARTIALLY_FILLED);
updateOrder(order, order.open_quantity() == 0
? FIX::OrdStatus_FILLED
: FIX::OrdStatus_PARTIALLY_FILLED);
}
void ExchangeSimApplication::send_execution_report(const Order &order, char status) {
void ExchangeSimApplication::updateOrder(const Order &order, char status) {
FIX::TargetCompID targetCompID(order.owner());
FIX::SenderCompID senderCompID(order.target());
FIX::TargetSubID(order.sender_sub_id());
@@ -490,8 +481,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;
@@ -512,19 +503,17 @@ void ExchangeSimApplication::update_md(std::string const &sec_desc) {
return md::PriceSize_from_double<precision>(
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<ex_sim::precision>(
t.price.value() * price_factor, t.quantity.value()),
md::PriceSize_from_double<ex_sim::precision>(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
@@ -533,16 +522,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<precision>(order.price() *
price_factor),
(int)order.open_quantity()};
md::SnapshotOrder sno {
md::ExchangeOrderKey(std::atoll(ek.getString().c_str())),
md::IntPrice_from_double<precision>(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);
}
}
@@ -592,18 +581,16 @@ 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()) {
@@ -612,7 +599,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()) {
@@ -621,7 +608,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()) {
@@ -630,8 +617,7 @@ 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()) {
@@ -641,19 +627,20 @@ void ExchangeSimApplication::on_close(md::Security const &sec,
}
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<md::PriceSize, md::COCONUT_MAX_IMPLIED_DEPTH> *implied_bids,
std::array<md::PriceSize, md::COCONUT_MAX_IMPLIED_DEPTH> *implied_asks) {
std::array<md::PriceSize, md::COCONUT_MAX_IMPLIED_DEPTH>* implied_bids,
std::array<md::PriceSize, md::COCONUT_MAX_IMPLIED_DEPTH>* implied_asks) {
std::lock_guard<std::mutex> 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());
@@ -677,14 +664,13 @@ 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);
}
}
}
@@ -696,9 +682,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 {}. {} {} {}@{}",
@@ -80,7 +80,7 @@ private:
// Order functionality
void processOrder( const Order& );
// void processCancel( const std::string& id, const std::string& symbol, Order::Side );
void send_execution_report( const Order&, char status );
void updateOrder( const Order&, char status );
void rejectOrder( const Order& order );
// void acceptOrder( const Order& order );
void fillOrder( const Order& order );
@@ -109,8 +109,7 @@ void OrderMatcher::update(std::string const &clordid, Price price, Quantity qty,
if (order_cpy.quantity() != qty.value()) {
order_cpy.set_quantity(qty.value());
bts_assert(qty.value() > order_cpy.executed_quantity());
order_cpy.set_open_quantity(qty.value()-order_cpy.executed_quantity());
order_cpy.set_open_quantity(qty.value());
}
if (order->side() == api::SIDE_BUY) {
+1 -1
View File
@@ -1 +1 @@
set(sources ../../externals/linux/include/google/protobuf/descriptor.proto;../../externals/linux/include/google/protobuf/timestamp.proto;../lib/api/apicore.proto;../lib/api/apigateway.proto;../lib/api/apioptions.proto;../lib/api/services/AdminService.proto;../lib/api/services/AlgoDefinitionService.proto;../lib/api/services/AlgoService.proto;../lib/api/services/ApiUnitTestService.proto;../lib/api/services/AuthService.proto;../lib/api/services/ErrorReportService.proto;../lib/api/services/HelloService.proto;../lib/api/services/MBOService.proto;../lib/api/services/MarketDataAuxiliaryService.proto;../lib/api/services/MarketDataRelay.proto;../lib/api/services/OrderService.proto;../lib/api/services/OutOfProcessURLListener.proto;../lib/api/services/PersistenceService.proto;../lib/api/services/PositionService.proto;../lib/api/services/ShellDiagnosticService.proto;../lib/api/services/ShellLatencyService.proto;../lib/api/services/SyntheticSecurityService.proto;../lib/domain_model/Security.proto;../lib/md/protos/co2.proto;../lib/sparkproto/SparkProtos.proto;api/build.sh;api/node_modules/exit/test/fixtures/create-files.sh;api/node_modules/protobufjs/cli/node_modules/acorn-jsx/node_modules/acorn/bin/update_authors.sh;api/node_modules/watch/release.sh;api/quiet_build.sh;api/src/DynamicService.ts;api/src/ServiceContext.ts;api/src/bts_assert.ts;ui/src/Access.fs;ui/src/Accounts/ClipLimits.fs;ui/src/Accounts/ProductLimits.fs;ui/src/Accounts/SecurityLimits.fs;ui/src/Accounts/State.fs;ui/src/Accounts/Types.fs;ui/src/Accounts/View.fs;ui/src/App.fs;ui/src/Cmd.fs;ui/src/Controls/Button.fs;ui/src/Controls/DataGrid.fs;ui/src/Controls/Fields.fs;ui/src/Controls/Modal.fs;ui/src/Controls/ReactGrid.fs;ui/src/Controls/Table.fs;ui/src/Controls/nbsp.fs;ui/src/Global.fs;ui/src/Imports.fs;ui/src/Lens.fs;ui/src/Login/Login.fs;ui/src/Nav.fs;ui/src/State.fs;ui/src/Types.fs;ui/src/Users/State.fs;ui/src/Users/Types.fs;ui/src/Users/View.fs;ui/src/Util/EnumUtils.fs;ui/src/Util/JSMap.fs;ui/src/obj/Debug/netstandard2.0/ui.AssemblyInfo.fs)
set(sources ../../externals/linux/include/google/protobuf/descriptor.proto;../../externals/linux/include/google/protobuf/timestamp.proto;../lib/api/apicore.proto;../lib/api/apigateway.proto;../lib/api/apioptions.proto;../lib/api/services/AdminService.proto;../lib/api/services/AlgoDefinitionService.proto;../lib/api/services/AlgoService.proto;../lib/api/services/ApiUnitTestService.proto;../lib/api/services/AuthService.proto;../lib/api/services/ErrorReportService.proto;../lib/api/services/HelloService.proto;../lib/api/services/MBOService.proto;../lib/api/services/MarketDataAuxiliaryService.proto;../lib/api/services/MarketDataRelay.proto;../lib/api/services/OrderService.proto;../lib/api/services/OutOfProcessURLListener.proto;../lib/api/services/PersistenceService.proto;../lib/api/services/PositionService.proto;../lib/api/services/ShellDiagnosticService.proto;../lib/api/services/ShellLatencyService.proto;../lib/api/services/SyntheticSecurityService.proto;../lib/domain_model/Security.proto;../lib/md/protos/co2.proto;../lib/sparkproto/SparkProtos.proto;api/build.sh;api/node_modules/cssstyle/scripts/run_tests.sh;api/node_modules/exit/test/fixtures/create-files.sh;api/node_modules/protobufjs/cli/node_modules/acorn-jsx/node_modules/acorn/bin/update_authors.sh;api/node_modules/watch/release.sh;api/quiet_build.sh;api/src/DynamicService.ts;api/src/ServiceContext.ts;api/src/bts_assert.ts;ui/src/Access.fs;ui/src/Accounts/ClipLimits.fs;ui/src/Accounts/ProductLimits.fs;ui/src/Accounts/SecurityLimits.fs;ui/src/Accounts/State.fs;ui/src/Accounts/Types.fs;ui/src/Accounts/View.fs;ui/src/App.fs;ui/src/Cmd.fs;ui/src/Controls/Button.fs;ui/src/Controls/DataGrid.fs;ui/src/Controls/Fields.fs;ui/src/Controls/Modal.fs;ui/src/Controls/ReactGrid.fs;ui/src/Controls/Table.fs;ui/src/Controls/nbsp.fs;ui/src/Global.fs;ui/src/Imports.fs;ui/src/Lens.fs;ui/src/Login/Login.fs;ui/src/Nav.fs;ui/src/State.fs;ui/src/Types.fs;ui/src/Users/State.fs;ui/src/Users/Types.fs;ui/src/Users/View.fs;ui/src/Util/EnumUtils.fs;ui/src/Util/JSMap.fs;ui/src/obj/Debug/netstandard2.0/ui.AssemblyInfo.fs)
-16
View File
@@ -1,16 +0,0 @@
This test verifies that all required market data is present for users:
Use a production instance.
0. Go to the admin tool for the instance you are testing with, login as bts with the normal password.
1. make sure that all market data permissions you are testing have a check in the checkbox for the user "admin"
2. login to the front end with the user admin (password is adminadmin)
3. go to market view and choose a variety of both futures and spread products (only exchange listed products, no need to launch synthtetic, i.e. products in BTS exchange)
4. Verify you see market data for the products you chose in a market view.
5. Close out the front end, and go back to the admin tool and un-check all the market data permissions for the user "admin", click save.
@@ -1,47 +0,0 @@
Algo Studio lets you combine algos together and save it as an order type:
To test this, we will create a common algo combination and test to make sure it's working as desired.
Let's start by creating the Algo:
Launch Algo Studio
Click on top right icon to "add algo"
Give it a name, call it T_C and give the abbrev a title of T_C as well.
Create a Top with Cover, so the very top algos with be a "top" (top thresh 10) and it's child will be a cover (Hedge Ticks 2)
Leave both Hedge and Child as limits of the child
Use a very liquid market with recorded data to test, I suggest something like ES or CL.
On the ladder, go to settings, then algo favorites and click add and choose your T_C algo.
This will display it on the ladder for quick deployment
click on algo, then enter an order on the best bid
wait until it fills, once fills, it should submit the cover order 2 ticks above the price you got filled at.
try this with a sell order following the same procedure.
Additionally, we will add a "lean" into the mix as the child of the cover.
go back to your algo studio, and change the hedge of the cover to be that of lean.
What will happen is once the cover order is submitted, it will include the lean logic on that cover order. Meaning, it'll lean into the market and cross once the cross thresh is reach.
Set the parameters to a cross thresh of 10, max chase ticks 0 and on toward no change
save the algo, and send an order and wait for it to be filled.
Once filled, it will remain working until the market flips, which means it ticks up a level. Once it flips and there is 1 remaining, the order should cross.
+2 -2
View File
@@ -19,7 +19,7 @@ that the Parents Key show up correctly.
5. Verify that the lean parameters are what we attached them as
6. Now filter orders in the OB for limit, and detach from these orders entered in 2.
6. Now filter orders in the OB for limit, and detach from these orders entered in 2.
All the leans should go away and the limit orders should appear by themselves.
7. Repeat 3, but for Cross Threshold enter 1000. This should immediately fill the leans
7. Repeat 3, but for Cross Threshold enter 1000. This should immediatly fill the leans
+12 -7
View File
@@ -1,22 +1,27 @@
Detaching can be best illustrated by this example : if we have Join->Cover->Limit, we can detach Cover which means
Detaching can be best illustrated by this example : if we have Join->Cover->Limit, we can detach Cover which means
Cover->Limit will now exist on its own. If we detach the Limit, the Limit will exist on its own. The tree
is broken at the detachment point and a new root is created.
0. This needs sim market data **not** to be merged with replay (or cert), so we can create our own markets.
Also make sure you have limits to trade SI Future
1. Bring up a ladder, lets say in SIN1 (does not matter which security). Create an ask side market of 100 at 20.055.
1. Bring up a ladder, lets say in SIN1 (does not matter which security). Create an ask side market
of 100 at 20.055.
2. In the algo studio create a Join->Cover->(Hedge=Limit,Child=Limit). Default parameters will suffice. Call it JC1.
2. In the algo studio create a Join->Cover->(Hedge=Limit,Child=Limit). Default parameters will suffice. Call
its JC1.
3. In your ladder, Settings->Algo Favorites, add a favorite button for JC1.
4. From 20.025 down, enter 5 10 lot buy orders for JC1. You should see JC1 named badges pop up in the ladder.
4. From 20.025 down, enter 5 10 lot buy orders for JC1. You should see JC1 named badges pop up in the ladder.
5. In your Orderbook, go to settings and enable "Show Full Algo Tree". Check one of these orders and it should be displayed as JC1->Join->Cover->Limit.
5. In your Orderbook, go to setting and enable "Show Full Algo Tree". Check one of these orders and it should
be displayed as JC1->Join->Cover->Limit.
6. Now mass detach them at the Cover level. This should leave the trees as Cover->Limit. Make sure the orderbook, miniOB and ladders reflect it correctly.
6. Now mass detach them at the Cover level. This should leave the trees as Cover->Limit. Make sure the orderbook,
miniOB and ladders reflect it correctly.
7. Cancel all these orders and renter them (as in 4).
8. Now repeat 6 but instead detach them at the Limit order level. All this leaves are the Limit orders. Make sure the orderbook, miniOB and ladders reflect it correctly.
8. Now repeat 6 but instead detach them at the Limit order level. All what this leaves are the Limit orders.
Make sure the orderbook, miniOB and ladders reflect it correctly.
@@ -1,47 +0,0 @@
Algo Studio lets you combine algos together and save it as an order type:
To test this, we will create a common algo combination and test to make sure it's working as desired.
Let's start by creating the Algo:
Launch Algo Studio
Click on top right icon to "add algo"
Give it a name, call it Joiner and give the abbrev a title of Joiner as well.
Create a Joiner, the very top algos with be a "Join" (Join Thresh 10) and it's child will be a cover (Hedge Ticks 3)
Leave both Hedge and Child as limits of the child
Use a very liquid market with recorded data to test, I suggest something like ES or CL.
On the ladder, go to settings, then algo favorites and click add and choose your Joiner algo.
This will display it on the ladder for quick deployment
click on algo, then enter an order on the best bid
wait until it fills, once fills, it should submit the cover order 3 ticks above the price you got filled at.
try this with a sell order following the same procedure.
Additionally, we will add a "lean" into the mix as the child of the cover.
go back to your algo studio, and change the hedge of the cover to be that of lean.
What will happen is once the cover order is submitted, it will include the lean logic on that cover order. Meaning, it'll lean into the market and cross once the cross thresh is reach.
Set the parameters to a cross thresh of 10, max chase ticks 0 and on toward no change
save the algo, and send an order and wait for it to be filled.
Once filled, it will remain working until the market flips, which means it ticks up a level. Once it flips and there is 1 remaining, the order should cross.
+6 -6
View File
@@ -17,22 +17,22 @@ On Toward=No Change
4. Move the ask side market to 20.045 now. Leans should continue to work as is.
5. Select all the lean orders and change the Trade Toward Behavior to Cancel (don't commit yet).
5. Select all the lean orders and change the Trade Toward Behaviour to Cancel (dont commit yet).
As the parameter is changed its name should turn Green along with a *. Revert back and it should go to
No Change. Select a few of the leans and make sure Trade Toward Behavior is No Change. Now Change it
No Change. Select a few of the leans and make sure Trade Toward Behaviour is No Change. Now Change it
to Cancel and commit. Make sure it is set to Cancel for all the lean orders.
6. Move the ask book to 20.040. This should cancel all the leans (verifies the change
6. Move the ask book to 20.040. This should cancel all the leans (verifies the change
in 5 made through). Move the market back to 20.050
7. Enter 2 leans, 4 and 6 lots (configured like 3) at 20.025 and 20.020 respectively. In the orderbook
select both and make sure the Price and Size show as - (since they are different). Change the Trade Toward
Behavior on both to Cancel and make sure that goes through (you can validate that by viewing
Behaviour on both to Cancel and make sure that goes through (you can validate that by viewing
the parameters from the ladder ->miniOB -> update)
8. Now change the 20.020 lean's Trade Toward to Detach. Now select both and Trade Toward should
8. Now change the 20.020 lean's Trade Toward to Detach. Now select both and Trade Toward should
show as -.
9. Now we will generalize 7 and 8. The idea is to make the parameters different bw the 2 orders,
make sure they appear as - when both are selected. Also verify that when you mass update a parameter, the
make sure they appear as - when both are selected. Also verify that when you mass update a parameter, the
rest of them should continue with their current value.
+10 -20
View File
@@ -1,23 +1,11 @@
Test Author: Taha
If it breaks: Pedro
Cover order has 2 "child orders" - the main child order and a hedge order. Everytime the main child order
gets filled, it sends out a hedge order, "Hedge Ticks" away from the fill.
0. This needs sim market data **not** to be merged with replay (or
cert), so we can create our own markets. Use the following key to set
market data up:
ExchangeSim {
value {
merge_with_md: false
forward_implied: false
}
}
0. This needs sim market data **not** to be merged with replay (or cert), so we can create our own markets.
1. Bring up a ladder, lets say in SIN1 (does not matter which security)
2. Create the ask sides of the market by entering 50 lot sell limit order at 15.50
2. Create the ask sides of the market by entering 100 lot limit order at 15.500
(if there are no markets use the M View and the ticket to enter)
3. Enter a 10 lot Cover (Child=Limit, Hedge=Limit) buy at 15.450, with hedge Ticks=3.
@@ -32,22 +20,24 @@ Make sure a hedge is sent 3 ticks away from the fill (the hedge badge should sho
7. Repeat Step 5 and verify the hedge is sent 5 ticks away now.
8. Enter another 10 lot Cover order. Repeat step 5. until it is completely filled. Make sure it
8. Repeat Step 5 for a negative value and make sure it works (something interesting will happen!)
9. Enter another 10 lot Cover order. Repeat step 5. until it is completely filled. Make sure it
clearly gets marked as completed
9. Now that you know how Cover works, quickly test for the Sell case by repeating 1-5 for a sell cover order
10. Now that you know how Cover works, quickly test for the Sell case.
10. Clean the slate (except for the market). Enter a 10 lot buy Limit order. Attach a Cover
11. Clean the slate (except for the market). Enter a 10 lot buy Limit order. Attach a Cover
to it (with the same parameters from 3). Make sure this cover (the one "created" by attaching)
behaves in the same correct way as the one that was launched in 3 - ie get some fills, make
sure the hedges are fired correctly, make sure updates to Hedge Ticks reflect the
next hedges etc.
11. Repeat 11 but instead attach to a partially filled Limit order. Make sure the Cover does not
12. Repeat 11 but instead attach to a partially filled Limit order. Make sure the Cover does not
immediatly fire off hedges for fills happened before the attachment time. Verify it works correctly,
just like a Cover attached to a non partially filled order (as in 11)
12. Boundary cases
11. Boundary cases
Enter a cover order away from the market. Cancel its child order and Cover should be cancelled too.
Mess in any way with the ChildOrder and make sure the parent does the right thing (ex: fill
the Child, partially fill the Child, Change the qty of the Child and then fill it etc)
the Child, partially fill the Child, Change the qty of the Child and then fill it etc)
+29
View File
@@ -0,0 +1,29 @@
- Open up a ladder for a liquid future
- Make sure you have limits to trade this future
- Select Join order from the menu
Label 1) Set join thresh to absolute 10
The goal of the join order is to watch the opposite-inside market and join when the market *flips and
has at least threshold size
*flip is when the best offer becomes the best bid, or the market trades away from you (the line moves up in the gui)
Label 3) Put an order in to way down in the bid side of the book
- Watch the opposite inside market, if it flips make sure the order moves itself to join the new best bid (former offer)
Goto Label l and test the ratio threshold
{
- Use a threshold of at least 1.0
}
Goto Label 3 and try a sell order
{
}
Now do this test again but use a Cover of Join (that's a Cover order with a Join Child and a Limit Hedge, HedgeTicks = 1)
This should modify the behavior such that the algorithm will send a limit order on the opposite
side of the market, one tick away from fill price in a quantity equivalent to the amount of the fill
+4 -23
View File
@@ -1,8 +1,5 @@
Test Author: Taha
If it breaks: Pedro
The goal of the join order is to watch the opposite-inside market and join when the market flips and
has at least threshold size. (flip is when the best offer price becomes the best bid, or the market trades
has at least threshold size. (flip is when the best offer becomes the best bid, or the market trades
away from you (the line moves up in the gui))
0. This needs sim market data **not** to be merged with replay (or cert), so we can create our own markets.
@@ -24,24 +21,8 @@ moved its Child limit order to 15.575 ie it joins the bid market.
6. Cancel all orders and put the market to where it was (step 2.)
7. Now an enter a Join order with threshold 15, again at
15.525. Repeat step 5. except that the Join order will not join since
the top of the bid qty threshold of 15 is not met.
7. Now an enter a Join order with threshold 15. Repeat step 5. except that the Join order will not join
since the top of the bid qty threshold of 15 is not met.
8. Increase the top of the bid qty by adding a limit order there at a time. When the qty
8. Increase the top of the bid qty by adding on1 limit order there at a time. When the qty
reaches 15 it should join.
Updates:
9. Clean the slate and repeat 2. Enter 10 5 lot Join orders at 15.525, with threshold 1000. Once again move the ask one level up (15.580)
and the bid to where the ask was (15.575). The join child orders should stay where they were. Select 7 join orders in the OB, and change
their threshold to 10. These should force their child orders to join the market. The other 3 should be at the same place. For the other
change their threshold from the miniOB to 10, and they should jump too (these algos will be the only ones with chidl orders in the miniOB)
Attach:
10. Clean the slate and repeat 2. Enter 15 5 lot limit orders, between 15.525 and 15.500. Select them in the OB and attach a join with threshold of 10. Verify
that all these limit orders are now controlled by Joins. Now like 9, move the ask one level up, and the bid to where the ask was. All the joins should
jump and join the bid.
Detach:
11. Select these limit orders from the OB and hit detach. They should all be detached from the parent lean now.
+29
View File
@@ -0,0 +1,29 @@
- Open up a ladder for a liquid future
- Make sure you have limits to trade this future
- Select Lean order from the menu
Label 1) Set cross thresh to absolute 10
The goal of the lean order is to watch the opposite-inside market size and *cross when that size goes below the threshold
(this also implies a cross if that size goes to zero and the market trades away from you)
*cross means take an order working on the bid and 'cross' by buying into the asks. This is also called 'paying up'
- Open up order book and fills
- Make sure OnToward behavior is set to No Change (not Cancel)
Label 2) Put an order in to Join the best bid
- Watch the opposite inside market, if it dips below the threshold (or trades away from you) make sure the order moves itself to cross
- Verify that the order filled at the offer price
- If the opposite inside market does not dip below threshhold, you should expect to be eventually filled at the bid price
- Verify that these fills come in at the proper price, crosses at the offer, working fills at the bid
Goto Label 2 and join the ask instead of the bid
{
}
Goto Label l and test the ratio threshold
{
- Use a threshold of at least 1.0
- Test with a larger order (say 100) to trigger crosses more quickly and across different price levels
}
+3 -15
View File
@@ -1,25 +1,13 @@
Test Author: Taha
If it breaks: Taha
When the lean order is placed, it takes a snapshot of the opposite inside market. If the quantity
at that level falls below the "Cross Threshold" it crosses into it.
(cross means take an order working on the bid and 'cross' by buying into the asks. This is also called 'paying up')
0. This needs sim market data **not** to be merged with replay (or
cert), so we can create our own markets. Use the following key to set
market data up:
ExchangeSim {
value {
merge_with_md: false
forward_implied: false
}
}
0. This needs sim market data **not** to be merged with replay (or cert), so we can create our own markets.
Also make sure you have limits to trade SI Future
1. Bring up a ladder, lets say in SIN1 (does not matter which security)
2. Create the ask side of the market by sending a 10 lot sell limit order at 20.050
2. Create the ask side of the market by sending a 10 lot limit order at 20.050
(if there are no markets use the M View and the ticket to enter, if you already had left over
orders cancel them)
+8 -23
View File
@@ -13,41 +13,26 @@ Also make sure you have limits to trade SI Future
(if there are no markets use the M View and the ticket to enter)
3. Enter a Buy top order with threshold of 15 right at the top of the book. This should immediately
cancel. Now do the same with a threshold <= 10 and it should not cancel. Cancel this top order.
cancel. Now do the same with a threshold < 10 and it should not cancel. Cancel this top order.
4. Enter a Buy top order with threshold of 15 away from the market. Verify that an exchange order
is sent. Now move the top of the market toward the Top order so that the Top order eventually
is at the Top of the market. This should cancel the Top order. Repeat the same with a threshold of <= 10
4. Enter a Buy top order with threshold of 15 way from the market. Verify that an exchange order
is sent. Now move the top of the market toward the Top order, so that the Top order eventually
is at the Top of the market. This should cancel the Top order. Repeat the same with a threshold of < 10
and it should not cancel. Cancel the top order.
5. Enter a Buy top order with a threshold of 5 at the top of the market. Now start reducing the
top of market (remember its your limit order that is creating the market). When the size of the market
(net of the Top order) becomes < 5, the Top order should cancel.
6. You know enough about the Top order now. Do some basic sanity checks for Sells too.
6. You know enough about the Top order now. Make sure it works for Sells too.
7. Updates:
Clear the slate and repeat 2. Enter a buy top order away from the market
Create the 10 aside market condition from 2 again. Enter a buy top order away from the market
with a threshold of 15. Now if this is brought to the top it should cancel (like in 4.). However
we will go to OrderBook, select the order and change its threshold to 1. Now bring the Top order
to the top of the market and it should not cancel. Cancel it manually
7.1 Mass Updates:
Clear the slate and repeat 2. Enter 10 top buy orders at the top of the book
with threshold 10. Verify that they show in the orderbook. Select them all and change their threshold
to 500. All of them should cancel.
8. Attach:
Clear the slate and repeat 2. Enter another 5 lot buy limit order at the top of the book. Bring the miniOB
from where these 2 orders are working and attach a Top to the 5 lot with a threshold of 100. This 5 lot
should immediatly cancel.
8.1 Mass Attach:
Clear the slate and repeat 2. Enter 10 5 lot buy limit order at the top of the book. Select them in the OB
and mass attach a Top with threshold 10. Verify that the Tops are working with the 10 5 lots as their child
orders. Now select the tops and change their threshold to 1000. Make sure all are cancelled.
9. Boundary cases
8. Boundary cases
Enter a top order away from the market. Cancel its child order and the Top order should be cancelled too.
Mess in any way with the ChildOrder and make sure the parent TopOrder does the right thing (ex: fill
the Child, partially fill the Child, Change the qty of the Child and then fill it etc).
the Child, partially fill the Child, Change the qty of the Child and then fill it etc)
+1 -3
View File
@@ -7,10 +7,8 @@ ExchangeSim {
value {merge_with_md:false}
}
clear your fills database and sim fix (to prevent recent orders/fills from sim being resurrected):
clear your fills database:
rm ~/sparkdata/data/databases/fills/*
rm -rf /home/bts/sparkdata/data/jetfix/sim
rm -rf /home/bts/sparkdata/data/exchange_sim
and you may also want to clear your orders for a clean slate:
rm ~/sparkdata/data/databases/orders/*
@@ -12,5 +12,5 @@ select the drop down to Size (ie absolute size vs a ratio) and set Payless ticks
3. Send a buy order at -0.20. Verify that the hedger order is sent 15 ticks away from the hedging price
(since it is a buy order, it should be 15 ticks lower than the hedging price level).
This will result in the hedging order being worked on the bid side. Cancel the spreader order (and
verify that the hedge order keeps working)
This will result in the hedging order being worked on the bid side. Cancel the spreader order (andverify that the
hedge order keeps working)