diff --git a/doc/user/content/release_notes/_index.md b/doc/user/content/release_notes/_index.md index 568a5a8a8..21d5272ed 100644 --- a/doc/user/content/release_notes/_index.md +++ b/doc/user/content/release_notes/_index.md @@ -15,7 +15,9 @@ insert_anchor_links = "right" - Added feedback to the ladder when the user attempts to middle click on bid/ask columns using an order that does not have parameters - Fixed display of algo studio algo types in order book - Hid net change setting in synthetic ladders - + - Fixed a number of problems with filtering on the Fills form + - On the Lean algo, OnToward and Away are now calculated with respect to the opposite inside market at time of the order launch + - Iceberg Spreaders with queue holders are not erroneously cancelled after the first fill ## 2.1.4 ### User Visible Changes - Fixed handling of cancel button in security picker diff --git a/src/client/spark/Modules/Market/MarketView/MarketViewWindow.cs b/src/client/spark/Modules/Market/MarketView/MarketViewWindow.cs index 0363f1db0..10d875227 100644 --- a/src/client/spark/Modules/Market/MarketView/MarketViewWindow.cs +++ b/src/client/spark/Modules/Market/MarketView/MarketViewWindow.cs @@ -1,6 +1,7 @@ using bts; using bts.api; using bts.shell; +using bts.shell.fills; using bts.spark; using bts.utils; using mbts.persist; @@ -117,8 +118,8 @@ namespace mbts.spark { // show fills var show_fills_cmd = new DelegateCommand(() => { var sc = _selected_security_criteria; - _bus.post(SparkTags.ShowFillsTag, new FillsWindowFactory.StartupData( - new FillsWindowFactory.FilterStates { + _bus.post(SparkTags.ShowFillsTag, new FillsSettings( + new FillsFilterStates { security = sc.is_defined() ? sc : _state.security_criteria })); }); diff --git a/src/client/spark/Modules/Market/TimeAndSales/TimeAndSalesWindow.cs b/src/client/spark/Modules/Market/TimeAndSales/TimeAndSalesWindow.cs index 0f2f472cb..b075d16ef 100644 --- a/src/client/spark/Modules/Market/TimeAndSales/TimeAndSalesWindow.cs +++ b/src/client/spark/Modules/Market/TimeAndSales/TimeAndSalesWindow.cs @@ -1,6 +1,7 @@ using bts; using bts.api; using bts.shell; +using bts.shell.fills; using bts.spark; using mbts.co2; using mbts.persist; @@ -92,8 +93,8 @@ namespace mbts.spark { _initialize(); bool always_true(T _) => true; - FillsWindowFactory.StartupData get_fills_startup_data(IReadOnlyList secs) => - new FillsWindowFactory.StartupData(new FillsWindowFactory.FilterStates { + FillsSettings get_fills_startup_data(IReadOnlyList secs) => + new FillsSettings(new FillsFilterStates { security = secs.Count > 0 ? new SecurityCriteria(secs) : _state.security_criteria }); void update_criteria(SecurityCriteria c) { diff --git a/src/client/spark/Modules/Trading/Fills/FillsVM.cs b/src/client/spark/Modules/Trading/Fills/FillsVM.cs index ce4ed2b72..b4c64bf6a 100644 --- a/src/client/spark/Modules/Trading/Fills/FillsVM.cs +++ b/src/client/spark/Modules/Trading/Fills/FillsVM.cs @@ -2,6 +2,7 @@ using bts.api.core; using bts.api.orderman; using bts.collections; +using bts.shell.fills; using bts.spark; using bts.utils; using mbts.collections; @@ -18,7 +19,6 @@ using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Collections.Specialized; -using System.ComponentModel; using System.Linq; using System.Reactive.Disposables; using System.Reactive.Linq; @@ -34,21 +34,19 @@ using OrderType = bts.api.orderman.CustomOrderDefinition.CustomOneofCase; namespace mbts.spark { class FillsVM : DisposableViewModelBase, IHandleGridSorting { readonly OrdersModel _model; - readonly DIYGridSortManager _sort_manager; - readonly IDIYGridFiltersManager _filters_manager; + readonly DIYGridRowsManager _rows_manager; readonly ObservableKeyedCollection _columns = new ObservableKeyedCollection(_col_key); - List<(ColumnBase col, Columns key, ListSortDirection direction)> _active_comparers = new List<(ColumnBase col, Columns key, ListSortDirection direction)>(); IWindowSettingsManager _settings_manager; int _total_row_count; - public FillsVM(IBus bus, OrdersModel model, IObservable state_obs, IWindowSettingsManager settings_manager) + public FillsVM(IBus bus, OrdersModel model, IObservable state_obs, IWindowSettingsManager settings_manager) : this(bus, model, state_obs, _get_observable(bus, model, state_obs), settings_manager) { } - public FillsVM(IBus bus, OrdersModel model, IObservable state_obs, IObservable> fills_source, IWindowSettingsManager settings_manager) { + public FillsVM(IBus bus, OrdersModel model, IObservable state_obs, IObservable> fills_source, IWindowSettingsManager settings_manager) { _model = model; _settings_manager = settings_manager; /// Columns - var col_tups = new ObservableKeyedCollection, Columns>(c => c.key); + var col_tups = new ObservableKeyedCollection, Columns>(c => c.key); // security add_col(Columns.Security, DefaultColumnHeaders.Security, r => r.security.ToString(), DiscreteValuesFilterVM.Create( @@ -85,25 +83,15 @@ namespace mbts.spark { add_col(Columns.FillKey, DefaultColumnHeaders.FillKey, r => r.fill_key.ToString(), new RegexFilterVM(r => r.fill.FillKey), DataGridFilterKnownTemplates.Regex, DefaultColumnWidths.FillKey); add_col(Columns.OrderKey, DefaultColumnHeaders.OrderKey, r => r.order_key.ToString(), new RegexFilterVM(r => r.fill.OrderKey.ToString()), DataGridFilterKnownTemplates.Regex, DefaultColumnWidths.OrderKey); add_col(Columns.SecurityKey, DefaultColumnHeaders.SecurityKey, r => r.security_key.ToString(), new RegexFilterVM(r => r.fill.SecurityKey.ToString()), DataGridFilterKnownTemplates.Regex, DefaultColumnWidths.SecurityKey); - /// Rows - rows = new OperableCollection( - (ft, fk) => new Row(ft, model), - ft => ft.fill.FillKey, - new ComparerBuilder(new[] { - _get_column_comparer(Columns.FillTime), - _get_column_comparer(Columns.FillKey) - }).to_comparer()); - // row sort/filter managers - _sort_manager = new DIYGridSortManager(col_tups.WrapSelector(t => (t.col, t.key)), Columns.FillKey); - _filters_manager = DIYGridFiltersManager.create(col_tups); - var rows_manager = new DIYGridRowsManager(_filters_manager, _sort_manager, _get_column_comparer, FillsWindow.window_type_name); + // rows + _rows_manager = DIYGridRowsManager.create(FillsWindow.window_type_name, Columns.FillKey, col_tups, col_tups.WrapSelector(t => (t.col, t.key)), _get_column_comparer, fs => fs.build_predicate()); // grid settings grid_settings_manager = new SimpleGridSettingsManager(columns, new Dictionary { }, rows); // this will initialize the immutable properties that correspond to the col_settings_flags above (e.g. Bid/Ask font_color_override, etc.) if (_settings_manager != null) grid_settings_manager.load_from(_settings_manager.current_settings()); - var filter_src = Observable.FromEvent>, Func>(cb => rows_manager.filter_changed += cb, cb => rows_manager.filter_changed -= cb); - var comp_src = Observable.FromEvent>, IComparer>(cb => rows_manager.comparer_changed += cb, cb => rows_manager.comparer_changed -= cb); + var filter_src = Observable.FromEvent>, Func>(cb => _rows_manager.filter_changed += cb, cb => _rows_manager.filter_changed -= cb); + var comp_src = Observable.FromEvent>, IComparer>(cb => _rows_manager.comparer_changed += cb, cb => _rows_manager.comparer_changed -= cb); TableUpdate last_unfiltered_fills = TableUpdate.mk_empty(FillTuple.key_fn); var fills_buffer = Observable.Create>(o => { // this is what .Cache() does, but is a little cheaper, since we know subscriptions and callbacks occur on the same thread (i.e., on this Dispatcher). @@ -125,13 +113,13 @@ namespace mbts.spark { // Note: settings_manager in turn notifies grid_settings_manager of this update _settings_manager.instance_settings = s.grid; } - var fs = s.filters ?? new FilterStates { + var fs = s.filters ?? new FillsFilterStates { fill_time = new TimeFilterTuple( TimeFilterMode.CMEOpen, TimeTextTuple.FromDateTime(DateTime.Today), TimeTextTuple.FromDateTime(DateTime.Today.AddDays(1))) }; - rows_manager.on_settings(fs, s.sorting_criterion); + _rows_manager.on_settings(fs, s.sorting_criterion); }), settings_manager == null ? Disposable.empty : settings_manager.subscribe_current().OnDispatcher().Subscribe(grid_settings_manager), (fills_source as IConnectableObservable>)?.Connect() ?? Disposable.empty @@ -144,7 +132,7 @@ namespace mbts.spark { Width = width }, filter); void add_col_expl(Columns col_key, ColumnBase col, IDataGridColumnPersistentFilter filter) => - col_tups.Add(col_key, DIYGridColumnData.create(col, filter, _get_column_comparer(col_key))); + col_tups.Add(col_key, DIYGridColumnData.create(col, filter, _get_column_comparer(col_key))); // discrete-values-filter factories IDataGridColumnPersistentFilter dv_filter(IReadOnlyCollection items, Func get_row_val) => DiscreteValuesFilterVM.Create(items, get_row_val); IDataGridColumnPersistentFilter dv_filter_rx(IObservable> items, Func get_row_val) => DiscreteValuesFilterVM.Create(items, get_row_val); @@ -166,26 +154,26 @@ namespace mbts.spark { return grid_settings_manager.create(); } + public FillsFilterStates get_filters() => + _rows_manager.get_filters(); + public IEnumerable get_sorting_criterion() => - _sort_manager.create(); + _rows_manager.get_sorting_criterion(); public void on_sorting(object sender, DIYGridSortingEventArgs e) => - _sort_manager.on_sorting(e); + _rows_manager.on_sorting(e); static Columns _col_key(ColumnBase column) => ((IKeyedColumn)column).key; - public FilterStates get_filters() => - _filters_manager.create(); - - static IObservable> _get_observable(IBus bus, OrdersModel model, StartupData state) { + static IObservable> _get_observable(IBus bus, OrdersModel model, FillsSettings state) { if (!state.orders.is_null_or_empty()) { var orders_hash = new HashSet(state.orders); return model.on_fill_tuples.Filter(f => orders_hash.Contains(f.fill.OrderKey)); } else return model.on_fill_tuples; } - static IConnectableObservable> _get_observable(IBus bus, OrdersModel model, IObservable state) => + static IConnectableObservable> _get_observable(IBus bus, OrdersModel model, IObservable state) => state.SelectManyInSeries(s => _get_observable(bus, model, s)); static IComparer _get_column_comparer(Columns col) { diff --git a/src/client/spark/Modules/Trading/Fills/FillsWindow.cs b/src/client/spark/Modules/Trading/Fills/FillsWindow.cs index 32b1800b3..9c4e93dab 100644 --- a/src/client/spark/Modules/Trading/Fills/FillsWindow.cs +++ b/src/client/spark/Modules/Trading/Fills/FillsWindow.cs @@ -1,6 +1,7 @@ using bts; using bts.api; using bts.shell; +using bts.shell.fills; using bts.spark; using mbts.persist; using mbts.ui; @@ -13,21 +14,20 @@ using System.Collections.Generic; using System.Linq; using System.Reactive.Linq; using System.Windows; -using StartupData = bts.shell.FillsWindowFactory.StartupData; namespace mbts.spark { - class FillsWindow : SparkWindow, ISharedWindow { + class FillsWindow : SparkWindow, ISharedWindow { public const string window_type_name = "Fills"; readonly AllowOnce _init_guard = new AllowOnce("Fills"); readonly OrdersModel _orders_model; readonly IWindowSettingsManager _settings_manager; FillsVM _vm; FillsView _view; - StartupData _state; + FillsSettings _state; IReadOnlyList _commands; IDisposable _subscriptions; - public FillsWindow(FillsWindowFactory factory, IBus bus, OrdersModel orders_model, StartupData state, WindowSettingsManager settings_manager) + public FillsWindow(FillsWindowFactory factory, IBus bus, OrdersModel orders_model, FillsSettings state, WindowSettingsManager settings_manager) : base("Fills", bus, factory, SparkCommands.ShowFills().icon) { _orders_model = orders_model; _state = state; @@ -35,15 +35,15 @@ namespace mbts.spark { thread_id = config.Configuration.get().fills ? "Fills" : null; } - event Action _state_changed; + event Action _state_changed; public override string window_type => window_type_name; public override UIElement Content => _view; public override IEnumerable Commands => _commands; - public override StartupData SaveState => _state = new StartupData(_state.orders, _vm.get_sorting_criterion().ToList(), _vm.get_filters(), _vm.get_grid_save_state()); + public override FillsSettings SaveState => _state = new FillsSettings(_state.orders, _vm.get_sorting_criterion().ToList(), _vm.get_filters(), _vm.get_grid_save_state()); public override double MinWidth => - StartupData.DefaultGridSettings.columns.Sum(gcs => gcs.width) + FillsSettings.DefaultGridSettings.columns.Sum(gcs => gcs.width) + SPARK_MENU_COLLAPSED_WIDTH + LAUNCHER_BUTTON_BORDER_WIDTH + EXTRA_FOR_NO_HORIZONTAL_SCROLLBAR_WIDTH; @@ -53,7 +53,7 @@ namespace mbts.spark { public void thread_init() { _init_guard.check_access(); Log.notnull(_state); - var state_src = Observable.FromEvent, FillsWindowFactory.StartupData>(cb => _state_changed += cb, cb => _state_changed -= cb).StartWith(_state); + var state_src = Observable.FromEvent, FillsSettings>(cb => _state_changed += cb, cb => _state_changed -= cb).StartWith(_state); _vm = new FillsVM(_bus, _orders_model, state_src, _settings_manager); _view = new FillsView { DataContext = _vm }; @@ -79,7 +79,7 @@ namespace mbts.spark { }; _subscriptions = Disposable.Create(() => _state_changed?.Invoke( - _state = new StartupData(_state.orders, + _state = new FillsSettings(_state.orders, _vm.get_sorting_criterion().ToList(), _vm.get_filters(), _vm.grid_settings_manager.create() diff --git a/src/client/spark/Modules/Trading/Fills/FillsWindowFactory.cs b/src/client/spark/Modules/Trading/Fills/FillsWindowFactory.cs index ce49d6e87..bbd9ddf5e 100644 --- a/src/client/spark/Modules/Trading/Fills/FillsWindowFactory.cs +++ b/src/client/spark/Modules/Trading/Fills/FillsWindowFactory.cs @@ -1,5 +1,6 @@ using bts.api; using bts.api.orderman; +using bts.shell.fills; using mbts.persist; using mbts.spark; using mbts.spark.filters; @@ -16,7 +17,7 @@ using static mbts.ui.controls.DIYGrid; using static mbts.ui.spark.FillsView; namespace bts.shell { - class FillsWindowFactory : ShellWindowFactory { + class FillsWindowFactory : ShellWindowFactory { readonly IBus _bus; readonly OrdersModel _orders_model; readonly UserSettingsHub _settings_hub; @@ -52,13 +53,13 @@ namespace bts.shell { public static string col_id(Columns col) => col.ToString(); - public override Task load(StartupData state) => + public override Task load(FillsSettings state) => Task.FromResult(_create(state)); - public async void show(StartupData state) => + public async void show(FillsSettings state) => _bus.post(SparkTags.ShowWindow, await load(state)); - IShellWindow _create(StartupData state) { + IShellWindow _create(FillsSettings state) { GridSettingsHelper.normalize_sorting_criterion(state.sorting_criterion, _sort_member_to_id); var settings_manager = new WindowSettingsManager(_settings_hub, state.grid, @@ -66,162 +67,5 @@ namespace bts.shell { set: (us, gs) => us.with(provided_fills_gridsettings: gs)); return new FillsWindow(this, _bus, _orders_model, state, settings_manager); } - - [ProtoContract] - public class StartupData { - public const int Version = 1; - - [ProtoMember(1)] - public uint[] orders; - [ProtoMember(2)] - List _sorting_criteria; - [ProtoMember(3)] - public FilterStates filters; - [ProtoMember(4)] - public GridSettings grid; - - public StartupData() { } - public StartupData(uint[] orders) : this(orders, null, null) { } - public StartupData(FilterStates filters) : this(null, null, filters) { } - public StartupData(uint[] orders, List sorting_criteria, FilterStates filters, GridSettings grid = default) { - this.orders = orders; - this._sorting_criteria = sorting_criteria; - this.filters = filters; - this.grid = grid; - } - - public static GridSettings DefaultGridSettings => GridSettings.Default.with(DefaultColumns.all, DefaultColumns.default_sorting_criterion); - public static GridSettings MiniGridSettings => GridSettings.Default.with(DefaultColumns.Mini.all, DefaultColumns.Mini.sorting_criterion); - public IReadOnlyList sorting_criterion => _sorting_criteria ?? (_sorting_criteria = DefaultColumns.default_sorting_criterion.ToList()); - public static StartupData Default() => - new StartupData(null, null, new FilterStates(), null); - - static class DefaultColumns { - public static GridColumnSettings security => new GridColumnSettings(col_id(Columns.Security), DefaultColumnHeaders.Security, width: DefaultColumnWidths.Security); - public static GridColumnSettings fill_time => new GridColumnSettings(col_id(Columns.FillTime), DefaultColumnHeaders.FillTime, width: DefaultColumnWidths.Time); - public static GridColumnSettings user => new GridColumnSettings(col_id(Columns.User), DefaultColumnHeaders.User, width: DefaultColumnWidths.User); - public static GridColumnSettings account => new GridColumnSettings(col_id(Columns.Account), DefaultColumnHeaders.Account, width: DefaultColumnWidths.Account); - public static GridColumnSettings exchange => new GridColumnSettings(col_id(Columns.Exchange), DefaultColumnHeaders.Exchange, width: DefaultColumnWidths.Exchange); - public static GridColumnSettings time_in_force => new GridColumnSettings(col_id(Columns.TimeInForce), DefaultColumnHeaders.TimeInForce, width: DefaultColumnWidths.TimeInForce); - public static GridColumnSettings order_type => new GridColumnSettings(col_id(Columns.OrderType), DefaultColumnHeaders.OrderType, width: DefaultColumnWidths.OrderType); - public static GridColumnSettings side => new GridColumnSettings(col_id(Columns.Side), DefaultColumnHeaders.Side, width: DefaultColumnWidths.Side); - public static GridColumnSettings quantity => new GridColumnSettings(col_id(Columns.Size), DefaultColumnHeaders.Size, width: DefaultColumnWidths.Size, horizontal_alignment: System.Windows.HorizontalAlignment.Right); - public static GridColumnSettings price => new GridColumnSettings(col_id(Columns.Price), DefaultColumnHeaders.Price, width: DefaultColumnWidths.Price, horizontal_alignment: System.Windows.HorizontalAlignment.Right); - public static GridColumnSettings fill_kind => new GridColumnSettings(col_id(Columns.FillKind), DefaultColumnHeaders.FillKind, width: DefaultColumnWidths.FillKind); - public static GridColumnSettings fill_key => new GridColumnSettings(col_id(Columns.FillKey), DefaultColumnHeaders.FillKey, width: DefaultColumnWidths.FillKey); - public static GridColumnSettings order_key => new GridColumnSettings(col_id(Columns.OrderKey), DefaultColumnHeaders.OrderKey, width: DefaultColumnWidths.OrderKey); - public static GridColumnSettings security_key => new GridColumnSettings(col_id(Columns.SecurityKey), DefaultColumnHeaders.SecurityKey, is_visible: false, width: DefaultColumnWidths.SecurityKey); - public static IEnumerable default_sorting_criterion { - get { - yield return new SortingCriteria(fill_time.id, false); - } - } - - public static IEnumerable all { - get { - yield return security; - yield return fill_time; - yield return user; - yield return account; - yield return exchange; - yield return time_in_force; - yield return order_type; - yield return side; - yield return quantity; - yield return price; - yield return fill_kind; - yield return fill_key; - yield return order_key; - yield return security_key; - } - } - - public static class Mini { - static readonly IReadOnlyDictionary _mini_cols_data = - new Dictionary { - { Columns.Security, (true, null) }, - { Columns.FillTime, (true, ShortColumnWidths.Time) }, - { Columns.OrderType, (true, ShortColumnWidths.OrderType) }, - { Columns.Side, (true, ShortColumnWidths.Side) }, - { Columns.Size, (true, ShortColumnWidths.Size) }, - { Columns.Price, (true, ShortColumnWidths.Price) }, - }; - - public static IEnumerable all => DefaultColumns.all.Select(_convert); - public static IEnumerable sorting_criterion => default_sorting_criterion.Where(c => _try_get_data(c.col_name, out (bool is_visible, double? _) d) && d.is_visible); - - static bool _try_get_data(string id_str, out (bool is_visible, double? width_override) data) { - if (Enum.TryParse(id_str, out Columns k) && _mini_cols_data.TryGetValue(k, out data)) - return true; - data = default; - return false; - } - - static GridColumnSettings _convert(GridColumnSettings default_col) => - _try_get_data(default_col.id, out (bool is_visible, double? width_override) d) ? - default_col.with(is_visible: d.is_visible, width: d.width_override) : - default_col.with(is_visible: false); - } - } - } - - [ProtoContract] - public class FilterStates { - [ProtoMember(1)] - [DIYGridColumnID(nameof(Columns.FillTime))] - public TimeFilterTuple fill_time { get; set; } - - [ProtoMember(2)] - [DIYGridColumnID(nameof(Columns.TimeInForce))] - public TimeInForce[] time_in_force { get; set; } - - [ProtoMember(3)] - [DIYGridColumnID(nameof(Columns.OrderType))] - public CustomOrderDefinition.CustomOneofCase[] order_type { get; set; } - - [ProtoMember(4)] - [DIYGridColumnID(nameof(Columns.Account))] - public string[] account { get; set; } - - [ProtoMember(5)] - [DIYGridColumnID(nameof(Columns.User))] - public string[] user { get; set; } - - [ProtoMember(6)] - [DIYGridColumnID(nameof(Columns.Exchange))] - public Venue[] exchange { get; set; } - - [ProtoMember(7)] - [DIYGridColumnID(nameof(Columns.Security))] - public SecurityCriteria security { get; set; } - - [ProtoMember(8)] - [DIYGridColumnID(nameof(Columns.Side))] - public Side[] side { get; set; } - - [ProtoMember(9)] - [DIYGridColumnID(nameof(Columns.Price))] - public DoubleMinMaxState price { get; set; } - - [ProtoMember(10)] - [DIYGridColumnID(nameof(Columns.Size))] - public DoubleMinMaxState size { get; set; } - - [ProtoMember(11)] - [DIYGridColumnID(nameof(Columns.FillKey))] - public string fill_key { get; set; } - - [ProtoMember(12)] - [DIYGridColumnID(nameof(Columns.OrderKey))] - public string order_key { get; set; } - - [ProtoMember(13)] - [DIYGridColumnID(nameof(Columns.SecurityKey))] - public string security_key { get; set; } - - [ProtoMember(14)] - [DIYGridColumnID(nameof(Columns.FillKind))] - public Fill.Types.FillKind[] fill_kind { get; set; } - } } } \ No newline at end of file diff --git a/src/client/spark/Modules/Trading/Fills/Settings/FillsFilterStates.cs b/src/client/spark/Modules/Trading/Fills/Settings/FillsFilterStates.cs new file mode 100644 index 000000000..3c59147c6 --- /dev/null +++ b/src/client/spark/Modules/Trading/Fills/Settings/FillsFilterStates.cs @@ -0,0 +1,95 @@ +using bts.api; +using bts.api.orderman; +using mbts.spark; +using mbts.spark.filters; +using mbts.ui; +using mbts.ui.controls; +using ProtoBuf; +using System; +using Columns = mbts.ui.spark.FillsView.Columns; + +namespace bts.shell.fills { + [ProtoContract] + class FillsFilterStates { + [ProtoMember(1)] + [DIYGridColumnID(nameof(Columns.FillTime))] + public TimeFilterTuple fill_time { get; set; } + + [ProtoMember(2)] + [DIYGridColumnID(nameof(Columns.TimeInForce))] + public TimeInForce[] time_in_force { get; set; } + + [ProtoMember(3)] + [DIYGridColumnID(nameof(Columns.OrderType))] + public CustomOrderDefinition.CustomOneofCase[] order_type { get; set; } + + [ProtoMember(4)] + [DIYGridColumnID(nameof(Columns.Account))] + public string[] account { get; set; } + + [ProtoMember(5)] + [DIYGridColumnID(nameof(Columns.User))] + public string[] user { get; set; } + + [ProtoMember(6)] + [DIYGridColumnID(nameof(Columns.Exchange))] + public Venue[] exchange { get; set; } + + [ProtoMember(7)] + [DIYGridColumnID(nameof(Columns.Security))] + public SecurityCriteria security { get; set; } + + [ProtoMember(8)] + [DIYGridColumnID(nameof(Columns.Side))] + public Side[] side { get; set; } + + [ProtoMember(9)] + [DIYGridColumnID(nameof(Columns.Price))] + public DoubleMinMaxState price { get; set; } + + [ProtoMember(10)] + [DIYGridColumnID(nameof(Columns.Size))] + public DoubleMinMaxState size { get; set; } + + [ProtoMember(11)] + [DIYGridColumnID(nameof(Columns.FillKey))] + public string fill_key { get; set; } + + [ProtoMember(12)] + [DIYGridColumnID(nameof(Columns.OrderKey))] + public string order_key { get; set; } + + [ProtoMember(13)] + [DIYGridColumnID(nameof(Columns.SecurityKey))] + public string security_key { get; set; } + + [ProtoMember(14)] + [DIYGridColumnID(nameof(Columns.FillKind))] + public Fill.Types.FillKind[] fill_kind { get; set; } + } + + static class FillsFilterStatesExtensions { + public static Func build_predicate(this FillsFilterStates fs) { + var pb = new ColumnPredicateBuilder(); + // fill time + pb.add_time_filter(fs.fill_time, ft => ft.fill_time()); + // security + pb.add_security_criteria(fs.security, ft => ft.security); + // regex + pb.add_regex(fs.fill_key, ft => ft.fill.FillKey); + pb.add_regex(fs.order_key, ft => ft.order_key().ToString()); + // discrete values + pb.add_discrete_values(fs.user, ft => ft.user()); + pb.add_discrete_values(fs.account, ft => ft.account); + pb.add_discrete_values(fs.exchange, ft => ft.exchange()); + pb.add_discrete_values(fs.time_in_force, ft => ft.time_in_force()); + pb.add_discrete_values(fs.order_type, ft => ft.order_type()); + pb.add_discrete_values(fs.side, ft => ft.fill.Side); + pb.add_discrete_values(fs.fill_kind, ft => ft.fill.FillKind); + // numeric + pb.add_numeric(fs.size, ft => ft.fill.LastShares); + pb.add_numeric(fs.price, ft => ft.fill.LastPrice); + return pb.to_predicate(); + } + } +} \ No newline at end of file diff --git a/src/client/spark/Modules/Trading/Fills/Settings/FillsSettings.cs b/src/client/spark/Modules/Trading/Fills/Settings/FillsSettings.cs new file mode 100644 index 000000000..18ba73b3c --- /dev/null +++ b/src/client/spark/Modules/Trading/Fills/Settings/FillsSettings.cs @@ -0,0 +1,109 @@ +using mbts.ui; +using mbts.ui.settings; +using ProtoBuf; +using System; +using System.Collections.Generic; +using System.Linq; +using static bts.shell.FillsWindowFactory; +using static mbts.ui.controls.DIYGrid; +using Columns = mbts.ui.spark.FillsView.Columns; + +namespace bts.shell.fills { + [ProtoContract] + class FillsSettings { + public const int Version = 1; + + [ProtoMember(1)] + public uint[] orders; + [ProtoMember(2)] + List _sorting_criteria; + [ProtoMember(3)] + public FillsFilterStates filters; + [ProtoMember(4)] + public GridSettings grid; + + public FillsSettings() { } + public FillsSettings(uint[] orders) : this(orders, null, null) { } + public FillsSettings(FillsFilterStates filters) : this(null, null, filters) { } + public FillsSettings(uint[] orders, List sorting_criteria, FillsFilterStates filters, GridSettings grid = default) { + this.orders = orders; + this._sorting_criteria = sorting_criteria; + this.filters = filters; + this.grid = grid; + } + + public static GridSettings DefaultGridSettings => GridSettings.Default.with(DefaultColumns.all, DefaultColumns.default_sorting_criterion); + public static GridSettings MiniGridSettings => GridSettings.Default.with(DefaultColumns.Mini.all, DefaultColumns.Mini.sorting_criterion); + public IReadOnlyList sorting_criterion => _sorting_criteria ?? (_sorting_criteria = DefaultColumns.default_sorting_criterion.ToList()); + public static FillsSettings Default() => + new FillsSettings(null, null, new FillsFilterStates(), null); + + static class DefaultColumns { + public static GridColumnSettings security => new GridColumnSettings(col_id(Columns.Security), DefaultColumnHeaders.Security, width: DefaultColumnWidths.Security); + public static GridColumnSettings fill_time => new GridColumnSettings(col_id(Columns.FillTime), DefaultColumnHeaders.FillTime, width: DefaultColumnWidths.Time); + public static GridColumnSettings user => new GridColumnSettings(col_id(Columns.User), DefaultColumnHeaders.User, width: DefaultColumnWidths.User); + public static GridColumnSettings account => new GridColumnSettings(col_id(Columns.Account), DefaultColumnHeaders.Account, width: DefaultColumnWidths.Account); + public static GridColumnSettings exchange => new GridColumnSettings(col_id(Columns.Exchange), DefaultColumnHeaders.Exchange, width: DefaultColumnWidths.Exchange); + public static GridColumnSettings time_in_force => new GridColumnSettings(col_id(Columns.TimeInForce), DefaultColumnHeaders.TimeInForce, width: DefaultColumnWidths.TimeInForce); + public static GridColumnSettings order_type => new GridColumnSettings(col_id(Columns.OrderType), DefaultColumnHeaders.OrderType, width: DefaultColumnWidths.OrderType); + public static GridColumnSettings side => new GridColumnSettings(col_id(Columns.Side), DefaultColumnHeaders.Side, width: DefaultColumnWidths.Side); + public static GridColumnSettings quantity => new GridColumnSettings(col_id(Columns.Size), DefaultColumnHeaders.Size, width: DefaultColumnWidths.Size, horizontal_alignment: System.Windows.HorizontalAlignment.Right); + public static GridColumnSettings price => new GridColumnSettings(col_id(Columns.Price), DefaultColumnHeaders.Price, width: DefaultColumnWidths.Price, horizontal_alignment: System.Windows.HorizontalAlignment.Right); + public static GridColumnSettings fill_kind => new GridColumnSettings(col_id(Columns.FillKind), DefaultColumnHeaders.FillKind, width: DefaultColumnWidths.FillKind); + public static GridColumnSettings fill_key => new GridColumnSettings(col_id(Columns.FillKey), DefaultColumnHeaders.FillKey, width: DefaultColumnWidths.FillKey); + public static GridColumnSettings order_key => new GridColumnSettings(col_id(Columns.OrderKey), DefaultColumnHeaders.OrderKey, width: DefaultColumnWidths.OrderKey); + public static GridColumnSettings security_key => new GridColumnSettings(col_id(Columns.SecurityKey), DefaultColumnHeaders.SecurityKey, is_visible: false, width: DefaultColumnWidths.SecurityKey); + public static IEnumerable default_sorting_criterion { + get { + yield return new SortingCriteria(fill_time.id, false); + } + } + + public static IEnumerable all { + get { + yield return security; + yield return fill_time; + yield return user; + yield return account; + yield return exchange; + yield return time_in_force; + yield return order_type; + yield return side; + yield return quantity; + yield return price; + yield return fill_kind; + yield return fill_key; + yield return order_key; + yield return security_key; + } + } + + public static class Mini { + static readonly IReadOnlyDictionary _mini_cols_data = + new Dictionary { + { Columns.Security, (true, null) }, + { Columns.FillTime, (true, ShortColumnWidths.Time) }, + { Columns.OrderType, (true, ShortColumnWidths.OrderType) }, + { Columns.Side, (true, ShortColumnWidths.Side) }, + { Columns.Size, (true, ShortColumnWidths.Size) }, + { Columns.Price, (true, ShortColumnWidths.Price) }, + }; + + public static IEnumerable all => DefaultColumns.all.Select(_convert); + public static IEnumerable sorting_criterion => default_sorting_criterion.Where(c => _try_get_data(c.col_name, out (bool is_visible, double? _) d) && d.is_visible); + + static bool _try_get_data(string id_str, out (bool is_visible, double? width_override) data) { + if (Enum.TryParse(id_str, out Columns k) && _mini_cols_data.TryGetValue(k, out data)) + return true; + data = default; + return false; + } + + static GridColumnSettings _convert(GridColumnSettings default_col) => + _try_get_data(default_col.id, out (bool is_visible, double? width_override) d) ? + default_col.with(is_visible: d.is_visible, width: d.width_override) : + default_col.with(is_visible: false); + } + } + } +} \ No newline at end of file diff --git a/src/client/spark/Modules/Trading/OrderBook/OrderBookVM.cs b/src/client/spark/Modules/Trading/OrderBook/OrderBookVM.cs index cff54d5c4..e92d0d929 100644 --- a/src/client/spark/Modules/Trading/OrderBook/OrderBookVM.cs +++ b/src/client/spark/Modules/Trading/OrderBook/OrderBookVM.cs @@ -3,12 +3,11 @@ using bts.api; using bts.api.core; using bts.api.orderman; using bts.collections; -using bts.md; using bts.shell; +using bts.shell.fills; using bts.shell.orderbook; using bts.spark; using bts.utils; -using mbts.collections; using mbts.persist; using mbts.spark.utilities; using mbts.ui; @@ -45,7 +44,7 @@ namespace mbts.spark { readonly OperableHierarchicalCollection _row_collection; readonly OrderBookColumnCollection _columns; readonly IWindowSettingsManager _settings_manager; - readonly IWindowSettingsManager _fills_settings_manager = new WindowSettingsManager.DisconnectedImpl(FillsWindowFactory.StartupData.MiniGridSettings, FillsWindowFactory.StartupData.MiniGridSettings); + readonly IWindowSettingsManager _fills_settings_manager = new WindowSettingsManager.DisconnectedImpl(FillsSettings.MiniGridSettings, FillsSettings.MiniGridSettings); readonly SelectedOrderParamsMon _selected_params_mon; readonly RightPanelModel _right_panel = new RightPanelModel(); OrderBookFillsGridSettings _cached_fills_settings = OrderBookStartupData.DefaultFillsGrid; diff --git a/src/client/spark/Modules/Trading/OrderBook/OrderBookWindow.cs b/src/client/spark/Modules/Trading/OrderBook/OrderBookWindow.cs index 876d96079..a13669bda 100644 --- a/src/client/spark/Modules/Trading/OrderBook/OrderBookWindow.cs +++ b/src/client/spark/Modules/Trading/OrderBook/OrderBookWindow.cs @@ -1,6 +1,7 @@ using bts.api; using bts.api.orderman; using bts.shell; +using bts.shell.fills; using bts.shell.orderbook; using bts.spark; using bts.view; @@ -68,7 +69,7 @@ namespace mbts.spark { _vm.load_from(_state); _view = new OrderBookView(_vm); - var show_fills_command = SparkCommands.ShowFills(SparkCommands.KeyGestures.ShowFills).complete(() => new FillsWindowFactory.StartupData(_vm.selected_orders.Select(r => r.Key).ToArray())); + var show_fills_command = SparkCommands.ShowFills(SparkCommands.KeyGestures.ShowFills).complete(() => new FillsSettings(_vm.selected_orders.Select(r => r.Key).ToArray())); var toggle_show_right_panel_command = new SparkCommandCommand( get_toggle_show_right_panel_cmd_title(), diff --git a/src/client/spark/Modules/Trading/OrderBook/Settings/OrderBookFillsGridSettings.cs b/src/client/spark/Modules/Trading/OrderBook/Settings/OrderBookFillsGridSettings.cs index 9c8489afa..92a1528eb 100644 --- a/src/client/spark/Modules/Trading/OrderBook/Settings/OrderBookFillsGridSettings.cs +++ b/src/client/spark/Modules/Trading/OrderBook/Settings/OrderBookFillsGridSettings.cs @@ -1,4 +1,5 @@ -using mbts.ui; +using bts.shell.fills; +using mbts.ui; using ProtoBuf; using System.Collections.Generic; using GridSettings = mbts.ui.settings.GridSettings; @@ -9,11 +10,11 @@ namespace bts.shell.orderbook { [ProtoMember(1)] public GridSettings general { get; set; } [ProtoMember(2)] - public FillsWindowFactory.FilterStates filters { get; set; } + public FillsFilterStates filters { get; set; } [ProtoMember(3)] public List sorting_criterion { get; set; } - public FillsWindowFactory.StartupData to_startup_data() => - new FillsWindowFactory.StartupData(null, sorting_criterion, filters, general); + public FillsSettings to_startup_data() => + new FillsSettings(null, sorting_criterion, filters, general); } } \ No newline at end of file diff --git a/src/client/spark/Modules/Trading/OrderBook/Settings/OrderBookFilterStates.cs b/src/client/spark/Modules/Trading/OrderBook/Settings/OrderBookFilterStates.cs index 7f2a070c2..1124b94d5 100644 --- a/src/client/spark/Modules/Trading/OrderBook/Settings/OrderBookFilterStates.cs +++ b/src/client/spark/Modules/Trading/OrderBook/Settings/OrderBookFilterStates.cs @@ -7,8 +7,6 @@ using mbts.spark.filters; using mbts.ui; using ProtoBuf; using System; -using System.Collections.Generic; -using System.Linq; namespace bts.shell.orderbook { [ProtoContract] @@ -121,86 +119,36 @@ namespace bts.shell.orderbook { static class FilterStatesExtensions { public static Func build_predicate(this FilterStates fs) { - var predicates = new List>(); + var pb = new ColumnPredicateBuilder(); // security - if (fs.security_criteria?.is_defined() ?? false) - predicates.Add(o => o.security.HasValue && ContractPickerModel.security_in_criteria(fs.security_criteria, o.security.Value)); + pb.add_security_criteria(fs.security_criteria, o => o.security); // regex - add_regex(fs.order_key_regex, o => o.order.Key.ToString()); - add_regex(fs.exchange_message_regex, o => o.order.State.LastMsg); - add_regex(fs.attached_target_order_key_regex, o => o.order.attached_target_order_key().ToString()); - add_regex(fs.parent_key_regex, o => o.order.ParentKey.ToString()); + pb.add_regex(fs.order_key_regex, o => o.order.Key.ToString()); + pb.add_regex(fs.exchange_message_regex, o => o.order.State.LastMsg); + pb.add_regex(fs.attached_target_order_key_regex, o => o.order.attached_target_order_key().ToString()); + pb.add_regex(fs.parent_key_regex, o => o.order.ParentKey.ToString()); // time - add_time_filter(fs.time_created, o => o.order.created()); - add_time_filter(fs.last_change, o => o.order.last_change()); + pb.add_time_filter(fs.time_created, o => o.order.created()); + pb.add_time_filter(fs.last_change, o => o.order.last_change()); // discrete values - add_discrete_values(fs.users, o => o.order.user()); - 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_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()); - add_discrete_values(fs.symbols, o => o.security?.Symbol); + pb.add_discrete_values(fs.users, o => o.order.user()); + pb.add_discrete_values(fs.accounts, o => o.order.account()); + pb.add_discrete_values(fs.exchanges, o => o.security?.Exchange ?? Venue.Unset); + pb.add_discrete_values(fs.tifs, o => o.order.time_in_force()); + pb.add_discrete_values(fs.order_types, o => AlgoID.from_order_def(o.order.Def)); + pb.add_discrete_values(fs.root_algo_types, o => AlgoID.from_algo_key(o.root_algo.key)); + pb.add_discrete_values(fs.order_sub_types, o => o.order.sub_type()); + pb.add_discrete_values(fs.sides, o => o.order.side()); + pb.add_discrete_values(fs.statuses, o => o.order.status()); + pb.add_discrete_values(fs.symbols, o => o.security?.Symbol); // numeric - add_numeric(fs.qty, o => o.order.quantity()); - add_numeric(fs.price, o => o.order.price()); - add_numeric(fs.qty_filled, o => o.order.filled()); - add_numeric(fs.avg_price, o => o.order.avg_price()); - add_numeric(fs.last_price, o => o.order.last_price()); - add_numeric(fs.piq, o => o.piq ?? uint.MaxValue); - return predicates.Count == 0 ? null : new Func(o => predicates.All(p => p(o))); - // local methods (impl) - void add_regex(string str, Func selector) { - var regex = RegexFilterUtils.build_regex(str); - if (regex == null) - return; - predicates.Add(impl); - bool impl(OrderSecurity o) => regex.IsMatch(selector(o) ?? string.Empty); - } - void add_time_filter(TimeFilterTuple t, Func selector) { - if (!t.is_active) - return; - var dt_pred = TimeFilterUtils.build_predicate(t); - predicates.Add(impl); - bool impl(OrderSecurity o) => dt_pred(selector(o)); - } - void add_discrete_values(T[] values, Func selector) { - if (values.is_null_or_empty()) - return; - if (values.Length < 16) { - predicates.Add(impl); - bool impl(OrderSecurity o) => values.Contains(selector(o)); - } else { - var set = new HashSet(values); - predicates.Add(impl); - bool impl(OrderSecurity o) => set.Contains(selector(o)); - } - } - void add_numeric(IMinMaxState value, Func selector) where T : struct, IComparable { - if (value == null) - return; - if (value.minimum.active) { - var min = value.minimum.value.Value; - if (value.maximum.active) { - var max = value.maximum.value.Value; - predicates.Add(impl); - bool impl(OrderSecurity o) { - var v = selector(o); - return min.CompareTo(v) <= 0 && max.CompareTo(v) >= 0; - } - } else { - predicates.Add(impl); - bool impl(OrderSecurity o) => min.CompareTo(selector(o)) <= 0; - } - } else if (value.maximum.active) { - var max = value.maximum.value.Value; - predicates.Add(impl); - bool impl(OrderSecurity o) => max.CompareTo(selector(o)) >= 0; - } - } + pb.add_numeric(fs.qty, o => o.order.quantity()); + pb.add_numeric(fs.price, o => o.order.price()); + pb.add_numeric(fs.qty_filled, o => o.order.filled()); + pb.add_numeric(fs.avg_price, o => o.order.avg_price()); + pb.add_numeric(fs.last_price, o => o.order.last_price()); + pb.add_numeric(fs.piq, o => o.piq ?? uint.MaxValue); + return pb.to_predicate(); } } } diff --git a/src/client/spark/Modules/Trading/OrderBook/Settings/OrderBookSettings.cs b/src/client/spark/Modules/Trading/OrderBook/Settings/OrderBookSettings.cs index 5c5caa779..236de5dfc 100644 --- a/src/client/spark/Modules/Trading/OrderBook/Settings/OrderBookSettings.cs +++ b/src/client/spark/Modules/Trading/OrderBook/Settings/OrderBookSettings.cs @@ -1,4 +1,5 @@ using bts.api.orderman; +using bts.shell.fills; using mbts; using mbts.ui; using mbts.ui.controls; @@ -127,11 +128,11 @@ namespace bts.shell.orderbook { public static OrderBookFillsGridSettings DefaultFillsGrid { get { - var default_fills = FillsWindowFactory.StartupData.Default(); + var default_fills = FillsSettings.Default(); var rv = new OrderBookFillsGridSettings { sorting_criterion = default_fills.sorting_criterion.ToList(), filters = default_fills.filters, - general = FillsWindowFactory.StartupData.MiniGridSettings + general = FillsSettings.MiniGridSettings }; return rv; } diff --git a/src/client/spark/Modules/Trading/TradingShellModule.cs b/src/client/spark/Modules/Trading/TradingShellModule.cs index 61234ddde..8188f0b23 100644 --- a/src/client/spark/Modules/Trading/TradingShellModule.cs +++ b/src/client/spark/Modules/Trading/TradingShellModule.cs @@ -1,4 +1,5 @@ using bts.api; +using bts.shell.fills; using bts.shell.manual_fills; using bts.spark; using mbts.persist; @@ -48,7 +49,7 @@ namespace bts.shell { public IEnumerable actions => new [] { SparkCommands.ShowOrders.complete(() => bts.shell.orderbook.OrderBookStartupData.Default), - SparkCommands.ShowFills(null).complete(() => new FillsWindowFactory.StartupData()), + SparkCommands.ShowFills(null).complete(() => new FillsSettings()), SparkCommands.ShowPAndL.complete(() => new PAndLWindowFactory.PAndLStartupData()), SparkCommands.PickLadder, SparkCommands.PickOrderTicket, diff --git a/src/client/spark/Orders/FillTuple.cs b/src/client/spark/Orders/FillTuple.cs index bfcd80a5c..40f4f65d6 100644 --- a/src/client/spark/Orders/FillTuple.cs +++ b/src/client/spark/Orders/FillTuple.cs @@ -46,4 +46,24 @@ namespace mbts.spark { order.HasValue ? order.Value.Key.GetHashCode() : 0, security.HasValue ? security.Value.Id.GetHashCode() : 0); } + + static class FillTupleExtensions { + public static DateTime fill_time(this FillTuple fill_tuple) => + fill_tuple.fill.Timestamp.to_local_time(); + + public static TimeInForce time_in_force(this FillTuple fill_tuple) => + fill_tuple.order.HasValue ? fill_tuple.order.Value.time_in_force() : TimeInForce.Undefined; + + public static CustomOrderDefinition.CustomOneofCase order_type(this FillTuple fill_tuple) => + fill_tuple.order.HasValue ? fill_tuple.order.Value.order_type() : CustomOrderDefinition.CustomOneofCase.None; + + public static Venue exchange(this FillTuple fill_tuple) => + fill_tuple.security.HasValue ? fill_tuple.security.Value.Exchange : Venue.Unset; + + public static uint order_key(this FillTuple fill_tuple) => + fill_tuple.order.HasValue ? fill_tuple.order.Value.Key : 0u; + + public static string user(this FillTuple fill_tuple) => + fill_tuple.order.HasValue ? fill_tuple.order.Value.user() : string.Empty; + } } \ No newline at end of file diff --git a/src/client/spark/core/Bus/SparkCommands.cs b/src/client/spark/core/Bus/SparkCommands.cs index 2dce59fc9..726eff24a 100644 --- a/src/client/spark/core/Bus/SparkCommands.cs +++ b/src/client/spark/core/Bus/SparkCommands.cs @@ -1,6 +1,7 @@ using bts.api; using bts.api.orderman; using bts.shell; +using bts.shell.fills; using bts.shell.manual_fills; using mbts; using mbts.spark; @@ -27,7 +28,7 @@ namespace bts.spark { SparkCommand.create("Order Book", Icons.Book, SparkTags.ShowOrderBookTag); // Fills - public static PartialCommand ShowFills(KeyGesture key_gesture = null) => + public static PartialCommand ShowFills(KeyGesture key_gesture = null) => SparkCommand.create("Fills", Icons.Payment, SparkTags.ShowFillsTag, key_gesture); public static PartialCommand ShowManualFills(KeyGesture key_gesture = null) => diff --git a/src/client/spark/core/Bus/SparkTags.cs b/src/client/spark/core/Bus/SparkTags.cs index c1c683f1c..eef9c6d4e 100644 --- a/src/client/spark/core/Bus/SparkTags.cs +++ b/src/client/spark/core/Bus/SparkTags.cs @@ -1,6 +1,7 @@ using bts.api; using bts.api.orderman; using bts.shell; +using bts.shell.fills; using bts.shell.manual_fills; using bts.spark; using mbts.ui; @@ -52,7 +53,7 @@ namespace mbts.spark #endregion #region Spark Window - public static ITag ShowFillsTag { get; } = new SparkTag(nameof(ShowFillsTag)); + public static ITag ShowFillsTag { get; } = new SparkTag(nameof(ShowFillsTag)); public static ITag ShowManualFillsTag { get; } = new SparkTag(nameof(ShowManualFillsTag)); // TODO: maybe get rid of the singlular ShowLadderTag, and just use the plural ShowLaddersTag. // The owners of the various SparkWindows may remove dependencies on the former at their leasure. diff --git a/src/client/spark/core/ShellInterface/UserSettings/UserSettings.cs b/src/client/spark/core/ShellInterface/UserSettings/UserSettings.cs index 869298646..61068c253 100644 --- a/src/client/spark/core/ShellInterface/UserSettings/UserSettings.cs +++ b/src/client/spark/core/ShellInterface/UserSettings/UserSettings.cs @@ -17,7 +17,7 @@ namespace mbts.spark { _ladder = LadderSettings.Default, _notification = NotificationSettings.Default, _market_view_grid = bts.shell.MarketViewWindowFactory.StartupData.DefaultGridSettings, - _fills_grid = bts.shell.FillsWindowFactory.StartupData.DefaultGridSettings, + _fills_grid = bts.shell.fills.FillsSettings.DefaultGridSettings, _time_and_sales_grid = bts.shell.TimeAndSalesWindowFactory.StartupData.DefaultGridSettings, _synthetic_management_grid = bts.shell.SyntheticManagementWindowFactory.StartupData.DefaultGridSettings, _order_book_grid = bts.shell.orderbook.OrderBookStartupData.DefaultGrid @@ -48,7 +48,7 @@ namespace mbts.spark { public NotificationSettings notification => _notification ?? (_notification = NotificationSettings.Default); public GridSettings market_view_grid => _market_view_grid ?? (_market_view_grid = bts.shell.MarketViewWindowFactory.StartupData.DefaultGridSettings); public GridSettings time_and_sales_grid => _time_and_sales_grid ?? (_time_and_sales_grid = GridSettings.Default.with(bts.shell.TimeAndSalesWindowFactory.StartupData.DefaultColumns.all)); - public GridSettings fills_grid => _fills_grid ?? (_fills_grid = bts.shell.FillsWindowFactory.StartupData.DefaultGridSettings); + public GridSettings fills_grid => _fills_grid ?? (_fills_grid = bts.shell.fills.FillsSettings.DefaultGridSettings); public GridSettings synthetic_management_grid => _synthetic_management_grid ?? (_synthetic_management_grid = bts.shell.SyntheticManagementWindowFactory.StartupData.DefaultGridSettings); public GridSettings pnl_grid => _pnl_grid ?? (_pnl_grid = bts.shell.PAndLWindowFactory.PAndLStartupData.DefaultGridSettings); public bts.shell.orderbook.OrderBookGridSettings order_book_grid => _order_book_grid ?? (_order_book_grid = bts.shell.orderbook.OrderBookStartupData.Default.grid_settings_wrapper()); diff --git a/src/client/spark/view/Controls/DIYGrid/Columns/ColumnPredicateBuilder.cs b/src/client/spark/view/Controls/DIYGrid/Columns/ColumnPredicateBuilder.cs new file mode 100644 index 000000000..03ee224f3 --- /dev/null +++ b/src/client/spark/view/Controls/DIYGrid/Columns/ColumnPredicateBuilder.cs @@ -0,0 +1,69 @@ +using bts.api; +using mbts.ui; +using System; +using System.Collections.Generic; +using System.Linq; + +namespace mbts.spark.filters { + class ColumnPredicateBuilder { + readonly List> _predicates = new List>(); + + public void add_discrete_values(T[] values, Func selector) { + if (values.is_null_or_empty()) + return; + var set = new HashSet(values); + _predicates.Add(impl); + bool impl(TRow o) => set.Contains(selector(o)); + } + + public void add_numeric(IMinMaxState value, Func selector) where T : struct, IComparable { + if (value == null) + return; + if (value.minimum.active) { + var min = value.minimum.value.Value; + if (value.maximum.active) { + var max = value.maximum.value.Value; + _predicates.Add(impl); + bool impl(TRow o) { + var v = selector(o); + return min.CompareTo(v) <= 0 && max.CompareTo(v) >= 0; + } + } else { + _predicates.Add(impl); + bool impl(TRow o) => min.CompareTo(selector(o)) <= 0; + } + } else if (value.maximum.active) { + var max = value.maximum.value.Value; + _predicates.Add(impl); + bool impl(TRow o) => max.CompareTo(selector(o)) >= 0; + } + } + + public void add_regex(string str, Func selector) { + var regex = RegexFilterUtils.build_regex(str); + if (regex == null) + return; + _predicates.Add(impl); + bool impl(TRow o) => regex.IsMatch(selector(o) ?? string.Empty); + } + + public void add_security_criteria(SecurityCriteria security_criteria, Func selector) { + if (security_criteria != null && security_criteria.is_defined()) + _predicates.Add(r => { + var sec = selector(r); + return sec.HasValue && ContractPickerModel.security_in_criteria(security_criteria, sec.Value); + }); + } + + public void add_time_filter(TimeFilterTuple t, Func selector) { + if (!t.is_active) + return; + var dt_pred = TimeFilterUtils.build_predicate(t); + _predicates.Add(impl); + bool impl(TRow o) => dt_pred(selector(o)); + } + + public Func to_predicate() => + _predicates.Count == 0 ? null : new Func(o => _predicates.All(p => p(o))); + } +} \ No newline at end of file diff --git a/src/client/spark/view/Controls/DIYGrid/Utils/DIYGridRowsManager.cs b/src/client/spark/view/Controls/DIYGrid/Utils/DIYGridRowsManager.cs index 268a6b61a..c9f5e4126 100644 --- a/src/client/spark/view/Controls/DIYGrid/Utils/DIYGridRowsManager.cs +++ b/src/client/spark/view/Controls/DIYGrid/Utils/DIYGridRowsManager.cs @@ -1,5 +1,6 @@ using bts; using bts.utils; +using mbts.collections; using mbts.utils; using System; using System.Collections.Generic; @@ -7,13 +8,30 @@ using System.ComponentModel; using System.Linq; namespace mbts.ui.controls { + static class DIYGridRowsManager { + public static DIYGridRowsManager create( + string window_name, + TColKey primary_key, + ObservableKeyedCollection, TColKey> columns, + IReadOnlyObservableKeyedCollection<(DIYGrid.ColumnBase col, TColKey key), TColKey> map, + Func> get_comparer_for_column, + Func> build_filter_from_state = null) where TColKey : struct where TFiltersState : new() => + // + new DIYGridRowsManager( + DIYGridFiltersManager.create(columns), + new DIYGridSortManager(map, primary_key), + get_comparer_for_column, + window_name, + build_filter_from_state); + } + class DIYGridRowsManager where TColKey : struct { readonly IDIYGridFiltersManager _filters; readonly DIYGridSortManager _sorting; readonly DeferrableActionWrapper _update; bool _filters_dirty, _sorting_dirty; - public DIYGridRowsManager(IDIYGridFiltersManager filters_manager, DIYGridSortManager sort_manager, Func> get_comparer_for_column, string window_name) { + public DIYGridRowsManager(IDIYGridFiltersManager filters_manager, DIYGridSortManager sort_manager, Func> get_comparer_for_column, string window_name, Func> build_filter_from_state = null) { _filters = filters_manager; _sorting = sort_manager; _update = new DeferrableActionWrapper(() => { @@ -59,10 +77,15 @@ namespace mbts.ui.controls { desc = "(none)"; return null; } else { - // TODO: the actual IDataGridFilter implementations should be able to provide a concise description of their filter state/parameters (e.g., for a min/max filter: 'min=40, max=60') desc = string.Join(", ", col_filters.Select(f => f.col)); - var filters = Array.ConvertAll(col_filters, cf => cf.filter); - return new Func(r => filters.All(f => f.filter(r))); + if (build_filter_from_state != null) { + var filter_state = filters_manager.create(); + return build_filter_from_state(filter_state); + } else { + // TODO: the actual IDataGridFilter implementations should be able to provide a concise description of their filter state/parameters (e.g., for a min/max filter: 'min=40, max=60') + var filters = Array.ConvertAll(col_filters, cf => cf.filter); + return new Func(r => filters.All(f => f.filter(r))); + } } } } @@ -70,6 +93,10 @@ namespace mbts.ui.controls { public event Action> filter_changed; public event Action> comparer_changed; + public TFiltersState get_filters() => _filters.create(); + public IEnumerable get_sorting_criterion() => _sorting.create(); + + public void on_sorting(DIYGridSortingEventArgs e) => _sorting.on_sorting(e); public void on_settings(TFiltersState filters, IEnumerable sorting) { using (_update.defer_execution()) { _filters.load_from(filters); diff --git a/src/client/spark/view/Utility/RXCollection.cs b/src/client/spark/view/Utility/RXCollection.cs index 3fd6e23da..57fbd014b 100644 --- a/src/client/spark/view/Utility/RXCollection.cs +++ b/src/client/spark/view/Utility/RXCollection.cs @@ -1,14 +1,11 @@ -using bts; -using bts.api.core; +using bts.api.core; using bts.collections; -using bts.utils; using mbts.utils; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.Linq; -using System.Reactive; using System.Reactive.Linq; namespace mbts.ui.utility { @@ -37,16 +34,16 @@ namespace mbts.ui.utility { table_update_source.Subscribe(on_table)); // on comparer void on_comp(IComparer new_comp) { + comp = new_comp; if (table != null) { target.Clear(); - target.InsertSorted(table.state.Values, comp); + target.InsertSorted(table.state.Values, new_comp); } - comp = new_comp; } // on table update void on_table(TableUpdate new_table) { + table = table == null ? new_table.as_snapshot() : new_table; if (comp != null) { - table = table == null ? new_table.as_snapshot() : new_table; target.RemoveSorted(table.removed.Concat(table.changes.Old()), comp); target.InsertSorted(table.added.Concat(table.changed), comp); } diff --git a/src/lib/md/test/md2_tests.cpp b/src/lib/md/test/md2_tests.cpp index d9da74ddd..74370e662 100644 --- a/src/lib/md/test/md2_tests.cpp +++ b/src/lib/md/test/md2_tests.cpp @@ -1270,10 +1270,10 @@ struct Co2RelayTests { // That's right. Expirations daily. out_producers->push_back( producer.add_security( - *mkfixedfuture("FOO", invalid_security_key, 2017, 1+(x/28), x%28))); + *mkfixedfuture("FOO", invalid_security_key, 2017, 1+(x/28), x%27+1))); out_producers->push_back( producer.add_security( - *mkfixedfuture("FOOF", invalid_security_key, 2017, 1+(x/28), x%28))); + *mkfixedfuture("FOOF", invalid_security_key, 2017, 1+(x/28), x%27+1))); } assign_ids(out_producers->begin(), out_producers->end(), 1000); diff --git a/src/lib/orderman/orders/algo/algo_orders/LeanAlgo.cpp b/src/lib/orderman/orders/algo/algo_orders/LeanAlgo.cpp index c1cd50f61..27a451aa2 100644 --- a/src/lib/orderman/orders/algo/algo_orders/LeanAlgo.cpp +++ b/src/lib/orderman/orders/algo/algo_orders/LeanAlgo.cpp @@ -20,11 +20,11 @@ struct LeanAlgo::PImpl { IAlgoServices* algo_services; double tick_size = os::nan(); Status status = Status::WAITING_FOR_MD; - Price initial_observed_price = Price(os::nan()); + // the first observed opp inside price + Price anchor_price = Price(os::nan()); Price observed_price = Price(os::nan()); OrderKey child_key = null_order_key(); ChildTemplate *child_template = nullptr; - md::PriceSize last_opp_inside = md::PriceSize(); Book curr_book; Price out_price = Price(os::nan()); Quantity out_qty = Quantity(0); @@ -106,8 +106,8 @@ void LeanAlgo::on_book(SecurityKey, const Book &book) { switch (me->status) { case LeanAlgo::Status::WAITING_FOR_MD: if (_opp_inside_market().size() != 0) { - me->initial_observed_price = Price(_opp_inside_market().price()); - me->observed_price = me->initial_observed_price; + me->anchor_price = Price(_opp_inside_market().price()); + me->observed_price = me->anchor_price; me->status = LeanAlgo::Status::WORKING; _analyze_and_act(); } @@ -158,11 +158,11 @@ LeanAlgo::_on_toward_behaviour() const { bool LeanAlgo::_book_moved_toward() const { return securities::is_better(_opp_side(), Price(_opp_inside_market().price()), - Price(me->last_opp_inside.price())); + me->anchor_price); } bool LeanAlgo::_book_moved_away() const { return securities::is_better(_opp_side(), - Price(me->last_opp_inside.price()), + me->anchor_price, Price(_opp_inside_market().price())); } md::PriceSize LeanAlgo::_opp_inside_market() const { @@ -173,29 +173,29 @@ api::Side LeanAlgo::_opp_side() const { } bool LeanAlgo::_within_chase_band(Price price) const{ return securities::is_better(algo().definition().side(), - me->initial_observed_price, + me->anchor_price, price) || static_cast(std::abs( securities::price_diff_to_ticks(price.value(), - me->initial_observed_price.value(), + me->anchor_price.value(), me->tick_size))) <= _max_chase_ticks(); } Price LeanAlgo::_chase_limit() const{ double offset=me->tick_size*_max_chase_ticks(); return securities::improve_price(algo().definition().side(), - me->initial_observed_price, + me->anchor_price, Price(offset)); } -LeanAlgo::MarketChange LeanAlgo::_market_change() const{ +LeanAlgo::OppMarketState LeanAlgo::_market_state() const{ md::PriceSize opp_inside=_opp_inside_market(); if(opp_inside.size()==0) - return MarketChange::NO_MARKET; + return OppMarketState::NO_MARKET; else if (_book_moved_away()) - return MarketChange::AWAY; + return OppMarketState::AWAY; else if (_book_moved_toward()) - return MarketChange::TOWARD; + return OppMarketState::TOWARD; else - return MarketChange::SIZE_CHANGE; + return OppMarketState::NO_DIRECTIONAL_CHANGE; } Price LeanAlgo::_get_price_to_pass (Price price) const{ // if it has crossed once, then the @@ -208,24 +208,25 @@ Price LeanAlgo::_get_price_to_pass (Price price) const{ /////////////////////////////////////////////////////////////////////////////// void LeanAlgo::_analyze_and_act() { bts_assert(me->status == LeanAlgo::Status::WORKING); - auto market_change=_market_change(); - me->last_opp_inside=_opp_inside_market(); + auto market_change=_market_state(); switch(market_change){ - case MarketChange::NO_MARKET: + case OppMarketState::NO_MARKET: _go_furthest_possible(); break; - case MarketChange::SIZE_CHANGE: + case OppMarketState::NO_DIRECTIONAL_CHANGE: _try_cross(me->observed_price); break; - case MarketChange::AWAY: + case OppMarketState::AWAY: me->observed_price = Price(_opp_inside_market().price()); _go_furthest_possible(); break; - case MarketChange::TOWARD: + case OppMarketState::TOWARD: _on_toward_me(); break; } } +// since this is more complicated than the +// other market states void LeanAlgo::_on_toward_me() { switch (_on_toward_behaviour()) { case LeanOrderDefinition_OnToward_CANCEL: @@ -242,7 +243,7 @@ void LeanAlgo::_on_toward_me() { algo().cancel("Opposite inside market moved towards order(detaching)"); break; case LeanOrderDefinition_OnToward_REPRICE: - LOG(OrderMan, Diag, + LOG(OrderMan, Info, "LeanAlgo {} changing its target to {} because opposite moved " "towards order", algo().order_key().value(), _opp_inside_market().price()); @@ -250,7 +251,7 @@ void LeanAlgo::_on_toward_me() { _try_cross(me->observed_price); break; case LeanOrderDefinition_OnToward_NO_CHANGE: - LOG(OrderMan, Diag, "LeanAlgo {} ignoring opposite move towards order", + LOG(OrderMan, Info, "LeanAlgo {} ignoring opposite move towards order", algo().order_key().value()); _try_cross(me->observed_price); break; @@ -259,10 +260,11 @@ void LeanAlgo::_on_toward_me() { break; } } -// this assumes the opposite side is there -// and will always try to cross into the other side -// IF the qty threshold AND chase band condition is met. -// it returns true if it successfully crossed. +// if the price is within the chase bands +// (which is only applied on AWAY prices), +// and the cum qty on the opposite side +// up to the price is less than +// the threshold, then it jumps to that price. bool LeanAlgo::_try_cross(Price price) { if(_within_chase_band(price)){ Quantity cumm_qty; @@ -271,6 +273,13 @@ bool LeanAlgo::_try_cross(Price price) { price, me->tick_size, cumm_qty); + // if we are within the chase bands and + // the price happens to be better than + // the opposite inside market (ie for buy orders + // the price < top sell market) + // then cumm_qty will be 0, which + // means the price will always be modified + // to the arg Quantity trigger_quantity = _cross_threshold(); if(cumm_qty.value()observed_price)){ + // this will be false if the observed price + // is outside the chase OR qty threshold + // is not met 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) + // 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 and it should go at + // that price, see try_cross) auto opp_inside=_opp_inside_market(); if(opp_inside.size()>0){ + // goes to the opp side, improves a tick to get + // to the same market top, and crosses there auto inside = securities::worsen_price(algo().definition().side(), Price(opp_inside.price()), Price(me->tick_size)); diff --git a/src/lib/orderman/orders/algo/algo_orders/LeanAlgo.h b/src/lib/orderman/orders/algo/algo_orders/LeanAlgo.h index 09aea41ba..b258cea51 100644 --- a/src/lib/orderman/orders/algo/algo_orders/LeanAlgo.h +++ b/src/lib/orderman/orders/algo/algo_orders/LeanAlgo.h @@ -21,7 +21,15 @@ class LeanAlgo : public IAlgoOrder { void on_child_change(OrderKey, ChildState const &) override; private: - enum class MarketChange {NO_MARKET,SIZE_CHANGE,AWAY,TOWARD}; + // this is the state of opposite inside market (oim) + // NO_MARKET: oim.qty==0 + // NO_DIRECTIONAL_CHANGE: oim.price==anchor_price + // AWAY: anchor_price is_better_than oim.price + // TOWARD: oim.price is_better_than anchor_price + // since lean order is placed away from the market + // on the same size, AWAY means opp inside moves + // AWAY from the order, similiarly TOWARD + enum class OppMarketState {NO_MARKET,NO_DIRECTIONAL_CHANGE,AWAY,TOWARD}; struct PImpl; enum class Status; IAlgoServices &algo() const ; @@ -34,7 +42,7 @@ class LeanAlgo : public IAlgoOrder { api::Side _opp_side() const; bool _within_chase_band(Price price) const; Price _chase_limit() const; - MarketChange _market_change() const; + OppMarketState _market_state() const; Price _get_price_to_pass (Price price) const; void _analyze_and_act(); bool _try_cross(Price); diff --git a/src/lib/orderman/orders/queue_holder/QueueHolderOrder.cpp b/src/lib/orderman/orders/queue_holder/QueueHolderOrder.cpp index 5c4e7a424..03ebe9f23 100644 --- a/src/lib/orderman/orders/queue_holder/QueueHolderOrder.cpp +++ b/src/lib/orderman/orders/queue_holder/QueueHolderOrder.cpp @@ -24,6 +24,7 @@ _order_builder(), _order_manager(), _services(nullptr), _reported_state(), +_sent_state(), _book(), _state_worker(nullptr), _start_state_worker(this), @@ -120,7 +121,7 @@ void QueueHolderOrder::_switch_state(QueueHolderOrderState new_state) { LOG(OrderMan, Info, "QueueHolderOrder::_switch_state key:{} {}->{}", key(), s0,_state_int()); } -api::orderman::OrderStatus QueueHolderOrder::status(std::string& message) const{ +api::orderman::OrderStatus QueueHolderOrder::_status(std::string& message) const{ QueueHolderOrderState curr_state= _state_worker==nullptr?QueueHolderOrderState::START:_state(); switch (curr_state){ diff --git a/src/lib/orderman/orders/queue_holder/QueueHolderOrder.h b/src/lib/orderman/orders/queue_holder/QueueHolderOrder.h index 1a36c9dc1..6dc798cd3 100644 --- a/src/lib/orderman/orders/queue_holder/QueueHolderOrder.h +++ b/src/lib/orderman/orders/queue_holder/QueueHolderOrder.h @@ -11,6 +11,7 @@ #include "lib/orderman/orders/queue_holder/state_workers/QHOEndStateWorker.h" #include "lib/orderman/orders/queue_holder/QHOOrderManager.h" #include "lib/orderman/orders/OrderOpResult.h" +#include "lib/domain_model/Security.h" namespace bts { namespace api {namespace orderman {class OrderDefinition;}} @@ -83,12 +84,13 @@ private: _termination_reason=termination_reason; _switch_state(QueueHolderOrderState::WAITING_FOR_CANCEL_ALL); } - api::orderman::OrderStatus status(std::string& message) const; + api::orderman::OrderStatus _status(std::string& message) const; // sends orders for the first time void _report_state(){ if(_activated()){ - std::string err_msg; - _reported_state.set_status(status(err_msg)); + std::string& err_msg = *(_reported_state.mutable_last_msg()); + // both status and err_msg are set here + _reported_state.set_status(_status(err_msg)); double filled_price; uint32_t filled_qty; _order_manager.filled_price(filled_price,filled_qty); @@ -104,8 +106,10 @@ private: } _reported_state.set_avg_price(filled_price); _reported_state.set_filled_quantity(filled_qty); - _reported_state.set_last_msg(err_msg); - _services->report_state(_reported_state); + if(!_state_eq()){ + _sent_state=_reported_state; + _services->report_state(_reported_state); + } } } void _set_state_price_qty(Price price, Quantity qty){ @@ -124,6 +128,18 @@ private: oss << str << " key:" << key(); bts_assert_msg(false, oss.str()); } + bool _state_eq() const{ + return _reported_state.status() == _sent_state.status() && + securities::is_same(Price(_reported_state.price()), + Price(_sent_state.price())) && + _reported_state.quantity() == _sent_state.quantity() && + _reported_state.filled_quantity() == _sent_state.filled_quantity() && + securities::is_same(Price(_reported_state.last_price()), + Price(_sent_state.last_price())) && + securities::is_same(Price(_reported_state.avg_price()), + Price(_sent_state.avg_price())) && + _reported_state.last_msg() == _sent_state.last_msg(); + } private: // if the init call succeeded which means // i. order is properly built @@ -138,7 +154,7 @@ private: OrderBuilder _order_builder; QHOOrderManager _order_manager; OrderServices *_services; - api::orderman::OrderState _reported_state; + api::orderman::OrderState _reported_state, _sent_state; Book _book; IQueueHolderOrderStateWorker* _state_worker; QHOStartStateWorker _start_state_worker;