diff --git a/doc/user/content/release_notes/_index.md b/doc/user/content/release_notes/_index.md index 99931f53d..3b1adae92 100644 --- a/doc/user/content/release_notes/_index.md +++ b/doc/user/content/release_notes/_index.md @@ -6,9 +6,14 @@ insert_anchor_links = "right" +++ ## 2.14.0 ### User Visible Changes + - All ladders can now be recentered by (shift or alt) + double clicking over the Price column in a ladder + - Added a Max Order Quantity setting to the Safety Checks tab on the Ladder settings. This setting allows for a user-defined maximum order quantity. + - Added a Price Display Format setting to the Market Price and Size Display tab on the Ladder settings. This setting allows for price levels in the ladder to be displayed without a decimal separator. + - Synthetic instrument creation with 3 legs no longer defaults to butterfly quantites ### Bug Fixes - Fixed an issue where market transition were not observed by IAlgoOrder - Fixed a bug in error reporting + - Fixed a bug in the PnL window where specifying a certain grouping order would lead to a UI failure ## 2.13.0 ### User Visible Changes diff --git a/src/client/spark/Modules/Market/TimeAndSales/TimeAndSalesVM.cs b/src/client/spark/Modules/Market/TimeAndSales/TimeAndSalesVM.cs index e2b5b8139..fac70916b 100644 --- a/src/client/spark/Modules/Market/TimeAndSales/TimeAndSalesVM.cs +++ b/src/client/spark/Modules/Market/TimeAndSales/TimeAndSalesVM.cs @@ -1,6 +1,7 @@ using bts.api; using bts.co2; using bts.collections; +using bts.utils.csv; using mbts.persist; using mbts.spark.filters; using mbts.ui; @@ -52,7 +53,7 @@ namespace mbts.spark { columns.Add(new RenderTextColumn(col_key, r => r[col_key], filter, filter_template, r => _get_aggressor_brush(r)) { id = col_id(col_key), Header = header, Width = width, sort_member_path = sort_member_path, horizontal_alignment = h_alignment } ); - + // be sure to load GridSettings AFTER the columns collection has been populated, the grid settings manager looks columns by id to apply the appropriate settings, // if the collection is not populated, the column settings will not be applied grid_settings_manager = new SimpleGridSettingsManager(columns, new Dictionary { }, row_vms); @@ -173,6 +174,19 @@ namespace mbts.spark { } } + public static System.Collections.Specialized.OrderedDictionary csv_ordered_properties => + CsvHelper.create_ordering_maintainer( + typeof(TimeAndSalesVM.Row), + new string[] { + nameof(security), + nameof(time), + nameof(price), + nameof(size), + nameof(aggressor_side), + nameof(security_key), + }); + + public void raise_invalidated() => invalidated?.Invoke(); } } diff --git a/src/client/spark/Modules/Market/TimeAndSales/TimeAndSalesWindow.cs b/src/client/spark/Modules/Market/TimeAndSales/TimeAndSalesWindow.cs index 85938778a..168d47796 100644 --- a/src/client/spark/Modules/Market/TimeAndSales/TimeAndSalesWindow.cs +++ b/src/client/spark/Modules/Market/TimeAndSales/TimeAndSalesWindow.cs @@ -3,6 +3,7 @@ using bts.api; using bts.shell; using bts.shell.fills; using bts.spark; +using bts.utils.csv; using mbts.co2; using mbts.persist; using mbts.ui; @@ -63,6 +64,7 @@ namespace mbts.spark { var current_smd_source = connectable_builder.create(vm => vm.current_security_md_observable(_bus)).OnDispatcher(); var selected_secs_source = connectable_builder.create(vm => vm.selected_securities_observable()).OnDispatcher(); _commands = new SparkCommand[] { + new SparkCommandCommand("Export to csv", Icons.Export, FileDialogCommand.export_csv(() => _vm.value.row_vms.ToCsv(TimeAndSalesVM.Row.csv_ordered_properties), "TaS")), SparkCommands.ShowLadder(SparkCommands.KeyGestures.ShowLadder).complete(current_smd_source, md => md.HasValue, ConvertUtils.ValueOrDefault), SparkCommands.ShowOrderTicketFromSecurity(SparkCommands.KeyGestures.ShowOrderTicket).complete(current_smd_source, md => md.HasValue, ConvertUtils.ValueOrDefault), SparkCommands.ShowFills(SparkCommands.KeyGestures.ShowFills).complete(selected_secs_source, always_true, get_fills_startup_data), diff --git a/src/client/spark/Modules/Spreader/VM/SyntheticEditorVM.cs b/src/client/spark/Modules/Spreader/VM/SyntheticEditorVM.cs index d6e81bb99..b9c676d9e 100644 --- a/src/client/spark/Modules/Spreader/VM/SyntheticEditorVM.cs +++ b/src/client/spark/Modules/Spreader/VM/SyntheticEditorVM.cs @@ -357,19 +357,13 @@ namespace mbts.spark { if (leg_tuples.Count == 2) { _is_setting_price_mults = true; _price_mult_model.override_value(leg_tuples[1], -1); - } else if (leg_tuples.Count == 3) { - _is_setting_price_mults = true; - _price_mult_model.override_value(leg_tuples[1], -2); - } + } } void _deduce_quantities() { if (leg_tuples.Count == 2) { _is_setting_quantities = true; _quantity_model.override_value(leg_tuples[1], -1); - } else if (leg_tuples.Count == 3) { - _is_setting_quantities = true; - _quantity_model.override_value(leg_tuples[1], -2); } } diff --git a/src/client/spark/Modules/Trading/Fills/FillsVM.cs b/src/client/spark/Modules/Trading/Fills/FillsVM.cs index e370685ea..c13f07e0a 100644 --- a/src/client/spark/Modules/Trading/Fills/FillsVM.cs +++ b/src/client/spark/Modules/Trading/Fills/FillsVM.cs @@ -5,6 +5,7 @@ using bts.collections; using bts.shell.fills; using bts.spark; using bts.utils; +using bts.utils.csv; using mbts.collections; using mbts.persist; using mbts.spark.filters; @@ -23,6 +24,7 @@ using System.Linq; using System.Reactive.Disposables; using System.Reactive.Linq; using System.Windows.Data; +using System.Windows.Input; using System.Windows.Media; using static bts.api.orderman.Fill.Types; using static bts.shell.FillsWindowFactory; @@ -298,6 +300,7 @@ namespace mbts.spark { public FillStatus fill_status => _fill.FillStatus; public string fill_key => _fill.FillKey; public string order_key => _order.Key.ToString(); + public string symbol => fill_tuple.security?.Symbol; // Root Algo public OrderType root_algo_order_type => _root_algo.HasValue ? _root_algo.Value.value.CustomCase : OrderType.None; @@ -309,6 +312,28 @@ namespace mbts.spark { public override bool Equals(object obj) => Equals(obj as Row); public override int GetHashCode() => _fill.FillKey.GetHashCode() ^ _order.Key.GetHashCode(); + public static System.Collections.Specialized.OrderedDictionary csv_ordered_properties => + CsvHelper.create_ordering_maintainer(typeof(Row), + new string[] { + nameof(security), + nameof(symbol), + nameof(order_type), + nameof(root_algo_display_name), + nameof(side), + nameof(fill_time), + nameof(user), + nameof(account), + nameof(exchange), + nameof(time_in_force), + nameof(size), + nameof(price), + nameof(fill_kind), + nameof(fill_status), + nameof(fill_key), + nameof(order_key), + nameof(security_key) + }); + public event Action invalidated; void IRowVM.raise_invalidated() => invalidated?.Invoke(); } diff --git a/src/client/spark/Modules/Trading/Fills/FillsWindow.cs b/src/client/spark/Modules/Trading/Fills/FillsWindow.cs index 090fd86b5..1d16525cd 100644 --- a/src/client/spark/Modules/Trading/Fills/FillsWindow.cs +++ b/src/client/spark/Modules/Trading/Fills/FillsWindow.cs @@ -3,6 +3,7 @@ using bts.api; using bts.shell; using bts.shell.fills; using bts.spark; +using bts.utils.csv; using mbts.persist; using mbts.ui; using mbts.ui.settings; @@ -59,6 +60,7 @@ namespace mbts.spark { _view = new FillsView { DataContext = _vm }; _commands = new List { + new SparkCommandCommand("Export to csv", Icons.Export, FileDialogCommand.export_csv(() => _vm.rows.ToCsv(FillsVM.Row.csv_ordered_properties), "Fills")), // wrap the grid settings view factory in a dialogCommand here since the vm is destroyed/recreated when the security criteria changes SparkCommands.window_settings_command(new DialogCommand(() => { var vm = new ShellSettingsDialogVM( diff --git a/src/client/spark/Modules/Trading/Ladder/LadderSettings.cs b/src/client/spark/Modules/Trading/Ladder/LadderSettings.cs index c025e90ed..30a1059d7 100644 --- a/src/client/spark/Modules/Trading/Ladder/LadderSettings.cs +++ b/src/client/spark/Modules/Trading/Ladder/LadderSettings.cs @@ -249,6 +249,7 @@ namespace mbts.spark { const double _default_order_entry_panel_width = 110.0; const double _default_zoom_factor = 1.0; const bool _default_show_warn_on_cross = true; + const bool _default_enforce_max_clip = false; public static readonly IEqualityComparer profile_equality_comparer = EqualityComparer.Create(profile_equals); // this class is 100% mutable (there are literally 0 readonly members), @@ -282,6 +283,7 @@ namespace mbts.spark { use_defaults = true; favorite_algos = new LadderFavoriteAlgosSettings(null, 2, null); show_warn_on_cross = _default_show_warn_on_cross; + enforce_max_clip = _default_enforce_max_clip; } public static LadderSettings Default { @@ -347,6 +349,8 @@ namespace mbts.spark { zoom_factor = _default_zoom_factor, net_change = NetChangeTerms.None, mini_ob = new LadderMiniOrderBookSettings(bts.shell.orderbook.OrderBookStartupData.default_mini_grid.general), + max_clip = 0, + price_display_format = PriceDisplayFormat.Default, }; rv.row_height = LadderRender.measure_row_height(rv); return rv; @@ -365,6 +369,13 @@ namespace mbts.spark { Ticks } + public enum PriceDisplayFormat { + [Description("Default")] + Default, + [Description("Integer")] + Integer + } + [ProtoMember(1)] public double row_height { get; set; } [ProtoMember(2)] @@ -499,6 +510,15 @@ namespace mbts.spark { [ProtoMember(57)] public double left_panel_scroll_position { get; set; } + [ProtoMember(58), DefaultValue(_default_enforce_max_clip)] + public bool enforce_max_clip { get; set; } + + [ProtoMember(59)] + public uint max_clip { get; set; } + + [ProtoMember(60)] + public PriceDisplayFormat price_display_format { get; set; } + public void sanitize() => sanitize(this); @@ -600,7 +620,10 @@ namespace mbts.spark { a.favorite_algos == b.favorite_algos && a.net_change == b.net_change && a.show_warn_on_cross == b.show_warn_on_cross && - a.mini_ob == b.mini_ob; + a.mini_ob == b.mini_ob && + a.enforce_max_clip == b.enforce_max_clip && + a.max_clip == b.max_clip && + a.price_display_format == b.price_display_format; public bool Equals(LadderSettings other) => profile_equals(this, other) && diff --git a/src/client/spark/Modules/Trading/Ladder/VM/LadderSettingsVM.cs b/src/client/spark/Modules/Trading/Ladder/VM/LadderSettingsVM.cs index 68fffdeb8..22d2a75b5 100644 --- a/src/client/spark/Modules/Trading/Ladder/VM/LadderSettingsVM.cs +++ b/src/client/spark/Modules/Trading/Ladder/VM/LadderSettingsVM.cs @@ -29,7 +29,7 @@ using TextUtils = mbts.ui.utility.text.TextUtils; namespace mbts.spark { class LadderSettingsVM : DisposableViewModelBase, IWindowSettingsVM, IValueFactory, IObservable, ITemplateSelectorKey { readonly Property _badge_style; - readonly Property _alternate_order_size; + readonly Property _alternate_order_size, _max_clip; readonly DelegateProperty _row_height; readonly UserProperty _default_account; readonly UserProperty _default_algo; @@ -41,8 +41,9 @@ namespace mbts.spark { AlgoID? _desired_algo; TimeInForce _default_time_in_force; LadderSettings.NetChangeTerms _price_format; + LadderSettings.PriceDisplayFormat _price_display_format; double _order_entry_panel_width, _zoom_factor; - bool _auto_clear, _show_warn_on_cross; + bool _auto_clear, _show_warn_on_cross, _enforce_max_clip; LadderSettings _current; LadderColumnSettingsVM _orders = new OrdersColumnSettingsVM(), @@ -91,6 +92,7 @@ namespace mbts.spark { _alternate_order_size = backing(nameof(alternate_order_size)); _default_account = user_backing(nameof(default_account)); _default_algo = user_backing(nameof(default_algo)); + _max_clip = backing(nameof(max_clip)); // be sure to initialize backings before this measure_row_height call _row_height = backing(nameof(row_height), () => LadderRender.measure_row_height(get_result())); _orders.font_size_changed += on_font_size_changed; @@ -166,7 +168,9 @@ namespace mbts.spark { public SimpleGridSettingsVM mini_ob { get; } = new SimpleGridSettingsVM(OrderBookGridSettingsManager.hard_column_flags); // price format public LadderSettings.NetChangeTerms price_format { get => _price_format; set => Set(ref _price_format, value); } + public LadderSettings.PriceDisplayFormat price_display_format { get => _price_display_format; set => Set(ref _price_display_format, value); } public IEnumerable price_format_options => EnumHelper.get_values(); + public IEnumerable price_display_format_options => EnumHelper.get_values(); // time in force public TimeInForce default_time_in_force { get => _default_time_in_force; set => Set(ref _default_time_in_force, value); } public IEnumerable time_in_force_options => EnumHelper.get_values_except(TimeInForce.Undefined); @@ -182,6 +186,8 @@ namespace mbts.spark { public double zoom_factor { get => _zoom_factor; set => Set(ref _zoom_factor, value); } // safety checks public bool show_warn_on_cross { get => _show_warn_on_cross; set => Set(ref _show_warn_on_cross, value); } + public bool enforce_max_clip { get => _enforce_max_clip; set => Set(ref _enforce_max_clip, value); } + public uint max_clip { get => _max_clip.Value; set => _max_clip.Value = value; } // favorites public FavoriteAlgosVM favorite_algos_vm { get; } @@ -354,8 +360,11 @@ namespace mbts.spark { _cancel_sells_visibility.show = settings.cancel_sells_visible; _cancel_all_visibility.show = settings.cancel_all_visible; price_format = settings.net_change; + price_display_format = settings.price_display_format; // safety checks show_warn_on_cross = settings.show_warn_on_cross; + enforce_max_clip = settings.enforce_max_clip; + max_clip = settings.max_clip; } } @@ -428,8 +437,11 @@ namespace mbts.spark { clone.cancel_all_visible = _cancel_all_visibility.show; clone.zoom_slider_visible = _zoom_slider_visbility.show; clone.net_change = price_format; + clone.price_display_format = price_display_format; // safety checks clone.show_warn_on_cross = show_warn_on_cross; + clone.enforce_max_clip = enforce_max_clip; + clone.max_clip = max_clip; return clone; } diff --git a/src/client/spark/Modules/Trading/Ladder/VM/LadderVM.cs b/src/client/spark/Modules/Trading/Ladder/VM/LadderVM.cs index 174a14b69..ca85b7b7f 100644 --- a/src/client/spark/Modules/Trading/Ladder/VM/LadderVM.cs +++ b/src/client/spark/Modules/Trading/Ladder/VM/LadderVM.cs @@ -397,6 +397,8 @@ namespace mbts.spark { public uint volume_column_width { get => _volume_column_width.Value; set => _volume_column_width.set(value); } public uint alternate_order_size_from_settings => current_settings.alternate_order_size; public bool show_warn_on_cross_from_settings => current_settings.show_warn_on_cross; + public bool enforce_max_clip_from_settings => current_settings.enforce_max_clip; + public uint max_clip_from_settings => current_settings.max_clip; internal LadderModel model => _model; internal IObservable settings { get; } @@ -447,6 +449,9 @@ namespace mbts.spark { public void key_down(KeyEventArgs e) { if (order_properties_vm == null) return; + if (KeyboardExtensions.IsDown(Key.Space)) { + _bus?.post(SparkTags.RequestRecenterLadder, null); + } // the ctrl modifier requirement helps avoid keyboard-input collisions w/ algo-templates popup if (!KeyboardExtensions.IsCtrlDown()) return; var new_algo = order_properties_vm.algo_definitions.FirstOrDefault(o => o.algo_root.key_match(e)); @@ -462,6 +467,10 @@ namespace mbts.spark { settings_invalidated?.Invoke(); } + public void recenter_all_ladders() { + _bus?.post(SparkTags.RequestRecenterLadder, null); + } + public Task send_order_async((double price, Side? side, MouseButton button) args) { if (order_properties_vm != null && args.button != MouseButton.Middle) { var size_from_alternate = args.button == MouseButton.Right; @@ -470,6 +479,10 @@ namespace mbts.spark { size_calculator.flash_error(); } else { uint size = size_from_alternate ? current_settings.alternate_order_size : (uint)Math.Abs(size_calculator.value ?? 0); + // enforce max clip + if (enforce_max_clip_from_settings && size > max_clip_from_settings) { + size = max_clip_from_settings; + } return send_order_async(args.side.Value, size, args.price); } } diff --git a/src/client/spark/Modules/Trading/Ladder/View/LadderGridHost.cs b/src/client/spark/Modules/Trading/Ladder/View/LadderGridHost.cs index b78519f62..7a51bc6d2 100644 --- a/src/client/spark/Modules/Trading/Ladder/View/LadderGridHost.cs +++ b/src/client/spark/Modules/Trading/Ladder/View/LadderGridHost.cs @@ -350,6 +350,17 @@ namespace mbts.spark { } } else if (_vm != null) { uint size = e.ChangedButton == MouseButton.Right ? _vm.alternate_order_size_from_settings : _vm.size_calculator.value ?? 0; + + // does the size violate the local max clip + if (_vm.enforce_max_clip_from_settings && size > _vm.max_clip_from_settings) { + // note this size is only used for the cross market message, not the actual order command + size = _vm.max_clip_from_settings; + // only update the calculator value when it's a standard left-click order + if (e.ChangedButton == MouseButton.Left) { + _vm.size_calculator.value = _vm.max_clip_from_settings; + } + } + // if warning enabled && (buy above opposite inside market || ask below opposite inside market) // when 1-sided market, _get_top_price will return NaN, and so the price comparison is false // meaning show no warning == correct @@ -479,8 +490,14 @@ namespace mbts.spark { protected override void OnMouseDoubleClick(MouseButtonEventArgs e) { var column = _column_for_point(e.GetPosition(this)); - if (column.column_type == ColumnType.Price) - _scroll_to_center(); + if (column.column_type == ColumnType.Price) { + if (Keyboard.IsKeyDown(Key.LeftShift) || Keyboard.IsKeyDown(Key.RightShift) || + Keyboard.IsKeyDown(Key.LeftAlt) || Keyboard.IsKeyDown(Key.RightAlt)) { + _vm?.recenter_all_ladders(); + } else { + _scroll_to_center(); + } + } } #region Row Utility Methods @@ -588,7 +605,8 @@ namespace mbts.spark { _settings.row_height, _price_list, column.settings, - security.ContractSpec); + security.ContractSpec, + _settings.price_display_format); } break; case ColumnType.Ask: render_market_col(_asks); break; @@ -911,7 +929,7 @@ namespace mbts.spark { var prev_price_list = _price_list; _price_list = (!(_settings.net_change == LadderSettings.NetChangeTerms.None)) ? LadderRender.render_prices(_price_vis_tup.visual, _price_vis_tup.glyph_context, _mkt_break_lines.origin, _vm.md.settlement_price, _settings.net_change == LadderSettings.NetChangeTerms.Ticks, _row_count, _settings.row_height, _settings.price_column, security.ContractSpec) : - LadderRender.render_prices(_price_vis_tup.visual, _price_vis_tup.glyph_context, _mkt_break_lines.origin, _row_count, _settings.row_height, _settings.price_column, security.ContractSpec); + LadderRender.render_prices(_price_vis_tup.visual, _price_vis_tup.glyph_context, _mkt_break_lines.origin, _row_count, _settings.row_height, _settings.price_column, security.ContractSpec, _settings.price_display_format); _ordershost.update_settings(_price_list, _price_comparer, _settings.row_height, _settings.orders_column); if (prev_price_list != null) { // maintain previous visible price range if possible diff --git a/src/client/spark/Modules/Trading/Ladder/View/LadderRender.cs b/src/client/spark/Modules/Trading/Ladder/View/LadderRender.cs index d12c79a6c..c6d5e6a2e 100644 --- a/src/client/spark/Modules/Trading/Ladder/View/LadderRender.cs +++ b/src/client/spark/Modules/Trading/Ladder/View/LadderRender.cs @@ -40,6 +40,8 @@ namespace mbts.spark { // Note: the orders-column has a separate "row_padding" value: Badge.DefaultMargin // (see how it is incorporated in measure_row_height() below) public static readonly Thickness row_padding = new Thickness(6); + const string tick_separator_period = "."; + const string tick_separator_dash = "-"; // IMPORTANT: this method ONLY WORKS if Badges use the BadgeRender.margin/border_thickness/padding values. // TODO: elminate the dependency on BadgeRender.margin/border_thickness/padding by integrating them into settings. @@ -52,8 +54,11 @@ namespace mbts.spark { public static int index_of(double[] prices, double price, IComparer comparer) => Array.BinarySearch(prices, price, comparer); - public static GlyphRun format_text(string text, int row, double row_height, LadderColumnSettings settings, GlyphContext glyph_context) => - glyph_context.get_glyph_run(text, settings.font_size, settings.width, row_height, HorizontalAlignment.Center, 0, VerticalAlignment.Center, row * row_height, true); + public static GlyphRun format_text(string text, int row, double row_height, LadderColumnSettings settings, GlyphContext glyph_context, LadderSettings.PriceDisplayFormat price_display_format = LadderSettings.PriceDisplayFormat.Default) => + glyph_context.get_glyph_run( + // long term there is probably a better way to get rid of the separator, such as in the TickExtensions._format_tick + price_display_format == LadderSettings.PriceDisplayFormat.Integer ? text.Replace(tick_separator_period, string.Empty).Replace(tick_separator_dash, string.Empty) : text, + settings.font_size, settings.width, row_height, HorizontalAlignment.Center, 0, VerticalAlignment.Center, row * row_height, true); public static double[] gen_prices(double mid, int row_count, ContractSpecificationImmutable spec) { // require odd number @@ -79,10 +84,10 @@ namespace mbts.spark { result[i] = format_text(spec.format(prices[i], reference_price, format_in_tick_terms), i, row_height, settings, glyph_context)); return result; } - public static GlyphRun[] format_prices(double[] prices, double row_height, LadderColumnSettings settings, GlyphContext glyph_context, ContractSpecificationImmutable spec) { + public static GlyphRun[] format_prices(double[] prices, double row_height, LadderColumnSettings settings, GlyphContext glyph_context, ContractSpecificationImmutable spec, LadderSettings.PriceDisplayFormat price_display_format) { var result = new GlyphRun[prices.Length]; Parallel.For(0, prices.Length, i => - result[i] = format_text(spec.format(prices[i]), i, row_height, settings, glyph_context)); + result[i] = format_text(spec.format(prices[i]), i, row_height, settings, glyph_context, price_display_format)); return result; } @@ -104,9 +109,9 @@ namespace mbts.spark { } public static double[] render_prices(DrawingVisual price, GlyphContext glyph_context, double mid, int row_count, double row_height, - LadderColumnSettings settings, ContractSpecificationImmutable spec) { + LadderColumnSettings settings, ContractSpecificationImmutable spec, LadderSettings.PriceDisplayFormat price_display_format) { var dprices = gen_prices(mid, row_count, spec); - render_prices(price, glyph_context, row_count, row_height, dprices, settings, spec); + render_prices(price, glyph_context, row_count, row_height, dprices, settings, spec, price_display_format); return dprices; } @@ -122,10 +127,10 @@ namespace mbts.spark { } } - public static void render_prices(DrawingVisual price, GlyphContext glyph_context, int row_count, double row_height, double[] dprices, LadderColumnSettings settings, ContractSpecificationImmutable spec) { + public static void render_prices(DrawingVisual price, GlyphContext glyph_context, int row_count, double row_height, double[] dprices, LadderColumnSettings settings, ContractSpecificationImmutable spec, LadderSettings.PriceDisplayFormat price_display_format) { var foreground = settings.foreground.rgb_brush(); //var background = new SolidColorBrush(settings.background.rgb_color()); - var fprices = format_prices(dprices, row_height, settings, glyph_context, spec); + var fprices = format_prices(dprices, row_height, settings, glyph_context, spec, price_display_format); using (var dc = price.RenderOpen()) using (_draw_with_clip(dc, settings, row_height, row_count)) { //dc.DrawRectangle(background, null, new Rect(0, 0, settings.width, row_count * row_height)); diff --git a/src/client/spark/Modules/Trading/Ladder/View/LadderSettingsView.xaml b/src/client/spark/Modules/Trading/Ladder/View/LadderSettingsView.xaml index 92ab62e4d..21d19bb24 100644 --- a/src/client/spark/Modules/Trading/Ladder/View/LadderSettingsView.xaml +++ b/src/client/spark/Modules/Trading/Ladder/View/LadderSettingsView.xaml @@ -178,6 +178,14 @@ + + @@ -630,7 +638,11 @@ - + + + + + @@ -710,6 +722,7 @@ + + + @@ -991,21 +1013,45 @@ + + + - + + + + + + + + + + + diff --git a/src/client/spark/Modules/Trading/OrderBook/OrderBookRowVM.cs b/src/client/spark/Modules/Trading/OrderBook/OrderBookRowVM.cs index 8644745b1..a4ebe3f3a 100644 --- a/src/client/spark/Modules/Trading/OrderBook/OrderBookRowVM.cs +++ b/src/client/spark/Modules/Trading/OrderBook/OrderBookRowVM.cs @@ -4,6 +4,7 @@ using bts.api.orderman; using bts.collections; using bts.spark; using bts.utils; +using bts.utils.csv; using mbts.ui; using mbts.ui.controls; using System; @@ -11,6 +12,7 @@ using System.Collections.Generic; using System.ComponentModel; using System.Reactive.Linq; using System.Runtime.CompilerServices; +using System.Linq; using System.Windows.Input; using System.Windows.Media; using Columns = mbts.spark.OrderBookGridView.ColumnKeys; @@ -60,6 +62,35 @@ namespace mbts.spark { public event Action<(OrderSecurityRootPair oldval, OrderSecurityRootPair newval)> updated; public event PropertyChangedEventHandler PropertyChanged; + public static System.Collections.Specialized.OrderedDictionary csv_ordered_properties => + CsvHelper.create_ordering_maintainer( + typeof(OrderBookRowVM), + new string[] { + nameof(security_text), + nameof(symbol), + nameof(time_created), + nameof(last_change), + nameof(user), + nameof(account), + nameof(exchange), + nameof(time_in_force), + nameof(order_type), + nameof(root_algo_display_name), + nameof(order_sub_type), + nameof(side), + nameof(quantity), + nameof(filled_quantity), + nameof(price), + nameof(avg_price), + nameof(last_price), + nameof(piq), + nameof(status), + // last message (could contains commas, so skipping) + nameof(security_key), + nameof(order_key), + nameof(parent_order_key), + }); + // Core public OrderSecurityRootPair order_tuple { get; private set; } public OrderRecordImmutable order => order_tuple.order.order; diff --git a/src/client/spark/Modules/Trading/OrderBook/OrderBookWindow.cs b/src/client/spark/Modules/Trading/OrderBook/OrderBookWindow.cs index b416e6937..1692a0140 100644 --- a/src/client/spark/Modules/Trading/OrderBook/OrderBookWindow.cs +++ b/src/client/spark/Modules/Trading/OrderBook/OrderBookWindow.cs @@ -4,6 +4,7 @@ using bts.shell; using bts.shell.fills; using bts.shell.orderbook; using bts.spark; +using bts.utils.csv; using bts.view; using mbts.persist; using mbts.ui; @@ -184,6 +185,7 @@ namespace mbts.spark { show_grid_settings_command.group = CommandGroups.Auxiliary; _commands = new SparkCommand[] { + new SparkCommandCommand("Export to csv", Icons.Export, FileDialogCommand.export_csv(() => _vm.rows.ToCsv(OrderBookRowVM.csv_ordered_properties), "OrderBook")), toggle_show_right_panel_command, attach_selected_orders_command, detach_selected_orders_command, diff --git a/src/client/spark/Modules/Trading/PNL/Settings/VM/PNLSettingsVM.cs b/src/client/spark/Modules/Trading/PNL/Settings/VM/PNLSettingsVM.cs index 47a36196f..518e259a6 100644 --- a/src/client/spark/Modules/Trading/PNL/Settings/VM/PNLSettingsVM.cs +++ b/src/client/spark/Modules/Trading/PNL/Settings/VM/PNLSettingsVM.cs @@ -1,220 +1,223 @@ -using bts.collections; -using bts.utils; -using mbts; -using mbts.collections; -using mbts.expression; -using mbts.spark; -using mbts.ui; -using mbts.ui.settings; -using mbts.ui.shell; -using mbts.ui.spark; -using mbts.ui.utility; -using mbts.utils; -using System; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Collections.Specialized; -using System.Dynamic; -using System.Linq; -using ColumnKeys = bts.shell.pnl.PNLView.Columns; - -namespace bts.shell.pnl { - class PNLSettingsVM : DisposableViewModelBase, IWindowSettingsVM, IValueFactory, IObservable, ITemplateSelectorKey { - readonly IReadOnlyDictionary _anchor_cache; - readonly DeferrableActionWrapper _sync_anchors; - - PNLCalculationType _calculation_type; - PNLHeaderRowDisplay _header_row_display; - PNLSettings _last_loaded; - - public PNLSettingsVM(PNLSettings settings) { - // init anchor cache, deferrable resync - _anchor_cache = PNLSettings.anchorable_columns.ToDictionary(k => k, k => new AnchorItemVM(this, k)); - _sync_anchors = new DeferrableActionWrapper(() => { - for (int i = 0; i < anchor_items.Count; i++) { - anchor_items[i].anchor_index = i + 1; - anchor_items[i].refresh(); - } - }); - core_settings_vm = new SimpleGridSettingsVM(column_factory: col_settings => { - var col_vm = new PNLColumnVM(core_settings_vm, EnumHelper.parse(col_settings.id)); - col_vm.load_from(col_settings); - return col_vm; - }); - core_settings_vm.selection_highlight.bind_opacity_to_alpha = true; - _dispose = Disposable.Create( - anchor_items.Subscribe((s, e) => _sync_anchors.execute())); - load(settings); - } - - public IEnumerable anchor_item_headers => _anchor_cache.Values; - public ObservableCollection anchor_items { get; } = new ObservableCollection(); - public SimpleGridSettingsVM core_settings_vm { get; } - public PNLGroupRowAppearanceVM group_row_defaults { get; } = new PNLGroupRowAppearanceVM(); - public PNLCellAppearanceVM header_row_defaults { get; } = new PNLCellAppearanceVM(); - public PNLCalculationType calculation_type { get => _calculation_type; set => Set(ref _calculation_type, value); } - public IEnumerable calculation_types => EnumHelper.get_values_except(PNLCalculationType.None, PNLCalculationType.Same, PNLCalculationType.Opposite); - public PNLHeaderRowDisplay header_row_display { get => _header_row_display; set => Set(ref _header_row_display, value); } - public IEnumerable header_row_display_options => PNLSettings.header_row_display_options; - - string ITemplateSelectorKey.key => GridSettingsTemplateKeys.PNL; - - public PNLSettings get_result() { - var s = _last_loaded == null ? new PNLSettings() : SparkUtils.clone_proto(_last_loaded); - s.calculation_type = _calculation_type; - s.grid = core_settings_vm.create(); - // move anchor cols to the left, order wrt grouping hierarchy - var new_cols = new Lazy>(() => s.grid.columns.ToList()); - for (int i = 0; i < s.grid.columns.Count; i++) { - var key = s.grid.columns[i].strong_id(); - if (_anchor_cache.TryGetValue(key, out var a) && a.anchor_index.HasValue) { - // anchor index is 1 based, subtract 1 to get 0 based - int anchor_index = a.anchor_index.Value - 1; - if (anchor_index != i && anchor_index >= 0 && anchor_index < s.grid.columns.Count) { - new_cols.Value.RemoveAt(i); - new_cols.Value.Insert(anchor_index, s.grid.columns[i]); - } +using bts.collections; +using bts.utils; +using mbts; +using mbts.collections; +using mbts.expression; +using mbts.spark; +using mbts.ui; +using mbts.ui.settings; +using mbts.ui.shell; +using mbts.ui.spark; +using mbts.ui.utility; +using mbts.utils; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Collections.Specialized; +using System.Dynamic; +using System.Linq; +using ColumnKeys = bts.shell.pnl.PNLView.Columns; + +namespace bts.shell.pnl { + class PNLSettingsVM : DisposableViewModelBase, IWindowSettingsVM, IValueFactory, IObservable, ITemplateSelectorKey { + readonly IReadOnlyDictionary _anchor_cache; + readonly DeferrableActionWrapper _sync_anchors; + + PNLCalculationType _calculation_type; + PNLHeaderRowDisplay _header_row_display; + PNLSettings _last_loaded; + + public PNLSettingsVM(PNLSettings settings) { + // init anchor cache, deferrable resync + _anchor_cache = PNLSettings.anchorable_columns.ToDictionary(k => k, k => new AnchorItemVM(this, k)); + _sync_anchors = new DeferrableActionWrapper(() => { + for (int i = 0; i < anchor_items.Count; i++) { + anchor_items[i].anchor_index = i + 1; + anchor_items[i].refresh(); } - } - // rule-based animations - var trigger_anims = core_settings_vm.columns - .OfType() - .SelectMany(c => c.get_triggers()) - .GroupBy(tup => tup.expression) - .Where(g => CoreExpressionEvaluator.validate(g.Key)) - .Select(g => ( - expression: g.Key, - animations: g.ToArray())) - .ToList(); - - var normalized_anims = trigger_anims - .Where(tup => CoreExpressionEvaluator.validate(tup.expression)) - .ToList(); - - s = s.with(anchors: anchor_items.Select(vm => vm.key), - grid: new_cols.IsValueCreated ? s.grid.with(columns: new_cols.Value) : null, - group_columns: core_settings_vm.columns.OfType().Select(c => { - var col_settings = c.create(); - col_settings = c.group_column_vm.apply_to(col_settings); - return col_settings; - }), - header_columns: core_settings_vm.columns.OfType().Select(c => { - var col_settings = c.create(); - col_settings = c.header_column_vm.apply_to(col_settings); - return col_settings; - }), - animations: trigger_anims.Select( - ta => new PNLAnimationTriggerData { - expression = ta.expression, - animations = Array.ConvertAll(ta.animations, t => t.row) - }), - group_header_animations: normalized_anims - .Select( - ta => new PNLAnimationTriggerData { - expression = ta.expression, - animations = Array.ConvertAll(ta.animations, t => t.group) - }), - header_row_animations: normalized_anims.Select( - ta => new PNLAnimationTriggerData { - expression = ta.expression, - animations = Array.ConvertAll(ta.animations, t => t.header) - })); - s.header_row_display = header_row_display; - s.header_cell_appearance = PNLCellAppearanceProto.from_appearance(header_row_defaults.to_appearance()); - // group - var (group_cell_appearance, group_row_background_colors) = group_row_defaults.create(); - s.group_cell_appearance = PNLCellAppearanceProto.from_appearance(group_cell_appearance); - s.group_background_colors.SetItems(group_row_background_colors.Select(c => c.rgb_color())); - // - return s; - } - - public void load(PNLSettings value) { - _last_loaded = value; - header_row_defaults.load(value.header_cell_appearance.to_appearance()); - group_row_defaults.load_from((value.group_cell_appearance.to_appearance(), value.group_background_colors.WrapSelectorRO(c => c.argb_color()))); - var column_map = _map_column_data(value.grid.columns, value.animations); - var group_column_map = _map_column_data(value.group_columns, value.group_header_animations); - var header_column_map = _map_column_data(value.header_columns, value.header_row_animations); - - core_settings_vm.load_from(value.grid); - - for (int i = 0; i < core_settings_vm.columns.Count; i++) { - var col_vm = core_settings_vm.columns[i] as PNLColumnVM ?? throw new InvalidOperationException($"In {nameof(PNLSettingsVM)}, all columns should be of type {typeof(PNLColumnVM)}."); - var key = EnumHelper.parse(col_vm.id); - var (col_settings, trigger_animations) = column_map[key]; - var group_data = group_column_map.GetNullable(key); - var header_data = header_column_map.GetNullable(key); - col_vm.load_from(col_settings, trigger_animations, group_data?.settings, group_data?.triggers, header_data?.triggers, header_data?.settings); - } - using (_sync_anchors.defer_execution()) - anchor_items.WrapSelector(a => a.key, k => _anchor_cache[k]).sync_with(value.anchors.Intersect(PNLSettings.anchorable_columns)); - header_row_display = value.header_row_display; - calculation_type = value.calculation_type; - } - - PNLSettings IValueFactory.create() => get_result(); - void IValueFactory.load_from(PNLSettings value) => load(value); - IDisposable IObservable.Subscribe(IObserver observer) => throw new NotImplementedException(); - - static Dictionary triggers)> _map_column_data(IEnumerable columns, IEnumerable triggers) { - var map = columns.ToDictionary( - c => c.strong_id(), - c => (settings: c, triggers: new Dictionary())); - foreach (var trig in triggers) { - foreach (var anim in trig.animations) { - if (map.TryGetValue(anim.column, out var col_data)) - col_data.triggers[trig.expression] = anim; - } - } - return map; - } - - void _append_or_remove_anchor(ColumnKeys key, bool include) { - if (!_anchor_cache.TryGetValue(key, out var vm)) - throw new KeyNotFoundException($"Column key '{key}' is not anchorable (expected one of: {string.Join(", ", PNLSettings.anchorable_columns)})."); - if (vm.include == include) - return; - if (include) { - if (anchor_items.Any(a => a.key == key)) - throw new InvalidOperationException($"{nameof(anchor_items)} already contains an element with key '{key}.'"); - anchor_items.Add(vm); - vm.anchor_index = anchor_items.Count; - } else { - if (!anchor_items.Remove(vm)) - throw new InvalidOperationException($"{nameof(anchor_items)} does not contain an element with key '{key}.'"); - vm.anchor_index = null; - } - _sync_anchors.execute(); - } - - public class AnchorItemVM : ViewModelBase, IEquatable { - readonly PNLSettingsVM _owner; - int? _anchor_index; - - public AnchorItemVM(PNLSettingsVM owner, ColumnKeys key) { - _owner = owner; - this.key = key; - } - - public ColumnKeys key { get; } - public bool include { get => anchor_index.HasValue; set => _owner._append_or_remove_anchor(key, value); } - public int? anchor_index { get => _anchor_index; set => Set(ref _anchor_index, value); } - - public void refresh() => - RaisePropertyChanged(nameof(include), nameof(anchor_index)); - - public bool Equals(AnchorItemVM other) => - other != null && key == other.key; - - public override bool Equals(object obj) => - Equals(obj as AnchorItemVM); - - public override int GetHashCode() => - key.GetHashCode(); - - public override string ToString() => - EnumHelper.get_display_name(key); - } - } + }); + core_settings_vm = new SimpleGridSettingsVM(column_factory: col_settings => { + var col_vm = new PNLColumnVM(core_settings_vm, EnumHelper.parse(col_settings.id)); + col_vm.load_from(col_settings); + return col_vm; + }); + core_settings_vm.selection_highlight.bind_opacity_to_alpha = true; + _dispose = Disposable.Create( + anchor_items.Subscribe((s, e) => _sync_anchors.execute())); + load(settings); + } + + public IEnumerable anchor_item_headers => _anchor_cache.Values; + public ObservableCollection anchor_items { get; } = new ObservableCollection(); + public SimpleGridSettingsVM core_settings_vm { get; } + public PNLGroupRowAppearanceVM group_row_defaults { get; } = new PNLGroupRowAppearanceVM(); + public PNLCellAppearanceVM header_row_defaults { get; } = new PNLCellAppearanceVM(); + public PNLCalculationType calculation_type { get => _calculation_type; set => Set(ref _calculation_type, value); } + public IEnumerable calculation_types => EnumHelper.get_values_except(PNLCalculationType.None, PNLCalculationType.Same, PNLCalculationType.Opposite); + public PNLHeaderRowDisplay header_row_display { get => _header_row_display; set => Set(ref _header_row_display, value); } + public IEnumerable header_row_display_options => PNLSettings.header_row_display_options; + + string ITemplateSelectorKey.key => GridSettingsTemplateKeys.PNL; + + public PNLSettings get_result() { + var s = _last_loaded == null ? new PNLSettings() : SparkUtils.clone_proto(_last_loaded); + s.calculation_type = _calculation_type; + s.grid = core_settings_vm.create(); + // move anchor cols to the left, order wrt grouping hierarchy + List new_cols = null; + IEnumerable cols = s.grid.columns; + var sorted_anchors = anchor_items.OrderBy(a => a.anchor_index).ToList(); + for (int i = 0; i < sorted_anchors.Count; i++) { + if (GridSettingsHelper.try_find_column(cols, sorted_anchors[i].key, out var match, out int pos) && pos != i) { + if (new_cols == null) { + new_cols = s.grid.columns.ToList(); + // set cols to new_cols so subsequent position lookups + // take previous column order manipulations into account. + cols = new_cols; + } + new_cols.RemoveAt(pos); + new_cols.Insert(i, match); + } + } + // rule-based animations + var trigger_anims = core_settings_vm.columns + .OfType() + .SelectMany(c => c.get_triggers()) + .GroupBy(tup => tup.expression) + .Where(g => CoreExpressionEvaluator.validate(g.Key)) + .Select(g => ( + expression: g.Key, + animations: g.ToArray())) + .ToList(); + + var normalized_anims = trigger_anims + .Where(tup => CoreExpressionEvaluator.validate(tup.expression)) + .ToList(); + + s = s.with(anchors: anchor_items.Select(vm => vm.key), + grid: new_cols == null ? null : s.grid.with(columns: new_cols), + group_columns: core_settings_vm.columns.OfType().Select(c => { + var col_settings = c.create(); + col_settings = c.group_column_vm.apply_to(col_settings); + return col_settings; + }), + header_columns: core_settings_vm.columns.OfType().Select(c => { + var col_settings = c.create(); + col_settings = c.header_column_vm.apply_to(col_settings); + return col_settings; + }), + animations: trigger_anims.Select( + ta => new PNLAnimationTriggerData { + expression = ta.expression, + animations = Array.ConvertAll(ta.animations, t => t.row) + }), + group_header_animations: normalized_anims + .Select( + ta => new PNLAnimationTriggerData { + expression = ta.expression, + animations = Array.ConvertAll(ta.animations, t => t.group) + }), + header_row_animations: normalized_anims.Select( + ta => new PNLAnimationTriggerData { + expression = ta.expression, + animations = Array.ConvertAll(ta.animations, t => t.header) + })); + s.header_row_display = header_row_display; + s.header_cell_appearance = PNLCellAppearanceProto.from_appearance(header_row_defaults.to_appearance()); + // group + var (group_cell_appearance, group_row_background_colors) = group_row_defaults.create(); + s.group_cell_appearance = PNLCellAppearanceProto.from_appearance(group_cell_appearance); + s.group_background_colors.SetItems(group_row_background_colors.Select(c => c.rgb_color())); + // + return s; + } + + public void load(PNLSettings value) { + _last_loaded = value; + header_row_defaults.load(value.header_cell_appearance.to_appearance()); + group_row_defaults.load_from((value.group_cell_appearance.to_appearance(), value.group_background_colors.WrapSelectorRO(c => c.argb_color()))); + var column_map = _map_column_data(value.grid.columns, value.animations); + var group_column_map = _map_column_data(value.group_columns, value.group_header_animations); + var header_column_map = _map_column_data(value.header_columns, value.header_row_animations); + + core_settings_vm.load_from(value.grid); + + for (int i = 0; i < core_settings_vm.columns.Count; i++) { + var col_vm = core_settings_vm.columns[i] as PNLColumnVM ?? throw new InvalidOperationException($"In {nameof(PNLSettingsVM)}, all columns should be of type {typeof(PNLColumnVM)}."); + var key = EnumHelper.parse(col_vm.id); + var (col_settings, trigger_animations) = column_map[key]; + var group_data = group_column_map.GetNullable(key); + var header_data = header_column_map.GetNullable(key); + col_vm.load_from(col_settings, trigger_animations, group_data?.settings, group_data?.triggers, header_data?.triggers, header_data?.settings); + } + using (_sync_anchors.defer_execution()) + anchor_items.WrapSelector(a => a.key, k => _anchor_cache[k]).sync_with(value.anchors.Intersect(PNLSettings.anchorable_columns)); + header_row_display = value.header_row_display; + calculation_type = value.calculation_type; + } + + PNLSettings IValueFactory.create() => get_result(); + void IValueFactory.load_from(PNLSettings value) => load(value); + IDisposable IObservable.Subscribe(IObserver observer) => throw new NotImplementedException(); + + static Dictionary triggers)> _map_column_data(IEnumerable columns, IEnumerable triggers) { + var map = columns.ToDictionary( + c => c.strong_id(), + c => (settings: c, triggers: new Dictionary())); + foreach (var trig in triggers) { + foreach (var anim in trig.animations) { + if (map.TryGetValue(anim.column, out var col_data)) + col_data.triggers[trig.expression] = anim; + } + } + return map; + } + + void _append_or_remove_anchor(ColumnKeys key, bool include) { + if (!_anchor_cache.TryGetValue(key, out var vm)) + throw new KeyNotFoundException($"Column key '{key}' is not anchorable (expected one of: {string.Join(", ", PNLSettings.anchorable_columns)})."); + if (vm.include == include) + return; + if (include) { + if (anchor_items.Any(a => a.key == key)) + throw new InvalidOperationException($"{nameof(anchor_items)} already contains an element with key '{key}.'"); + anchor_items.Add(vm); + vm.anchor_index = anchor_items.Count; + } else { + if (!anchor_items.Remove(vm)) + throw new InvalidOperationException($"{nameof(anchor_items)} does not contain an element with key '{key}.'"); + vm.anchor_index = null; + } + _sync_anchors.execute(); + } + + public class AnchorItemVM : ViewModelBase, IEquatable { + readonly PNLSettingsVM _owner; + int? _anchor_index; + + public AnchorItemVM(PNLSettingsVM owner, ColumnKeys key) { + _owner = owner; + this.key = key; + } + + public ColumnKeys key { get; } + public bool include { get => anchor_index.HasValue; set => _owner._append_or_remove_anchor(key, value); } + public int? anchor_index { get => _anchor_index; set => Set(ref _anchor_index, value); } + + public void refresh() => + RaisePropertyChanged(nameof(include), nameof(anchor_index)); + + public bool Equals(AnchorItemVM other) => + other != null && key == other.key; + + public override bool Equals(object obj) => + Equals(obj as AnchorItemVM); + + public override int GetHashCode() => + key.GetHashCode(); + + public override string ToString() => + EnumHelper.get_display_name(key); + } + } } \ No newline at end of file diff --git a/src/client/spark/Modules/Trading/PNL/VM/PNLRowComparer.cs b/src/client/spark/Modules/Trading/PNL/VM/PNLRowComparer.cs index 0932b01db..9d88699da 100644 --- a/src/client/spark/Modules/Trading/PNL/VM/PNLRowComparer.cs +++ b/src/client/spark/Modules/Trading/PNL/VM/PNLRowComparer.cs @@ -90,12 +90,11 @@ namespace bts.shell.pnl { } int? _try_compare_groups(CollectionViewGroup x, CollectionViewGroup y) { - if (x == null || y == null) - return null; - var xcell = (IPNLCellData)x.Name; - var ycell = (IPNLCellData)y.Name; - var comp = _get_column_comparer(xcell.column); - return comp.value_comparer.Compare(xcell.value, ycell.value); + if (x?.Name is IPNLCellData xcell && y?.Name is IPNLCellData ycell) { + var comp = _get_column_comparer(xcell.column); + return comp.value_comparer.Compare(xcell.value, ycell.value); + } + return null; } } -} \ No newline at end of file +} diff --git a/src/client/spark/Modules/Trading/PNL/View/PNLView.xaml b/src/client/spark/Modules/Trading/PNL/View/PNLView.xaml index f30696473..3109114d0 100644 --- a/src/client/spark/Modules/Trading/PNL/View/PNLView.xaml +++ b/src/client/spark/Modules/Trading/PNL/View/PNLView.xaml @@ -698,8 +698,8 @@ c:DataGridFilterProperties.FilterActive="{Binding DataContext.security_filter.active, Source={u:DirectReference _grid}}" c:DataGridFilterProperties.FilterOpen="{Binding DataContext.security_filter.open, Source={u:DirectReference _grid}}" key="Security" - sort_member_path="security_cell.cell_data" - data_member_path="security" + data_member_path="security_cell.cell_data" + sort_member_path="security" HeaderTemplate="{StaticResource AnchorableColumnHeaderTemplate}" /> diff --git a/src/client/spark/core/Utility/MiscUtils.cs b/src/client/spark/core/Utility/MiscUtils.cs index 047eff9f3..4aa6074c8 100644 --- a/src/client/spark/core/Utility/MiscUtils.cs +++ b/src/client/spark/core/Utility/MiscUtils.cs @@ -102,14 +102,14 @@ namespace mbts.utils string identifier = ((felem.Name != null) && (felem.Name.Length > 0)) ? felem.Name : felem.GetType().ToString(); - return "$FrameworkElement [{identifier}]"; + return $"FrameworkElement [{identifier}]"; } else { // Maybe a FrameworkContentElement has focus if (elem is FrameworkContentElement fcelem) { string identifier = ((fcelem.Name != null) && (fcelem.Name.Length > 0)) ? fcelem.Name : fcelem.GetType().ToString(); - return "$FrameworkContentElement [{identifier}]"; + return $"FrameworkContentElement [{identifier}]"; } return $"Element of type [{elem.GetType().ToString()}] has focus"; } diff --git a/src/client/spark/view/Extensions/Command/FileDialogCommand.cs b/src/client/spark/view/Extensions/Command/FileDialogCommand.cs index 7b0778f1a..7889416f9 100644 --- a/src/client/spark/view/Extensions/Command/FileDialogCommand.cs +++ b/src/client/spark/view/Extensions/Command/FileDialogCommand.cs @@ -64,6 +64,25 @@ namespace mbts.ui { } }, can_execute == null ? null : new Func(_ => can_execute())); + public static IDialogCommand export_csv( + Func get_file_content, + string source_window_name) => + new AnonymousFileDialogCommand(_ => + _create_save_file_dialog( + Environment.GetFolderPath(Environment.SpecialFolder.Desktop), + $"BTS_Spark_{source_window_name}_{DateTime.Now.ToString("yyyyMMdd_HHmm")}.csv", + new[] { ("CSV (comma delimited)", new string[] { "csv" }) } + ), + (_, file) => { + try { + File.WriteAllText(file, get_file_content.Invoke()); + } catch (Exception ex) { + BTSMessageBox.Show($"Error exporting data to csv: {ex}.", "CSV Export Error", BTSMessageBoxButtons.OK, System.Windows.MessageBoxImage.Error, true, false, true); + } + }, + // we are always able to perform an export, even when no rows (it will just be a header) + (_) => true); + static TDialog _create_file_dialog(string initial_dir = null, IReadOnlyList<(string name, string[] extensions)> filter_items = null) where TDialog : FileDialog, new() { var rv = new TDialog(); if (!string.IsNullOrEmpty(initial_dir)) diff --git a/src/client/spark_core/utils/CsvHelper.cs b/src/client/spark_core/utils/CsvHelper.cs new file mode 100644 index 000000000..2b4fdfbe9 --- /dev/null +++ b/src/client/spark_core/utils/CsvHelper.cs @@ -0,0 +1,52 @@ +using System; +using System.IO; +using System.Collections.Generic; +using System.Collections.Specialized; +using System.Linq; +using System.Reflection; + +namespace bts.utils.csv { + public static class CsvHelper { + + public static string ToCsv(this IEnumerable items, OrderedDictionary properties = null) where T : class { + var output = ""; + var delimiter = ","; + if (properties == null) { + properties = new OrderedDictionary(); + foreach (var pi in typeof(T).GetProperties()) { + properties.Add(pi.Name, pi); + } + } + + using (var sw = new StringWriter()) { + var dict_values = properties.Values.OfType(); + var header = dict_values.Select(n => n.Name).Aggregate((first, second) => first + delimiter + second); + sw.WriteLine(header); + foreach (var i in items) { + var row = dict_values.Select(x => x.GetValue(i, null)) + .Select(x => x == null ? "null" : x.ToString()) + .Aggregate((first, second) => first + delimiter + second); + sw.WriteLine(row); + } + output = sw.ToString(); + } + return output; + } + + public static OrderedDictionary create_ordering_maintainer(Type t, string[] property_names_in_order) { + OrderedDictionary od = new OrderedDictionary(); + var props = t.GetProperties(); + foreach (var n in property_names_in_order) { + var query = props.Where(pi => pi.Name == n); + if (query.Any()) { + var property_info = query.First(); + if (!od.Contains(property_info)) { + od.Add(n, property_info); + } + } + } + return od; + } + + } +} diff --git a/src/lib/config/defaults/Symbols.conf b/src/lib/config/defaults/Symbols.conf index 93b7126d9..9f4d0f77a 100644 --- a/src/lib/config/defaults/Symbols.conf +++ b/src/lib/config/defaults/Symbols.conf @@ -96,6 +96,10 @@ Symbols { future: @SymbolLists.list[GLBX].symbol spread: @SymbolLists.list[GLBX].symbol } + simice { + future: @SymbolLists.list[ICE].symbol + spread: @SymbolLists.list[ICE].symbol + } } } @@ -106,6 +110,10 @@ Symbols { future: @SymbolLists.list[GLBX].symbol spread: @SymbolLists.list[GLBX].symbol } + ice { + future: @SymbolLists.list[ICE].symbol + spread: @SymbolLists.list[ICE].symbol + } } } diff --git a/src/sdk/Dockerfile b/src/sdk/Dockerfile index 3da602c57..3da5c5045 100644 --- a/src/sdk/Dockerfile +++ b/src/sdk/Dockerfile @@ -12,19 +12,22 @@ env SDK_ROOT=/sdk \ SDK_VERSION=$SDK_VERSION \ SDK_BUILD_DATE=$SDK_BUILD_DATE -# copy sdk -COPY include/ /sdk/include/ -COPY lib/ /sparkbin/ -COPY externals /sdk/externals/ -COPY spark.conf /sparkdata/conf/ -COPY futures.coconut /sparkdata/data/replay/futures.coconut - # add user bts RUN groupadd --gid 1000 $USERNAME && \ useradd -s /bin/bash --uid 1000 --gid 1000 -m $USERNAME && \ + mkdir -p /sparkbin/plugins && \ + mkdir /sparkdata && \ ln -s /sparkbin/ sdk/lib && \ echo $USERNAME ALL=\(root\) NOPASSWD:ALL > /etc/sudoers.d/$USERNAME && \ chmod 0440 /etc/sudoers.d/$USERNAME && \ chown -R bts.bts /sparkbin/plugins && \ chown -R bts.bts /sparkdata +# copy sdk +COPY include/ /sdk/include/ +COPY lib/ /sparkbin/ +COPY externals /sdk/externals/ +COPY spark.conf /sparkdata/conf/ +COPY --chown=$USERNAME futures.coconut /sparkdata/data/replay/futures.coconut + + diff --git a/src/server/sparkd/md/platforms/ice_onixs/ICEListener.h b/src/server/sparkd/md/platforms/ice_onixs/ICEListener.h index b73cf1c49..cd7001d41 100644 --- a/src/server/sparkd/md/platforms/ice_onixs/ICEListener.h +++ b/src/server/sparkd/md/platforms/ice_onixs/ICEListener.h @@ -212,30 +212,32 @@ void ICEListener::on_uds_future_spread(const Definition& def, bool& is_intereste fsec.alt_symbol(def.strategySymbol); const auto& legs = def.legs; - fsec.set_leg_count(legs.size()); - for(size_t x = 0; x < fsec.leg_count(); ++x) - { - const auto& leg = legs[x]; - if(leg.ratioPriceNumerator && leg.ratioPriceDenominator) + if (legs.size() > 0) { + fsec.set_leg_count(legs.size()); + for(size_t x = 0; x < fsec.leg_count(); ++x) { - auto num = *leg.ratioPriceNumerator; - auto denom = *leg.ratioPriceDenominator; - fsec.legs[x].leg_price = num / (double) denom; + const auto& leg = legs[x]; + if(leg.ratioPriceNumerator && leg.ratioPriceDenominator) + { + auto num = *leg.ratioPriceNumerator; + auto denom = *leg.ratioPriceDenominator; + fsec.legs[x].leg_price = num / (double) denom; + } + if(leg.ratioQtyNumerator && leg.ratioQtyDenominator) + { + auto num = *leg.ratioQtyNumerator; + auto denom = *leg.ratioQtyDenominator; + fsec.legs[x].leg_delta = num / (double) denom; + } + + fsec.legs[x].leg_quantity = leg.ratio; + fsec.legs[x].leg_side = leg.side == onixs_ice::Side::Bid ? api::SIDE_BUY : api::SIDE_SELL; + fsec.legs[x].exchange_key = ExchangeKey(leg.marketId); + fsec.legs[x].key = invalid_security_key; } - if(leg.ratioQtyNumerator && leg.ratioQtyDenominator) - { - auto num = *leg.ratioQtyNumerator; - auto denom = *leg.ratioQtyDenominator; - fsec.legs[x].leg_delta = num / (double) denom; - } - - fsec.legs[x].leg_quantity = leg.ratio; - fsec.legs[x].leg_side = leg.side == onixs_ice::Side::Bid ? api::SIDE_BUY : api::SIDE_SELL; - fsec.legs[x].exchange_key = ExchangeKey(leg.marketId); - fsec.legs[x].key = invalid_security_key; + add_security(fsec); + is_interested = true; } - add_security(fsec); - is_interested = true; } diff --git a/testing/manual/settings/Ladder_MaxClip.txt b/testing/manual/settings/Ladder_MaxClip.txt new file mode 100644 index 000000000..f4757c100 --- /dev/null +++ b/testing/manual/settings/Ladder_MaxClip.txt @@ -0,0 +1,41 @@ +1. Verify you can place orders +Launch a Ladder +Place a 10 lot order away from the market and make sure the order is not rejected +Cancel the order + +2. Verify the Max Order Quantity limit works +Click on the Settings button +Click on the Safety Checks tab +Click on the checkbox next to Max Order Quantity and specify 5 + You should additionally observe that the text has gone from a disabled appearance to active + The ticker box is also now active +Hit apply +Back in the ladder, attempt to place another 10 lot order away from the market. You should observe the following: + You are now working a 5 lot order + The qty in the qty box additionally reads 5 +Cancel the 5 lot order + +3. Verify the Max Order Quantity when disabled allows you to place a 10 lot order +This is essentially the same as step 1, except now we're explicitly unchecking the checkbox, ergo... +Uncheck the Max Order Quantity chechbox and observe that: + The Max order quantity text is disabled + The ticker box is disabled +Click Apply +In the ladder, click the 5 button so that your qty box reads 10, which is a quantity greater than the disabled 5 + A 10 lot order should now be working +Cancel the 10 lot order. + +4. Right click / Alternate order qty respects the limit +Re-enable the Max Order Quantity (5 is still fine) +On the Order Quantities tab, specify 7 as your 'Single Click' Quantity +In the ladder, Right click to work an order attempting to use your single click quantity + You should be working a a 5 lot order now i.e. your max order quantity + Observe that the qty box did NOT update with your alternate order quantity + +5. Cross market alert communicates respects the limit +Back on the Safety Checks tab, make sure Warn on Market Cross is checked +Attempt to place a 10 lot bid order (higher than your max of 5) on the sell side of the market + You should observe the message respects your max order quantity and warns you about buying 5 + Feel free to click whichever button you desire on the warning dialog + +FIN diff --git a/testing/manual/settings/Ladder_PriceDisplayFormat.txt b/testing/manual/settings/Ladder_PriceDisplayFormat.txt new file mode 100644 index 000000000..d7f4174e1 --- /dev/null +++ b/testing/manual/settings/Ladder_PriceDisplayFormat.txt @@ -0,0 +1,12 @@ +Launch an ES Ladder (i.e. an instrument whose separator is the .) + Observe the ladder prices are in fact separated by a decimal point +Launch a ZT ladder (i.e. an instrument whose separator is the -) + Observe the ladder prices are in fact separated by a dash +Perform the following in each: + Click Settings + Go to Market Price and Size Display tab + Click on Integer under Price Display Format + Click Apply + Observe that the separator disappears when you do this + Feel free to go back and forth several times + diff --git a/testing/manual/settings/Ladder_RecenterAll.txt b/testing/manual/settings/Ladder_RecenterAll.txt new file mode 100644 index 000000000..c7c6d5018 --- /dev/null +++ b/testing/manual/settings/Ladder_RecenterAll.txt @@ -0,0 +1,6 @@ +1. Verify pressing the shift or alt key while double clicking in the Price column in a Ladder Window recenters ALL ladders +Launch 2 ladders +Scroll both ladders so they are no longer centered at mid market +Press the shift + double click while over the Price column + You should observe both scrolled ladders are now centered once again + The countdown timer is also reset via this spacebar action. This is more informational; I don't expect you to wait to verify that the timer is reset. \ No newline at end of file