diff --git a/src/client/spark/Modules/Trading/Ladder/VM/LadderVM.cs b/src/client/spark/Modules/Trading/Ladder/VM/LadderVM.cs index 6552d7c17..399af1473 100644 --- a/src/client/spark/Modules/Trading/Ladder/VM/LadderVM.cs +++ b/src/client/spark/Modules/Trading/Ladder/VM/LadderVM.cs @@ -1,931 +1,932 @@ -#nullable enable -namespace mbts.spark { - using bts.api; - using bts.api.core; - using bts.api.orderman; - using bts.collections; - using bts.proto; - using bts.shell; - using bts.spark; - using bts.utils; - - using mbts.co2; - using mbts.spark.utilities; - using mbts.ui; - using mbts.ui.shell; - using mbts.ui.utility; - using mbts.user.settings; - using mbts.utils; - - using Spark.Api.Orders; - using Spark.Api.Position; - using Spark.Core; - using Spark.Core.Collections; - using Spark.Core.Data; - using Spark.Core.Disposables; - using Spark.Core.Reactive; - using Spark.Trading; - using Spark.ViewModel.Commands; - using Spark.ViewModel.Trading; - - using System; - using System.Collections.Generic; - using System.Collections.Immutable; - using System.Collections.ObjectModel; - using System.Collections.Specialized; - using System.Diagnostics.CodeAnalysis; - using System.Linq; - using System.Reactive.Linq; - using System.Threading.Tasks; - using System.Windows.Input; - using System.Windows.Media; - - class LadderVM : DisposableViewModelBase, IWillLetYouKnowWhenIDispose, IKeyListener { - static readonly Brush _transparent_status_brush = BTSColors.UI.transparent; - - readonly IBus _bus; - readonly LadderModel _model; - readonly IEqualityComparer _equality; - readonly Dictionary _slot_price_vs_orders; - readonly ObservableCollection _fair_value_line_inputs = new(); - - readonly Property _bid_price; - readonly Property _ask_price; - readonly Property _mid_price; - readonly Property _session_high; - readonly Property _session_low; - readonly Property _day_change; - readonly Property _open; - readonly Property _settlement; - readonly Property _theo; - readonly Property _delta; - readonly Property _vega; - readonly Property _left_panel_width; - readonly Property _zoom_factor; - readonly Property _orders_column_width; - readonly Property _bid_column_width; - readonly Property _price_column_width; - readonly Property _ask_column_width; - readonly Property _last_column_width; - readonly Property _volume_column_width; - readonly Property _piq_column_width; - readonly Property _volume; - readonly Property _auto_clear; - readonly PropertyAutoWrapper _show_account; - readonly PropertyAutoWrapper _show_tif; - readonly PropertyAutoWrapper _show_order_type; - readonly PropertyAutoWrapper _show_size_preset; - readonly PropertyAutoWrapper _show_auto_clear; - readonly PropertyAutoWrapper _show_clear; - readonly PropertyAutoWrapper _show_cancel_buys; - readonly PropertyAutoWrapper _show_cancel_sells; - readonly PropertyAutoWrapper _show_cancel_all; - readonly PropertyAutoWrapper _show_zoom; - readonly PropertyAutoWrapper _show_status_message; - readonly PropertyAutoWrapper _bid_background; - readonly PropertyAutoWrapper _bid_foreground; - readonly PropertyAutoWrapper _ask_background; - readonly PropertyAutoWrapper _ask_foreground; - readonly Property _status; - readonly Property _status_brush; - - double _position; - double _day_position; - double _raw_day_position; - double _left_panel_extent_height; - double _left_panel_view_port_height; - double _left_panel_scroll_position; - double _left_panel_scroll_position_target; - bool _show_account_position; - bool _show_day_position; - bool _show_raw_day_position; - ulong _misc_time = 0; - ulong _last_trade_time = 0; - ulong _last_bbo_time = 0; - IReadOnlyDictionary _cache = DictionaryHelper.empty(); - ImmutableDictionary _favorite_algo_metadata_map = - ImmutableDictionary.Empty; - RegionalTickFactors? _spec; - - LadderVM( - IBus bus, - LadderModel model, - LadderSettings init, - IObservable settings, - OrderPropertiesEditorVM? order_properties_vm = null - ) { - _bus = bus; - _model = model; - current_settings = init; - this.settings = settings; - _equality = TickUtils.tick_equality_comparer(_model.security.ContractSpec); - display_quantity_divisor = model.sec_meta_store.get_qty_display_divisor(security); - size_calculator.display_divisor = display_quantity_divisor; - size_calculator.display_settings = model.security_md.quantity_display; - _slot_price_vs_orders = new Dictionary(_equality); - this.order_properties_vm = order_properties_vm; - _session_high = backing(nameof(session_high), double.NaN); - _session_low = backing(nameof(session_low), double.NaN); - _day_change = backing(nameof(day_change), double.NaN); - _open = backing(nameof(open), double.NaN); - _settlement = backing(nameof(settlement), double.NaN); - _bid_price = backing(nameof(bid_price), double.NaN); - _ask_price = backing(nameof(ask_price), double.NaN); - _mid_price = backing( - nameof(mid_price), - _bid_price.observe_current().CombineLatest(_ask_price.observe_current(), (bid, ask) => { - if (bid.is_nan()) { - return ask; - } - if (ask.is_nan()) { - return bid; - } - var res = (bid + ask) * 0.5; - res = spec.round_to_tick(res); - return res; - })); - _theo = backing(nameof(theo), double.NaN); - _delta = backing(nameof(delta), double.NaN); - _vega = backing(nameof(vega), double.NaN); - - // init window-specific settings: these properties should not observe settings updates; - // they are independent from the settings dialog, so it doesn't make sense that the - // settings dialog should cause them to change. - var ws = init.get_window_specifics(); - _orders_column_width = backing(nameof(orders_column_width), ws.orders_column_width); - _bid_column_width = backing(nameof(bid_column_width), ws.bid_column_width); - _price_column_width = backing(nameof(price_column_width), ws.price_column_width); - _ask_column_width = backing(nameof(ask_column_width), ws.ask_column_width); - _last_column_width = backing(nameof(last_column_width), ws.last_column_width); - _piq_column_width = backing(nameof(piq_column_width), ws.piq_column_width); - _volume_column_width = backing(nameof(volume_column_width), ws.volume_column_width); - _left_panel_width = backing(nameof(left_panel_width), ws.order_entry_panel_width); - _zoom_factor = backing(nameof(zoom_factor), ws.zoom_factor); - _left_panel_scroll_position_target = init.left_panel_scroll_position; - // remember: account_positions needs to subscribe to selected_account; both the sub and - // account_positions need to be disposed - _volume = backing(nameof(volume), 0ul); - _auto_clear = backing(nameof(auto_clear), init.auto_clear); - _status = backing(nameof(status_message), ""); - _status_brush = backing(nameof(status_background), _transparent_status_brush); - go_to_price_cmd = new DelegateCommand(p => request_go_to_price?.Invoke(p)); - - // All settings observers should be aggregated together, so they can all share the same - // subscription to the settings (these subscriptions are not horribly expensive, but - // they're not free either - even more so with the .OnDispatcher() extension). - var settings_observer = new CompositeObserver { - /// first things first: assign our - s => current_settings = s, - // brush props - (_bid_background = brush_prop(nameof(bid_background), s => s.bid_column.background)).set, - (_bid_foreground = brush_prop(nameof(bid_foreground), s => s.bid_column.foreground)).set, - (_ask_background = brush_prop(nameof(ask_background), s => s.ask_column.background)).set, - (_ask_foreground = brush_prop(nameof(ask_foreground), s => s.ask_column.foreground)).set, - // bool visibility props - (_show_account = bool_prop(nameof(show_account), s => s.account_visible)).set, - (_show_tif = bool_prop(nameof(show_tif), s => s.tif_visible)).set, - (_show_order_type = bool_prop(nameof(show_order_type), s => s.order_type_visible)).set, - (_show_size_preset = bool_prop(nameof(show_size_preset), s => s.size_presets_visible)).set, - (_show_auto_clear = bool_prop(nameof(show_auto_clear), s => s.auto_clear_visible)).set, - (_show_clear = bool_prop(nameof(show_clear), s => s.clear_visible)).set, - (_show_cancel_buys = bool_prop(nameof(show_cancel_buys), s => s.cancel_buys_visible)).set, - (_show_cancel_sells = bool_prop(nameof(show_cancel_sells), s => s.cancel_sells_visible)).set, - (_show_cancel_all = bool_prop(nameof(show_cancel_all), s => s.cancel_all_visible)).set, - (_show_zoom = bool_prop(nameof(show_zoom), s => s.zoom_slider_visible)).set, - (_show_status_message = bool_prop(nameof(show_status_message), s => s.status_message_visible)).set, - s => { - // invalidate spec in case 'ticks per row' changed - _spec = null; - if ( - Set(ref _show_account_position, s.account_position_visible, nameof(show_account_position)) | - Set(ref _show_day_position, s.day_position_visible, nameof(show_day_position)) | - Set(ref _show_raw_day_position, s.raw_day_position_visible, nameof(show_raw_day_position))) { - RaisePropertyChanged(nameof(position_display_text)); - } - size_calculator.buttons = s.calculator_buttons; - _auto_clear.set(s.auto_clear); - // column widths - _orders_column_width.set(s.orders_column.width); - _bid_column_width.set(s.bid_column.width); - _price_column_width.set(s.price_column.width); - _ask_column_width.set(s.ask_column.width); - _last_column_width.set(s.last_column.width); - _piq_column_width.set(s.piq_column.width); - _volume_column_width.set(s.volume_column.general.width); - // left panel/zoom - // bid price - bid_price_style.load_from(s.panel_price_point_settings.bid_price); - bid_price_style.show = s.bid_price_visible; - // ask price - ask_price_style.load_from(s.panel_price_point_settings.ask_price); - ask_price_style.show = s.ask_price_visible; - // mid price - mid_price_style.load_from(s.panel_price_point_settings.mid_price); - mid_price_style.show = s.mid_price_visible; - // day - day_change_style.load_from(s.panel_price_point_settings.day_change); - day_change_style.show = s.day_visible; - // open - open_style.load_from(s.panel_price_point_settings.open); - open_style.show = s.open_visible; - // session low - session_low_style.load_from(s.panel_price_point_settings.session_low); - session_low_style.show = s.low_visible; - // session high - session_high_style.load_from(s.panel_price_point_settings.session_high); - session_high_style.show = s.high_visible; - // settlement - settlement_style.load_from(s.panel_price_point_settings.settlement); - settlement_style.show = s.settle_visible; - // theo - theo_style.load_from(s.panel_price_point_settings.theo); - theo_style.show = s.theo_visible; - // delta - delta_style.load_from(s.panel_price_point_settings.delta); - delta_style.show = s.delta_visible; - // vega - vega_style.load_from(s.panel_price_point_settings.vega); - vega_style.show = s.vega_visible; - // volume - volume_style.load_from(s.panel_price_point_settings.volume); - volume_style.show = s.volume_visible; - // left panel gen display - _left_panel_width.set(s.order_entry_panel_initial_width); - _zoom_factor.set(s.zoom_factor); - RaisePropertyChanged(nameof(day_change_font_color), nameof(day_change_background_color)); - // fair value lines - _fair_value_line_inputs.sync_with(s.fair_value_lines.Distinct()); - } - }; - - position_click_cmd = new Command( - () => { - var pos = _show_day_position ? day_position : - (_show_raw_day_position ? _raw_day_position : position); - size_calculator.value = pos.abs(); - }); - send_order_cmd = new AsyncCommand<(double price, Side? side, MouseButton button)>(send_order_async); - rfq_vm = new(security.Id); - rfq_vm.request_commit += _send_rfq; - cancel_cmd = new AsyncCommand(_model.cancel_orders, true); - show_book_cmd = new Command(_show_book); - show_ticket_cmd = new Command(_show_ticket); - settings_cmd = new Command(() => request_settings_dialog?.Invoke()); - - var orders_source = settings.Select(s => s.ticks_per_row).DistinctUntilChanged() - .SelectSeries(tpr => { - var spec = TickUtils.multiply_tick_size(security.regional_ticks(), tpr); - var price_comp = Comparer.Create((a, b) => - Comparer.Default.Compare(spec.count_ticks(a), spec.count_ticks(b))); - return _order_price_source(model.orders, price_comp, p => TickUtils.normalize_price(spec, p)); - }); - _day_change.Changed += (o, n) => RaisePropertyChanged( - nameof(day_change_font_color), nameof(day_change_background_color)); - - _dispose = Disposable.Create( - settings.OnDispatcher().Subscribe(settings_observer), - get_order_properties_editor_hooks(), - bus.subscribe(SparkTags.LogActivity).OnDispatcher().Subscribe(status_update), - model.greeks.OnDispatcher().Subscribe(g => { - _theo.set(g.normalized_theo); - _delta.set(g.delta); - _vega.set(g.vega); - }), - ObservableAutoWrapper.connect( - _fair_value_line_inputs, - fair_value_lines, - fvl => { - var key = new FairValueKey() { - security_id = fvl.security_key ?? security.Id, - type = fvl.price_type - }; - return new FairValueLineVM(key, _model.fair_value_model.get_price_source(key)) { - settings = fvl.display - }; - }), - orders_source.OnDispatcher().Subscribe(tup => { - _cache = tup.map; - /// remove empty price slots (the vm will be disposed automatically when it is - /// removed from ) - var removed_prices = _slot_price_vs_orders.Keys.Except(tup.price_index.Keys).ToList(); - foreach (var p in removed_prices) { - _slot_price_vs_orders.Remove(p); - } - // add or update current price slots - foreach (var kv in tup.price_index) { - _slot_price_vs_orders.AddOrUpdate( - kv.Key, - _ => new LadderOrderVM( - kv.Value, kv.Key, this, settings.Select(s => s.badge_style)), - (_, order_vm) => order_vm.sync_orders(kv.Value)); - } - // sync the collection - orders.sync_with(_slot_price_vs_orders.Values); - // update badge colors, text, etc. - foreach (var o in orders) { - o.update(); - } - }), - WorkLoop.Start($"Ladder '{security}'", _tick), - ObservableAutoWrapper.dispose_on_removed(orders, true), - Disposable.Create(() => _on_disposed_impl?.Invoke(true))); - - PropertyAutoWrapper bool_prop( - string name, Func get_bool) => - backing(name, init, get_bool, EqualityComparer.Create(get_bool)); - - PropertyAutoWrapper brush_prop( - string name, Func get_color_uint) { - var comp = EqualityComparer.Create(get_color_uint); - return backing(name, init, s => get_color_uint(s).rgb_brush(), comp); - } - - IDisposable get_order_properties_editor_hooks() { - if (order_properties_vm is null) { - return Disposable.empty; - } - var position_src = order_properties_vm.observe_account(true) - .Select(a => a?.name ?? string.Empty) - .SelectSeries(a => _model.position_model.on_security_positions(security.Id) - .Select(table => table.state.Values.FirstOrDefault( - pos => pos.Item2.Account == a, - tup => tup.Item2, (bts.api.position.PositionUnitImmutable?)null))); - - return Disposable.Create( - settings.OnDispatcher().Subscribe(s => { - _favorite_algo_metadata_map = s.favorite_algos.build_map(); - order_properties_vm.on_favorite_algos( - _favorite_algo_metadata_map, s.favorite_algos.column_count); - }), - order_properties_vm, - position_src.OnDispatcher().Subscribe(pos => { - double total, day, raw_day; - if (pos.HasValue) { - total = pos.Value.total_pos(); - day = pos.Value.day_pos(); - raw_day = pos.Value.raw_day_pos(); - } else { - total = day = raw_day = double.NaN; - } - if (( - Set(ref _position, total, nameof(position)) | - Set(ref _day_position, day, nameof(day_position)) | - Set(ref _raw_day_position, raw_day, nameof(raw_day_position)) - ) && (show_day_position || show_account_position || show_raw_day_position)) - RaisePropertyChanged(nameof(position_display_text)); - })); - } - } - - public static LadderVM create( - IBus bus, LadderModel model, LadderSettings init, IObservable settings) { - var order_props_vm = new OrderPropertiesEditorVM( - model.order_gateway, - Observable.Return(model.security_md), - bus.subscribe(SparkTags.AccountsTag), - settings.Select(s => new InlineOrderProperties(model.order_gateway, s))); - return new(bus, model, init, settings, order_props_vm); - } - - public static LadderVM create_readonly( - IBus bus, LadderModel model, IObservable settings) => - create_readonly(bus, model, LadderSettings.Default, settings); - - public static LadderVM create_readonly( - IBus bus, LadderModel model, LadderSettings init, IObservable settings) => - new(bus, model, init, settings); - - public event Action? on_tick; - public event Action? request_settings_dialog; - public event Action? request_recenter; - public event Action? settings_invalidated; - public event Action? request_go_to_price; - - event Action? _on_disposed_impl; - - public IMDConsumerHandle md => _model.md; - public IBus bus => _bus; - - // we return only entries who have piqs and whose piqs are not uint.Max - // uint.Max happens when the server is restarted but the client is still up - // maybe long term we don't show this data while the exchange connection is down - public IEnumerable<(double, uint)> price_vs_piq => - _slot_price_vs_orders.Values - .Where(result => result.min_piq.HasValue && result.min_piq.Value != uint.MaxValue) - .Select(o => (o.price, o.min_piq.assert_value())); - - public bool is_synthetic => - _model.security.ContractCase == Security.ContractOneofCase.Synthetic; - public string status_message => _status.Value; - public Brush status_background => _status_brush.Value; - - event Action IWillLetYouKnowWhenIDispose.OnDisposed { - add => _on_disposed_impl += value; - remove => _on_disposed_impl -= value; - } - - public SecurityImmutable security => _model.security; - public RegionalTickFactors spec => _spec ?? ( - _spec = TickUtils.multiply_tick_size( - security.regional_ticks(), current_settings?.ticks_per_row ?? 1)) - ?? RegionalTickFactors.Default; - - public double display_quantity_divisor { get; } - public LadderSettings current_settings { get; private set; } - - // left panel values - public double bid_price => _bid_price.Value; - public double ask_price => _ask_price.Value; - public double mid_price => _mid_price.Value; - public double session_high => _session_high.Value; - public double session_low => _session_low.Value; - public double day_change => _day_change.Value; - public double open => _open.Value; - public double settlement => _settlement.Value; - public double theo => _theo.Value; - public double delta => _delta.Value; - public double vega => _vega.Value; - public double position => _position; - public double day_position => _day_position; - public double raw_day_position => _raw_day_position; - public ulong volume => _volume.Value; - - // left panel styles - public LadderPanelRelativePricePointVM day_change_style { get; } = new(); - - public Color day_change_font_color => - day_change switch { - > 0 => day_change_style.positive_font_color, - < 0 => day_change_style.negative_font_color, - _ => day_change_style.font_color - }; - - public Color day_change_background_color => - day_change switch { - > 0 => day_change_style.positive_background_color, - < 0 => day_change_style.negative_background_color, - _ => day_change_style.font_color - }; - - public LadderPanelPricePointVM bid_price_style { get; } = new(); - public LadderPanelPricePointVM ask_price_style { get; } = new(); - public LadderPanelPricePointVM mid_price_style { get; } = new(); - public LadderPanelPricePointVM open_style { get; } = new(); - public LadderPanelPricePointVM settlement_style { get; } = new(); - public LadderPanelPricePointVM theo_style { get; } = new(); - public LadderPanelPricePointVM delta_style { get; } = new(); - public LadderPanelPricePointVM vega_style { get; } = new(); - public LadderPanelPricePointVM session_high_style { get; } = new(); - public LadderPanelPricePointVM session_low_style { get; } = new(); - public LadderPanelPricePointVM volume_style { get; } = new(); - public bool auto_clear { - get => _auto_clear.Value; - set => _auto_clear.set(value); - } - - public CalculatorLogic size_calculator { get; } = new(); - public OrderPropertiesEditorVM? order_properties_vm { get; } - public ObservableCollection orders { get; } = new(); - - public Brush bid_background => _bid_background.view; - public Brush bid_foreground => _bid_foreground.view; - public Brush ask_background => _ask_background.view; - public Brush ask_foreground => _ask_foreground.view; - - public bool show_account => _show_account.view; - public bool show_tif => _show_tif.view; - public bool show_order_type => _show_order_type.view; - public bool show_account_position => _show_account_position; - public bool show_day_position => _show_day_position; - public bool show_raw_day_position => _show_raw_day_position; - public bool show_size_preset => _show_size_preset.view; - public bool show_auto_clear => _show_auto_clear.view; - public bool show_clear => _show_clear.view; - public bool show_cancel_buys => _show_cancel_buys.view; - public bool show_cancel_sells => _show_cancel_sells.view; - public bool show_cancel_all => _show_cancel_all.view; - public bool show_zoom => _show_zoom.view; - public bool show_status_message => _show_status_message.view; - - public TickDisplaySettings day_change_display_settings => - TickDisplaySettings.Default.with( - pad_with_leading_zeros: false, - show_zero_integer: false); - - ////////////////////////////////////////////////// - // left panel scroll props - ////////////////////////////////////////////////// - - public double left_panel_view_port_height { - get => _left_panel_view_port_height; - set => Set( - ref _left_panel_view_port_height, - value, - dependent_props: nameof(left_panel_scroll_position)); - } - - public double left_panel_scroll_position { - get { - if (_left_panel_scroll_position_target < _max_left_panel_scroll_position) { - _left_panel_scroll_position = _left_panel_scroll_position_target; - _left_panel_scroll_position_target = double.NaN; - } - return Math.Min(_left_panel_scroll_position, _left_panel_extent_height); - } - set => Set(ref _left_panel_scroll_position, value); - } - - public double left_panel_extent_height { - get => _left_panel_extent_height; - set { - using (detect_property_changes(nameof(left_panel_scroll_position))) - Set(ref _left_panel_extent_height, value); - } - } - - public double left_panel_width { - get => _left_panel_width.Value; - set => _left_panel_width.set(value); - } - - public double zoom_factor { - get => _zoom_factor.Value; - set => _zoom_factor.set(value); - } - - public string position_display_text { - get { - string? rv = null; - if (show_day_position) { - rv = SparkUtils.fmt_position(day_position / display_quantity_divisor); - } - if (show_raw_day_position) { - var raw_day_text = SparkUtils.fmt_position( - raw_day_position / display_quantity_divisor); - rv = rv is null ? raw_day_text : $"{rv} / {raw_day_text}"; - } - if (show_account_position) { - var acc_text = SparkUtils.fmt_position(position / display_quantity_divisor); - rv = rv is null ? acc_text : $"{rv} ({acc_text})"; - } - return rv ?? ""; - } - } - - public ObservableCollection fair_value_lines { get; } = - new ObservableCollection(); - - public uint orders_column_width { - get => _orders_column_width.Value; - set => _orders_column_width.set(value); - } - public uint bid_column_width { - get => _bid_column_width.Value; - set => _bid_column_width.set(value); - } - public uint price_column_width { - get => _price_column_width.Value; - set => _price_column_width.set(value); - } - public uint ask_column_width { - get => _ask_column_width.Value; - set => _ask_column_width.set(value); - } - public uint last_column_width { - get => _last_column_width.Value; - set => _last_column_width.set(value); - } - public uint piq_column_width { - get => _piq_column_width.Value; - set => _piq_column_width.set(value); - } - public uint volume_column_width { - get => _volume_column_width.Value; - set => _volume_column_width.set(value); - } - - public double actual_alternate_order_size => - (current_settings?.alternate_order_size ?? 0) * Math.Max(1, display_quantity_divisor); - - public RFQCreationVM rfq_vm { get; } - - public IAsyncCommand cancel_cmd { get; } - public ICommand send_order_cmd { get; } - public ICommand show_book_cmd { get; } - public ICommand show_ticket_cmd { get; } - public ICommand settings_cmd { get; } - public ICommand go_to_price_cmd { get; } - public ICommand position_click_cmd { get; } - public ICommand status_click_cmd => SparkCommands.ShowActivityLog.ICommand(_bus); - - internal LadderModel model => _model; - internal IObservable settings { get; } - - double _max_left_panel_scroll_position => - Math.Max(0, _left_panel_extent_height - _left_panel_view_port_height); - - public LadderSettings get_save_state() { - var rv = current_settings.with_window_specifics( - new LadderSettings.WindowSpecifics( - left_panel_width, - orders_column_width, - bid_column_width, - price_column_width, - ask_column_width, - last_column_width, - volume_column_width, - zoom_factor, - piq_column_width)); - rv.auto_clear = auto_clear; - rv.left_panel_scroll_position = left_panel_scroll_position; - if (order_properties_vm is not null) { - rv.default_time_in_force = order_properties_vm.selected_time_in_force; - if (order_properties_vm.selected_account.HasValue) { - rv.default_account = order_properties_vm.selected_account.Value.id; - } - if (order_properties_vm.selected_algo_definition != null) { - rv.default_algo = AlgoID.from_algo_key( - order_properties_vm.selected_algo_definition.key); - } - } - rv.panel_price_point_settings = new LadderPanelPricePointSettings { - bid_price = bid_price_style.create(), - ask_price = ask_price_style.create(), - mid_price = mid_price_style.create(), - day_change = day_change_style.create(), - open = open_style.create(), - settlement = settlement_style.create(), - theo = theo_style.create(), - delta = delta_style.create(), - vega = vega_style.create(), - session_low = session_low_style.create(), - session_high = session_high_style.create(), - volume = volume_style.create() - }; - return rv; - } - - public async void status_update(Activity a) { - if (a.security == _model.security && a.category != ActivityLogCategory.modify) { - _status.set(a.message); - _status_brush.set(a.category.fill); - await Task.Delay(TimeSpan.FromSeconds(5)); - if (_status.Value == a.message) { - _status.set(""); - _status_brush.set(_transparent_status_brush); - } - } - } - - public void key_down(KeyEventArgs e) { - if (order_properties_vm is null) { - return; - } - switch (e.Key) { - case Key.Space: - if (KeyboardExtensions.IsShiftDown()) { - // only recenter this ladder - request_recenter?.Invoke(); - } else { - // recenter all ladders - _bus.post(SparkTags.RequestRecenterLadder, null); - } - e.Handled = true; - break; - default: - // the ctrl modifier requirement helps avoid keyboard-input collisions w/ - // algo-templates popup - if (KeyboardExtensions.IsCtrlDown()) { - var algo_defs = order_properties_vm.algo_definitions; - if (algo_defs.TryGetFirst( - o => o is not null && o.algo_root.key_match(e), out var new_algo)) { - order_properties_vm.selected_algo_definition = new_algo; - e.Handled = true; - } - } - break; - } - } - - public void on_mini_orderbook_closed(bts.shell.orderbook.OrderBookStartupData ob_state) { - current_settings = SparkUtils.clone_proto(current_settings); - current_settings.mini_ob = new(ob_state.orderbook_grid.general); - 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) { - var (price, side, button) = args; - if (order_properties_vm is null || - order_properties_vm.HasErrors || - button == MouseButton.Middle || - !price.is_real() || - !side.HasValue - ) { - return Task.CompletedTask; - } - - var qty = button == MouseButton.Right ? - actual_alternate_order_size : size_calculator.value ?? double.NaN; - if (current_settings.enforce_max_clip) { - qty = qty.within_range(double.MinValue, current_settings.max_clip); - } - if (!qty.is_real_positive()) { - size_calculator.flash_error(); - return Task.CompletedTask; - } - - return send_order_async(side.Value, qty, price); - } - - public async Task send_order_async(Side side, double qty, double price) { - if (order_properties_vm is null) { - return; - } - if (!_validate_price(side, price, out var invalid_price_msg)) { - status_update(new Activity { - security = security, - message = invalid_price_msg, - category = ActivityLogCategory.order - }); - return; - } - - var order = order_properties_vm.create(side); - if (order.CustomDef is not null) { - if (order.CustomDef.Stop is not null) { - order.CustomDef.Stop.StopPrice = price; - } else if (order.CustomDef.StopLimit is not null) { - // swap the prices here so that the level clicked - // in the ladder is the StopPrice (trigger) and the Price - // is what was specificed in the extra parameter box - (price, order.CustomDef.StopLimit.StopPrice) = - (order.CustomDef.StopLimit.StopPrice, price); - } - } - - await _model.order_gateway.send_order(security, order, price, qty); - if (auto_clear) { - size_calculator.value = null; - } - var fav_algo = order_properties_vm.selected_favorite_algo_definition; - if (fav_algo is not null && - _favorite_algo_metadata_map.TryGetValue(fav_algo.key, out var fav_algo_meta)) { - if (!fav_algo_meta.flags.HasFlag(LadderFavoriteAlgoFlags.Sticky) && - !order_properties_vm.try_pop_selected_algo_definition()) { - var key = new AlgoKey(OrderDataHelper.get_default_algo(security.ContractCase)); - if (order_properties_vm.try_get_algo_definition(key, out var r)) { - order_properties_vm.selected_algo_definition = r; - } - } - if (fav_algo_meta.flags.HasFlag(LadderFavoriteAlgoFlags.AutoRevert)) { - fav_algo.algo_root.revert_all_params(); - } - } - } - - internal OrderRecordImmutable get_root_at_price(OrderRecordTuple op) { - double p = _normalize_price(op.order.ui_price()); - return lineage(op.order.ParentKey) - .Where(o => _equality.Equals(p, _normalize_price(o.ui_price()))) - .LastOrDefault(op.order); - } - - internal IEnumerable lineage(uint key) { - while (key != 0 && _cache.TryGetValue(key, out var op)) { - yield return op.order; - key = op.order.ParentKey; - } - } - - static IObservable<(ImmutableSortedDictionary> price_index, IReadOnlyDictionary map)> _order_price_source( - IObservable> source, - IComparer price_comp, - Func normalize_price - ) { - return Observable.Create<(ImmutableSortedDictionary>, IReadOnlyDictionary)>(o => { - var state = ImmutableSortedDictionary.Create>(price_comp); - var sub = source.Subscribe(table => { - var bd = state.ToBuilder(); - - // removes - var removes = table.removed.Concat(table.changes.Where(price_changed).Old()); - foreach (var old_order in removes) { - var price = get_price(old_order); - if (bd.TryGetValue(price, out var index)) { - var new_index = index.Remove(old_order.order.Key); - if (new_index.Count == 0) { - bd.Remove(price); - } else { - bd[price] = new_index; - } - } - } - - // changes - var changes = table.changes.Where(ch => !price_changed(ch)).New(); - foreach (var changed_order in changes) { - var price = get_price(changed_order); - bd[price] = bd[price].SetItem(changed_order.order.Key, changed_order); - } - - // adds - var adds = table.added.Concat(table.changes.Where(price_changed).New()); - foreach (var new_order in adds) { - var price = get_price(new_order); - if (bd.TryGetValue(price, out var index)) { - bd[price] = index.Add(new_order.order.Key, new_order); - } else { - bd[price] = ImmutableDictionary.CreateRange(new[] { - new KeyValuePair(new_order.order.Key, new_order) - }); - } - } - o.OnNext((state = bd.ToImmutable(), table.state)); - }); - return sub; - }); - - bool price_changed(Change ch) => - price_comp.Compare(ch.New.order.ui_price(), ch.Old.order.ui_price()) != 0; - - double get_price(OrderRecordTuple order) { - var p = order.order.ui_price(); - if (!(normalize_price is null)) - p = normalize_price(p); - return p; - } - } - - double _normalize_price(double price) => - TickUtils.normalize_price(spec, price); - - bool _validate_price(Side side, double price, [MaybeNullWhen(true)] out string? msg) { - msg = null; - if (!price.is_real()) { - msg = "not a real number"; - } else if (settlement.is_real()) { - var ticks_from_settle = security.tickdiff(price, settlement); - if (ticks_from_settle.HasValue) { - var max_cross = (current_settings?.ladder_order_limits?.max_settlement_cross_ticks) - .as_nullable(); - if (max_cross.HasValue && - (side == Side.Sell ? - ticks_from_settle < (-1 * max_cross.Value) : - ticks_from_settle > max_cross.Value) - ) { - msg = $"exceeds settle cross ticks limit ({ticks_from_settle.Value})"; - } - } - } - return msg is null; - } - - void _update_header() { - bool last_updated = md.get_last_trade( - ref _last_trade_time, out var last, out var _, out var volume); - if (_misc_time == _model.md.misc_timestamp && !last_updated) { - return; - } - - _session_high.set(md.session_high); - _session_low.set(md.session_low); - _open.set(md.open_price); - _settlement.set(md.settlement_price); - if (md.get_bbo(ref _last_bbo_time, out var bid, out var ask)) { - _bid_price.set(bid.price); - _ask_price.set(ask.price); - } - _day_change.set(last.price.if_nan(mid_price) - md.settlement_price); - _volume.set(volume); - _misc_time = _model.md.misc_timestamp; - } - - void _send_rfq(RFQRequestImmutable req) => - _bus.post(SparkTags.RFQSend, req); - - void _show_book() { - var ob_settings = bts.shell.orderbook.OrderBookStartupData.Default; - ob_settings.filters = new bts.shell.orderbook.FilterStates { - security_criteria = SecurityCriteria.from_securities(security) - }; - _bus.post(SparkTags.ShowOrderBookTag, ob_settings); - } - - void _show_ticket() { - if (order_properties_vm is null) { - return; - } - _bus.post( - SparkTags.ShowOrderTicketTag, - new(new(order_properties_vm.create(Side.Buy)), 0d, 0u)); - } - - void _tick() { - _update_header(); - on_tick?.Invoke(); - } - } -} +#nullable enable +namespace mbts.spark { + using bts.api; + using bts.api.core; + using bts.api.orderman; + using bts.collections; + using bts.proto; + using bts.shell; + using bts.spark; + using bts.utils; + + using mbts.co2; + using mbts.spark.utilities; + using mbts.ui; + using mbts.ui.shell; + using mbts.ui.utility; + using mbts.user.settings; + using mbts.utils; + + using Spark.Api.Orders; + using Spark.Api.Position; + using Spark.Core; + using Spark.Core.Collections; + using Spark.Core.Data; + using Spark.Core.Disposables; + using Spark.Core.Math; + using Spark.Core.Reactive; + using Spark.Trading; + using Spark.ViewModel.Commands; + using Spark.ViewModel.Trading; + + using System; + using System.Collections.Generic; + using System.Collections.Immutable; + using System.Collections.ObjectModel; + using System.Collections.Specialized; + using System.Diagnostics.CodeAnalysis; + using System.Linq; + using System.Reactive.Linq; + using System.Threading.Tasks; + using System.Windows.Input; + using System.Windows.Media; + + class LadderVM : DisposableViewModelBase, IWillLetYouKnowWhenIDispose, IKeyListener { + static readonly Brush _transparent_status_brush = BTSColors.UI.transparent; + + readonly IBus _bus; + readonly LadderModel _model; + readonly IEqualityComparer _equality; + readonly Dictionary _slot_price_vs_orders; + readonly ObservableCollection _fair_value_line_inputs = new(); + + readonly Property _bid_price; + readonly Property _ask_price; + readonly Property _mid_price; + readonly Property _session_high; + readonly Property _session_low; + readonly Property _day_change; + readonly Property _open; + readonly Property _settlement; + readonly Property _theo; + readonly Property _delta; + readonly Property _vega; + readonly Property _left_panel_width; + readonly Property _zoom_factor; + readonly Property _orders_column_width; + readonly Property _bid_column_width; + readonly Property _price_column_width; + readonly Property _ask_column_width; + readonly Property _last_column_width; + readonly Property _volume_column_width; + readonly Property _piq_column_width; + readonly Property _volume; + readonly Property _auto_clear; + readonly PropertyAutoWrapper _show_account; + readonly PropertyAutoWrapper _show_tif; + readonly PropertyAutoWrapper _show_order_type; + readonly PropertyAutoWrapper _show_size_preset; + readonly PropertyAutoWrapper _show_auto_clear; + readonly PropertyAutoWrapper _show_clear; + readonly PropertyAutoWrapper _show_cancel_buys; + readonly PropertyAutoWrapper _show_cancel_sells; + readonly PropertyAutoWrapper _show_cancel_all; + readonly PropertyAutoWrapper _show_zoom; + readonly PropertyAutoWrapper _show_status_message; + readonly PropertyAutoWrapper _bid_background; + readonly PropertyAutoWrapper _bid_foreground; + readonly PropertyAutoWrapper _ask_background; + readonly PropertyAutoWrapper _ask_foreground; + readonly Property _status; + readonly Property _status_brush; + + double _position; + double _day_position; + double _raw_day_position; + double _left_panel_extent_height; + double _left_panel_view_port_height; + double _left_panel_scroll_position; + double _left_panel_scroll_position_target; + bool _show_account_position; + bool _show_day_position; + bool _show_raw_day_position; + ulong _misc_time = 0; + ulong _last_trade_time = 0; + ulong _last_bbo_time = 0; + IReadOnlyDictionary _cache = DictionaryHelper.empty(); + ImmutableDictionary _favorite_algo_metadata_map = + ImmutableDictionary.Empty; + RegionalTickFactors? _spec; + + LadderVM( + IBus bus, + LadderModel model, + LadderSettings init, + IObservable settings, + OrderPropertiesEditorVM? order_properties_vm = null + ) { + _bus = bus; + _model = model; + current_settings = init; + this.settings = settings; + _equality = TickUtils.tick_equality_comparer(_model.security.ContractSpec); + display_quantity_divisor = model.sec_meta_store.get_qty_display_divisor(security); + size_calculator.display_divisor = display_quantity_divisor; + size_calculator.display_settings = model.security_md.quantity_display; + _slot_price_vs_orders = new Dictionary(_equality); + this.order_properties_vm = order_properties_vm; + _session_high = backing(nameof(session_high), double.NaN); + _session_low = backing(nameof(session_low), double.NaN); + _day_change = backing(nameof(day_change), double.NaN); + _open = backing(nameof(open), double.NaN); + _settlement = backing(nameof(settlement), double.NaN); + _bid_price = backing(nameof(bid_price), double.NaN); + _ask_price = backing(nameof(ask_price), double.NaN); + _mid_price = backing( + nameof(mid_price), + _bid_price.observe_current().CombineLatest(_ask_price.observe_current(), (bid, ask) => { + if (bid.is_nan()) { + return ask; + } + if (ask.is_nan()) { + return bid; + } + var res = (bid + ask) * 0.5; + res = spec.round_to_tick(res); + return res; + })); + _theo = backing(nameof(theo), double.NaN); + _delta = backing(nameof(delta), double.NaN); + _vega = backing(nameof(vega), double.NaN); + + // init window-specific settings: these properties should not observe settings updates; + // they are independent from the settings dialog, so it doesn't make sense that the + // settings dialog should cause them to change. + var ws = init.get_window_specifics(); + _orders_column_width = backing(nameof(orders_column_width), ws.orders_column_width); + _bid_column_width = backing(nameof(bid_column_width), ws.bid_column_width); + _price_column_width = backing(nameof(price_column_width), ws.price_column_width); + _ask_column_width = backing(nameof(ask_column_width), ws.ask_column_width); + _last_column_width = backing(nameof(last_column_width), ws.last_column_width); + _piq_column_width = backing(nameof(piq_column_width), ws.piq_column_width); + _volume_column_width = backing(nameof(volume_column_width), ws.volume_column_width); + _left_panel_width = backing(nameof(left_panel_width), ws.order_entry_panel_width); + _zoom_factor = backing(nameof(zoom_factor), ws.zoom_factor); + _left_panel_scroll_position_target = init.left_panel_scroll_position; + // remember: account_positions needs to subscribe to selected_account; both the sub and + // account_positions need to be disposed + _volume = backing(nameof(volume), 0ul); + _auto_clear = backing(nameof(auto_clear), init.auto_clear); + _status = backing(nameof(status_message), ""); + _status_brush = backing(nameof(status_background), _transparent_status_brush); + go_to_price_cmd = new DelegateCommand(p => request_go_to_price?.Invoke(p)); + + // All settings observers should be aggregated together, so they can all share the same + // subscription to the settings (these subscriptions are not horribly expensive, but + // they're not free either - even more so with the .OnDispatcher() extension). + var settings_observer = new CompositeObserver { + /// first things first: assign our + s => current_settings = s, + // brush props + (_bid_background = brush_prop(nameof(bid_background), s => s.bid_column.background)).set, + (_bid_foreground = brush_prop(nameof(bid_foreground), s => s.bid_column.foreground)).set, + (_ask_background = brush_prop(nameof(ask_background), s => s.ask_column.background)).set, + (_ask_foreground = brush_prop(nameof(ask_foreground), s => s.ask_column.foreground)).set, + // bool visibility props + (_show_account = bool_prop(nameof(show_account), s => s.account_visible)).set, + (_show_tif = bool_prop(nameof(show_tif), s => s.tif_visible)).set, + (_show_order_type = bool_prop(nameof(show_order_type), s => s.order_type_visible)).set, + (_show_size_preset = bool_prop(nameof(show_size_preset), s => s.size_presets_visible)).set, + (_show_auto_clear = bool_prop(nameof(show_auto_clear), s => s.auto_clear_visible)).set, + (_show_clear = bool_prop(nameof(show_clear), s => s.clear_visible)).set, + (_show_cancel_buys = bool_prop(nameof(show_cancel_buys), s => s.cancel_buys_visible)).set, + (_show_cancel_sells = bool_prop(nameof(show_cancel_sells), s => s.cancel_sells_visible)).set, + (_show_cancel_all = bool_prop(nameof(show_cancel_all), s => s.cancel_all_visible)).set, + (_show_zoom = bool_prop(nameof(show_zoom), s => s.zoom_slider_visible)).set, + (_show_status_message = bool_prop(nameof(show_status_message), s => s.status_message_visible)).set, + s => { + // invalidate spec in case 'ticks per row' changed + _spec = null; + if ( + Set(ref _show_account_position, s.account_position_visible, nameof(show_account_position)) | + Set(ref _show_day_position, s.day_position_visible, nameof(show_day_position)) | + Set(ref _show_raw_day_position, s.raw_day_position_visible, nameof(show_raw_day_position))) { + RaisePropertyChanged(nameof(position_display_text)); + } + size_calculator.buttons = s.calculator_buttons; + _auto_clear.set(s.auto_clear); + // column widths + _orders_column_width.set(s.orders_column.width); + _bid_column_width.set(s.bid_column.width); + _price_column_width.set(s.price_column.width); + _ask_column_width.set(s.ask_column.width); + _last_column_width.set(s.last_column.width); + _piq_column_width.set(s.piq_column.width); + _volume_column_width.set(s.volume_column.general.width); + // left panel/zoom + // bid price + bid_price_style.load_from(s.panel_price_point_settings.bid_price); + bid_price_style.show = s.bid_price_visible; + // ask price + ask_price_style.load_from(s.panel_price_point_settings.ask_price); + ask_price_style.show = s.ask_price_visible; + // mid price + mid_price_style.load_from(s.panel_price_point_settings.mid_price); + mid_price_style.show = s.mid_price_visible; + // day + day_change_style.load_from(s.panel_price_point_settings.day_change); + day_change_style.show = s.day_visible; + // open + open_style.load_from(s.panel_price_point_settings.open); + open_style.show = s.open_visible; + // session low + session_low_style.load_from(s.panel_price_point_settings.session_low); + session_low_style.show = s.low_visible; + // session high + session_high_style.load_from(s.panel_price_point_settings.session_high); + session_high_style.show = s.high_visible; + // settlement + settlement_style.load_from(s.panel_price_point_settings.settlement); + settlement_style.show = s.settle_visible; + // theo + theo_style.load_from(s.panel_price_point_settings.theo); + theo_style.show = s.theo_visible; + // delta + delta_style.load_from(s.panel_price_point_settings.delta); + delta_style.show = s.delta_visible; + // vega + vega_style.load_from(s.panel_price_point_settings.vega); + vega_style.show = s.vega_visible; + // volume + volume_style.load_from(s.panel_price_point_settings.volume); + volume_style.show = s.volume_visible; + // left panel gen display + _left_panel_width.set(s.order_entry_panel_initial_width); + _zoom_factor.set(s.zoom_factor); + RaisePropertyChanged(nameof(day_change_font_color), nameof(day_change_background_color)); + // fair value lines + _fair_value_line_inputs.sync_with(s.fair_value_lines.Distinct()); + } + }; + + position_click_cmd = new Command( + () => { + var pos = _show_day_position ? day_position : + (_show_raw_day_position ? _raw_day_position : position); + size_calculator.value = pos.abs(); + }); + send_order_cmd = new AsyncCommand<(double price, Side? side, MouseButton button)>(send_order_async); + rfq_vm = new(security.Id); + rfq_vm.request_commit += _send_rfq; + cancel_cmd = new AsyncCommand(_model.cancel_orders, true); + show_book_cmd = new Command(_show_book); + show_ticket_cmd = new Command(_show_ticket); + settings_cmd = new Command(() => request_settings_dialog?.Invoke()); + + var orders_source = settings.Select(s => s.ticks_per_row).DistinctUntilChanged() + .SelectSeries(tpr => { + var spec = TickUtils.multiply_tick_size(security.regional_ticks(), tpr); + var price_comp = Comparer.Create((a, b) => + Comparer.Default.Compare(spec.count_ticks(a), spec.count_ticks(b))); + return _order_price_source(model.orders, price_comp, p => spec.round_to_tick(p, RoundingMode.AbsDown)); + }); + _day_change.Changed += (o, n) => RaisePropertyChanged( + nameof(day_change_font_color), nameof(day_change_background_color)); + + _dispose = Disposable.Create( + settings.OnDispatcher().Subscribe(settings_observer), + get_order_properties_editor_hooks(), + bus.subscribe(SparkTags.LogActivity).OnDispatcher().Subscribe(status_update), + model.greeks.OnDispatcher().Subscribe(g => { + _theo.set(g.normalized_theo); + _delta.set(g.delta); + _vega.set(g.vega); + }), + ObservableAutoWrapper.connect( + _fair_value_line_inputs, + fair_value_lines, + fvl => { + var key = new FairValueKey() { + security_id = fvl.security_key ?? security.Id, + type = fvl.price_type + }; + return new FairValueLineVM(key, _model.fair_value_model.get_price_source(key)) { + settings = fvl.display + }; + }), + orders_source.OnDispatcher().Subscribe(tup => { + _cache = tup.map; + /// remove empty price slots (the vm will be disposed automatically when it is + /// removed from ) + var removed_prices = _slot_price_vs_orders.Keys.Except(tup.price_index.Keys).ToList(); + foreach (var p in removed_prices) { + _slot_price_vs_orders.Remove(p); + } + // add or update current price slots + foreach (var kv in tup.price_index) { + _slot_price_vs_orders.AddOrUpdate( + kv.Key, + _ => new LadderOrderVM( + kv.Value, kv.Key, this, settings.Select(s => s.badge_style)), + (_, order_vm) => order_vm.sync_orders(kv.Value)); + } + // sync the collection + orders.sync_with(_slot_price_vs_orders.Values); + // update badge colors, text, etc. + foreach (var o in orders) { + o.update(); + } + }), + WorkLoop.Start($"Ladder '{security}'", _tick), + ObservableAutoWrapper.dispose_on_removed(orders, true), + Disposable.Create(() => _on_disposed_impl?.Invoke(true))); + + PropertyAutoWrapper bool_prop( + string name, Func get_bool) => + backing(name, init, get_bool, EqualityComparer.Create(get_bool)); + + PropertyAutoWrapper brush_prop( + string name, Func get_color_uint) { + var comp = EqualityComparer.Create(get_color_uint); + return backing(name, init, s => get_color_uint(s).rgb_brush(), comp); + } + + IDisposable get_order_properties_editor_hooks() { + if (order_properties_vm is null) { + return Disposable.empty; + } + var position_src = order_properties_vm.observe_account(true) + .Select(a => a?.name ?? string.Empty) + .SelectSeries(a => _model.position_model.on_security_positions(security.Id) + .Select(table => table.state.Values.FirstOrDefault( + pos => pos.Item2.Account == a, + tup => tup.Item2, (bts.api.position.PositionUnitImmutable?)null))); + + return Disposable.Create( + settings.OnDispatcher().Subscribe(s => { + _favorite_algo_metadata_map = s.favorite_algos.build_map(); + order_properties_vm.on_favorite_algos( + _favorite_algo_metadata_map, s.favorite_algos.column_count); + }), + order_properties_vm, + position_src.OnDispatcher().Subscribe(pos => { + double total, day, raw_day; + if (pos.HasValue) { + total = pos.Value.total_pos(); + day = pos.Value.day_pos(); + raw_day = pos.Value.raw_day_pos(); + } else { + total = day = raw_day = double.NaN; + } + if (( + Set(ref _position, total, nameof(position)) | + Set(ref _day_position, day, nameof(day_position)) | + Set(ref _raw_day_position, raw_day, nameof(raw_day_position)) + ) && (show_day_position || show_account_position || show_raw_day_position)) + RaisePropertyChanged(nameof(position_display_text)); + })); + } + } + + public static LadderVM create( + IBus bus, LadderModel model, LadderSettings init, IObservable settings) { + var order_props_vm = new OrderPropertiesEditorVM( + model.order_gateway, + Observable.Return(model.security_md), + bus.subscribe(SparkTags.AccountsTag), + settings.Select(s => new InlineOrderProperties(model.order_gateway, s))); + return new(bus, model, init, settings, order_props_vm); + } + + public static LadderVM create_readonly( + IBus bus, LadderModel model, IObservable settings) => + create_readonly(bus, model, LadderSettings.Default, settings); + + public static LadderVM create_readonly( + IBus bus, LadderModel model, LadderSettings init, IObservable settings) => + new(bus, model, init, settings); + + public event Action? on_tick; + public event Action? request_settings_dialog; + public event Action? request_recenter; + public event Action? settings_invalidated; + public event Action? request_go_to_price; + + event Action? _on_disposed_impl; + + public IMDConsumerHandle md => _model.md; + public IBus bus => _bus; + + // we return only entries who have piqs and whose piqs are not uint.Max + // uint.Max happens when the server is restarted but the client is still up + // maybe long term we don't show this data while the exchange connection is down + public IEnumerable<(double, uint)> price_vs_piq => + _slot_price_vs_orders.Values + .Where(result => result.min_piq.HasValue && result.min_piq.Value != uint.MaxValue) + .Select(o => (o.price, o.min_piq.assert_value())); + + public bool is_synthetic => + _model.security.ContractCase == Security.ContractOneofCase.Synthetic; + public string status_message => _status.Value; + public Brush status_background => _status_brush.Value; + + event Action IWillLetYouKnowWhenIDispose.OnDisposed { + add => _on_disposed_impl += value; + remove => _on_disposed_impl -= value; + } + + public SecurityImmutable security => _model.security; + public RegionalTickFactors spec => _spec ?? ( + _spec = TickUtils.multiply_tick_size( + security.regional_ticks(), current_settings?.ticks_per_row ?? 1)) + ?? RegionalTickFactors.Default; + + public double display_quantity_divisor { get; } + public LadderSettings current_settings { get; private set; } + + // left panel values + public double bid_price => _bid_price.Value; + public double ask_price => _ask_price.Value; + public double mid_price => _mid_price.Value; + public double session_high => _session_high.Value; + public double session_low => _session_low.Value; + public double day_change => _day_change.Value; + public double open => _open.Value; + public double settlement => _settlement.Value; + public double theo => _theo.Value; + public double delta => _delta.Value; + public double vega => _vega.Value; + public double position => _position; + public double day_position => _day_position; + public double raw_day_position => _raw_day_position; + public ulong volume => _volume.Value; + + // left panel styles + public LadderPanelRelativePricePointVM day_change_style { get; } = new(); + + public Color day_change_font_color => + day_change switch { + > 0 => day_change_style.positive_font_color, + < 0 => day_change_style.negative_font_color, + _ => day_change_style.font_color + }; + + public Color day_change_background_color => + day_change switch { + > 0 => day_change_style.positive_background_color, + < 0 => day_change_style.negative_background_color, + _ => day_change_style.font_color + }; + + public LadderPanelPricePointVM bid_price_style { get; } = new(); + public LadderPanelPricePointVM ask_price_style { get; } = new(); + public LadderPanelPricePointVM mid_price_style { get; } = new(); + public LadderPanelPricePointVM open_style { get; } = new(); + public LadderPanelPricePointVM settlement_style { get; } = new(); + public LadderPanelPricePointVM theo_style { get; } = new(); + public LadderPanelPricePointVM delta_style { get; } = new(); + public LadderPanelPricePointVM vega_style { get; } = new(); + public LadderPanelPricePointVM session_high_style { get; } = new(); + public LadderPanelPricePointVM session_low_style { get; } = new(); + public LadderPanelPricePointVM volume_style { get; } = new(); + public bool auto_clear { + get => _auto_clear.Value; + set => _auto_clear.set(value); + } + + public CalculatorLogic size_calculator { get; } = new(); + public OrderPropertiesEditorVM? order_properties_vm { get; } + public ObservableCollection orders { get; } = new(); + + public Brush bid_background => _bid_background.view; + public Brush bid_foreground => _bid_foreground.view; + public Brush ask_background => _ask_background.view; + public Brush ask_foreground => _ask_foreground.view; + + public bool show_account => _show_account.view; + public bool show_tif => _show_tif.view; + public bool show_order_type => _show_order_type.view; + public bool show_account_position => _show_account_position; + public bool show_day_position => _show_day_position; + public bool show_raw_day_position => _show_raw_day_position; + public bool show_size_preset => _show_size_preset.view; + public bool show_auto_clear => _show_auto_clear.view; + public bool show_clear => _show_clear.view; + public bool show_cancel_buys => _show_cancel_buys.view; + public bool show_cancel_sells => _show_cancel_sells.view; + public bool show_cancel_all => _show_cancel_all.view; + public bool show_zoom => _show_zoom.view; + public bool show_status_message => _show_status_message.view; + + public TickDisplaySettings day_change_display_settings => + TickDisplaySettings.Default.with( + pad_with_leading_zeros: false, + show_zero_integer: false); + + ////////////////////////////////////////////////// + // left panel scroll props + ////////////////////////////////////////////////// + + public double left_panel_view_port_height { + get => _left_panel_view_port_height; + set => Set( + ref _left_panel_view_port_height, + value, + dependent_props: nameof(left_panel_scroll_position)); + } + + public double left_panel_scroll_position { + get { + if (_left_panel_scroll_position_target < _max_left_panel_scroll_position) { + _left_panel_scroll_position = _left_panel_scroll_position_target; + _left_panel_scroll_position_target = double.NaN; + } + return Math.Min(_left_panel_scroll_position, _left_panel_extent_height); + } + set => Set(ref _left_panel_scroll_position, value); + } + + public double left_panel_extent_height { + get => _left_panel_extent_height; + set { + using (detect_property_changes(nameof(left_panel_scroll_position))) + Set(ref _left_panel_extent_height, value); + } + } + + public double left_panel_width { + get => _left_panel_width.Value; + set => _left_panel_width.set(value); + } + + public double zoom_factor { + get => _zoom_factor.Value; + set => _zoom_factor.set(value); + } + + public string position_display_text { + get { + string? rv = null; + if (show_day_position) { + rv = SparkUtils.fmt_position(day_position / display_quantity_divisor); + } + if (show_raw_day_position) { + var raw_day_text = SparkUtils.fmt_position( + raw_day_position / display_quantity_divisor); + rv = rv is null ? raw_day_text : $"{rv} / {raw_day_text}"; + } + if (show_account_position) { + var acc_text = SparkUtils.fmt_position(position / display_quantity_divisor); + rv = rv is null ? acc_text : $"{rv} ({acc_text})"; + } + return rv ?? ""; + } + } + + public ObservableCollection fair_value_lines { get; } = + new ObservableCollection(); + + public uint orders_column_width { + get => _orders_column_width.Value; + set => _orders_column_width.set(value); + } + public uint bid_column_width { + get => _bid_column_width.Value; + set => _bid_column_width.set(value); + } + public uint price_column_width { + get => _price_column_width.Value; + set => _price_column_width.set(value); + } + public uint ask_column_width { + get => _ask_column_width.Value; + set => _ask_column_width.set(value); + } + public uint last_column_width { + get => _last_column_width.Value; + set => _last_column_width.set(value); + } + public uint piq_column_width { + get => _piq_column_width.Value; + set => _piq_column_width.set(value); + } + public uint volume_column_width { + get => _volume_column_width.Value; + set => _volume_column_width.set(value); + } + + public double actual_alternate_order_size => + (current_settings?.alternate_order_size ?? 0) * Math.Max(1, display_quantity_divisor); + + public RFQCreationVM rfq_vm { get; } + + public IAsyncCommand cancel_cmd { get; } + public ICommand send_order_cmd { get; } + public ICommand show_book_cmd { get; } + public ICommand show_ticket_cmd { get; } + public ICommand settings_cmd { get; } + public ICommand go_to_price_cmd { get; } + public ICommand position_click_cmd { get; } + public ICommand status_click_cmd => SparkCommands.ShowActivityLog.ICommand(_bus); + + internal LadderModel model => _model; + internal IObservable settings { get; } + + double _max_left_panel_scroll_position => + Math.Max(0, _left_panel_extent_height - _left_panel_view_port_height); + + public LadderSettings get_save_state() { + var rv = current_settings.with_window_specifics( + new LadderSettings.WindowSpecifics( + left_panel_width, + orders_column_width, + bid_column_width, + price_column_width, + ask_column_width, + last_column_width, + volume_column_width, + zoom_factor, + piq_column_width)); + rv.auto_clear = auto_clear; + rv.left_panel_scroll_position = left_panel_scroll_position; + if (order_properties_vm is not null) { + rv.default_time_in_force = order_properties_vm.selected_time_in_force; + if (order_properties_vm.selected_account.HasValue) { + rv.default_account = order_properties_vm.selected_account.Value.id; + } + if (order_properties_vm.selected_algo_definition != null) { + rv.default_algo = AlgoID.from_algo_key( + order_properties_vm.selected_algo_definition.key); + } + } + rv.panel_price_point_settings = new LadderPanelPricePointSettings { + bid_price = bid_price_style.create(), + ask_price = ask_price_style.create(), + mid_price = mid_price_style.create(), + day_change = day_change_style.create(), + open = open_style.create(), + settlement = settlement_style.create(), + theo = theo_style.create(), + delta = delta_style.create(), + vega = vega_style.create(), + session_low = session_low_style.create(), + session_high = session_high_style.create(), + volume = volume_style.create() + }; + return rv; + } + + public async void status_update(Activity a) { + if (a.security == _model.security && a.category != ActivityLogCategory.modify) { + _status.set(a.message); + _status_brush.set(a.category.fill); + await Task.Delay(TimeSpan.FromSeconds(5)); + if (_status.Value == a.message) { + _status.set(""); + _status_brush.set(_transparent_status_brush); + } + } + } + + public void key_down(KeyEventArgs e) { + if (order_properties_vm is null) { + return; + } + switch (e.Key) { + case Key.Space: + if (KeyboardExtensions.IsShiftDown()) { + // only recenter this ladder + request_recenter?.Invoke(); + } else { + // recenter all ladders + _bus.post(SparkTags.RequestRecenterLadder, null); + } + e.Handled = true; + break; + default: + // the ctrl modifier requirement helps avoid keyboard-input collisions w/ + // algo-templates popup + if (KeyboardExtensions.IsCtrlDown()) { + var algo_defs = order_properties_vm.algo_definitions; + if (algo_defs.TryGetFirst( + o => o is not null && o.algo_root.key_match(e), out var new_algo)) { + order_properties_vm.selected_algo_definition = new_algo; + e.Handled = true; + } + } + break; + } + } + + public void on_mini_orderbook_closed(bts.shell.orderbook.OrderBookStartupData ob_state) { + current_settings = SparkUtils.clone_proto(current_settings); + current_settings.mini_ob = new(ob_state.orderbook_grid.general); + 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) { + var (price, side, button) = args; + if (order_properties_vm is null || + order_properties_vm.HasErrors || + button == MouseButton.Middle || + !price.is_real() || + !side.HasValue + ) { + return Task.CompletedTask; + } + + var qty = button == MouseButton.Right ? + actual_alternate_order_size : size_calculator.value ?? double.NaN; + if (current_settings.enforce_max_clip) { + qty = qty.within_range(double.MinValue, current_settings.max_clip); + } + if (!qty.is_real_positive()) { + size_calculator.flash_error(); + return Task.CompletedTask; + } + + return send_order_async(side.Value, qty, price); + } + + public async Task send_order_async(Side side, double qty, double price) { + if (order_properties_vm is null) { + return; + } + if (!_validate_price(side, price, out var invalid_price_msg)) { + status_update(new Activity { + security = security, + message = invalid_price_msg, + category = ActivityLogCategory.order + }); + return; + } + + var order = order_properties_vm.create(side); + if (order.CustomDef is not null) { + if (order.CustomDef.Stop is not null) { + order.CustomDef.Stop.StopPrice = price; + } else if (order.CustomDef.StopLimit is not null) { + // swap the prices here so that the level clicked + // in the ladder is the StopPrice (trigger) and the Price + // is what was specificed in the extra parameter box + (price, order.CustomDef.StopLimit.StopPrice) = + (order.CustomDef.StopLimit.StopPrice, price); + } + } + + await _model.order_gateway.send_order(security, order, price, qty); + if (auto_clear) { + size_calculator.value = null; + } + var fav_algo = order_properties_vm.selected_favorite_algo_definition; + if (fav_algo is not null && + _favorite_algo_metadata_map.TryGetValue(fav_algo.key, out var fav_algo_meta)) { + if (!fav_algo_meta.flags.HasFlag(LadderFavoriteAlgoFlags.Sticky) && + !order_properties_vm.try_pop_selected_algo_definition()) { + var key = new AlgoKey(OrderDataHelper.get_default_algo(security.ContractCase)); + if (order_properties_vm.try_get_algo_definition(key, out var r)) { + order_properties_vm.selected_algo_definition = r; + } + } + if (fav_algo_meta.flags.HasFlag(LadderFavoriteAlgoFlags.AutoRevert)) { + fav_algo.algo_root.revert_all_params(); + } + } + } + + internal OrderRecordImmutable get_root_at_price(OrderRecordTuple op) { + double p = _normalize_price(op.order.ui_price()); + return lineage(op.order.ParentKey) + .Where(o => _equality.Equals(p, _normalize_price(o.ui_price()))) + .LastOrDefault(op.order); + } + + internal IEnumerable lineage(uint key) { + while (key != 0 && _cache.TryGetValue(key, out var op)) { + yield return op.order; + key = op.order.ParentKey; + } + } + + static IObservable<(ImmutableSortedDictionary> price_index, IReadOnlyDictionary map)> _order_price_source( + IObservable> source, + IComparer price_comp, + Func normalize_price + ) { + return Observable.Create<(ImmutableSortedDictionary>, IReadOnlyDictionary)>(o => { + var state = ImmutableSortedDictionary.Create>(price_comp); + var sub = source.Subscribe(table => { + var bd = state.ToBuilder(); + + // removes + var removes = table.removed.Concat(table.changes.Where(price_changed).Old()); + foreach (var old_order in removes) { + var price = get_price(old_order); + if (bd.TryGetValue(price, out var index)) { + var new_index = index.Remove(old_order.order.Key); + if (new_index.Count == 0) { + bd.Remove(price); + } else { + bd[price] = new_index; + } + } + } + + // changes + var changes = table.changes.Where(ch => !price_changed(ch)).New(); + foreach (var changed_order in changes) { + var price = get_price(changed_order); + bd[price] = bd[price].SetItem(changed_order.order.Key, changed_order); + } + + // adds + var adds = table.added.Concat(table.changes.Where(price_changed).New()); + foreach (var new_order in adds) { + var price = get_price(new_order); + if (bd.TryGetValue(price, out var index)) { + bd[price] = index.Add(new_order.order.Key, new_order); + } else { + bd[price] = ImmutableDictionary.CreateRange(new[] { + new KeyValuePair(new_order.order.Key, new_order) + }); + } + } + o.OnNext((state = bd.ToImmutable(), table.state)); + }); + return sub; + }); + + bool price_changed(Change ch) => + price_comp.Compare(ch.New.order.ui_price(), ch.Old.order.ui_price()) != 0; + + double get_price(OrderRecordTuple order) { + var p = order.order.ui_price(); + if (!(normalize_price is null)) + p = normalize_price(p); + return p; + } + } + + double _normalize_price(double price) => + TickUtils.normalize_price(spec, price); + + bool _validate_price(Side side, double price, [MaybeNullWhen(true)] out string? msg) { + msg = null; + if (!price.is_real()) { + msg = "not a real number"; + } else if (settlement.is_real()) { + var ticks_from_settle = security.tickdiff(price, settlement); + if (ticks_from_settle.HasValue) { + var max_cross = (current_settings?.ladder_order_limits?.max_settlement_cross_ticks) + .as_nullable(); + if (max_cross.HasValue && + (side == Side.Sell ? + ticks_from_settle < (-1 * max_cross.Value) : + ticks_from_settle > max_cross.Value) + ) { + msg = $"exceeds settle cross ticks limit ({ticks_from_settle.Value})"; + } + } + } + return msg is null; + } + + void _update_header() { + bool last_updated = md.get_last_trade( + ref _last_trade_time, out var last, out var _, out var volume); + if (_misc_time == _model.md.misc_timestamp && !last_updated) { + return; + } + + _session_high.set(md.session_high); + _session_low.set(md.session_low); + _open.set(md.open_price); + _settlement.set(md.settlement_price); + if (md.get_bbo(ref _last_bbo_time, out var bid, out var ask)) { + _bid_price.set(bid.price); + _ask_price.set(ask.price); + } + _day_change.set(last.price.if_nan(mid_price) - md.settlement_price); + _volume.set(volume); + _misc_time = _model.md.misc_timestamp; + } + + void _send_rfq(RFQRequestImmutable req) => + _bus.post(SparkTags.RFQSend, req); + + void _show_book() { + var ob_settings = bts.shell.orderbook.OrderBookStartupData.Default; + ob_settings.filters = new bts.shell.orderbook.FilterStates { + security_criteria = SecurityCriteria.from_securities(security) + }; + _bus.post(SparkTags.ShowOrderBookTag, ob_settings); + } + + void _show_ticket() { + if (order_properties_vm is null) { + return; + } + _bus.post( + SparkTags.ShowOrderTicketTag, + new(new(order_properties_vm.create(Side.Buy)), 0d, 0u)); + } + + void _tick() { + _update_header(); + on_tick?.Invoke(); + } + } +} diff --git a/src/client/spark/Modules/Trading/Ladder/View/LadderGridHost.cs b/src/client/spark/Modules/Trading/Ladder/View/LadderGridHost.cs index 8d76af989..4d60f5167 100644 --- a/src/client/spark/Modules/Trading/Ladder/View/LadderGridHost.cs +++ b/src/client/spark/Modules/Trading/Ladder/View/LadderGridHost.cs @@ -1401,7 +1401,10 @@ namespace mbts.spark { double _get_bid_market_break() { double best_bid = _get_top_price(_bids); double best_ask = _get_top_price(_asks); - return LadderPriceLineViewAdapter.bid_line(best_bid, best_ask, _vm.settlement, _spec); + var v = best_bid + .if_nan(_spec.tickdown(best_ask)) + .if_nan(_vm.settlement); + return _spec.round_to_tick(v, RoundingMode.AbsDown); } double _normalize_price(double price) => @@ -1410,13 +1413,20 @@ namespace mbts.spark { double _get_ask_market_break() { double best_bid = _get_top_price(_bids); double best_ask = _get_top_price(_asks); - return LadderPriceLineViewAdapter.ask_line(best_bid, best_ask, _vm.settlement, _spec); + var v = _spec.tickdown(best_ask) + .if_nan(best_bid) + .if_nan(_vm.settlement); + return _spec.round_to_tick(v, RoundingMode.AbsDown); } double _get_mid_market_break() { double best_bid = _get_top_price(_bids); double best_ask = _get_top_price(_asks); - return LadderPriceLineViewAdapter.mid_line(best_bid, best_ask, _vm.settlement, _spec); + var v = TickUtils.mid_tick(_spec, best_bid, best_ask) + .if_nan(best_bid) + .if_nan(_spec?.tickdown(best_ask) ?? double.NaN) + .if_nan(_vm.settlement); + return _spec.round_to_tick(v, RoundingMode.AbsDown); } double _get_session_low() => _normalize_price(_get_session_low_raw()); diff --git a/src/client/spark/Modules/Trading/Ladder/View/LadderPriceLineViewAdapter.cs b/src/client/spark/Modules/Trading/Ladder/View/LadderPriceLineViewAdapter.cs deleted file mode 100644 index 83acedd61..000000000 --- a/src/client/spark/Modules/Trading/Ladder/View/LadderPriceLineViewAdapter.cs +++ /dev/null @@ -1,62 +0,0 @@ -using bts.api; - -namespace mbts.spark { - using RegionalTickFactors = user.settings.RegionalTickFactors; - - class LadderPriceLineViewAdapter { - public static double bid_line( - double bid, double ask, double settlement, RegionalTickFactors spec) { - return TickUtils.normalize_price(spec, impl()); - double impl() { - if (!double.IsNaN(bid)) { - return bid; - } - if (!double.IsNaN(ask)) { - return _try_tick_down(spec, ask); - } - return settlement; - } - } - - public static double ask_line( - double bid, double ask, double settlement, RegionalTickFactors spec) { - return TickUtils.normalize_price(spec, impl()); - double impl() { - if (!double.IsNaN(ask)) { - return _try_tick_down(spec, ask); - } - if (!double.IsNaN(bid)) { - return bid; - } - return settlement; - } - } - - public static double mid_line( - double bid, double ask, double settlement, RegionalTickFactors spec) { - return TickUtils.normalize_price(spec, impl()); - double impl() { - if (double.IsNaN(bid)) { - if (double.IsNaN(ask)) { - return settlement; - } - return _try_tick_down(spec, ask); - } - if (double.IsNaN(ask)) { - return bid; - } - if (spec is not null) { - return TickUtils.mid_tick(spec, bid, ask); - } - return bid; - } - } - - static double _try_tick_down(RegionalTickFactors spec, double value) { - if (spec is not null) { - return spec.tickdown(value); - } - return value; - } - } -} diff --git a/src/client/spark_api/data/ticks/TickExtensions.cs b/src/client/spark_api/data/ticks/TickExtensions.cs index ad564f133..4a2982565 100644 --- a/src/client/spark_api/data/ticks/TickExtensions.cs +++ b/src/client/spark_api/data/ticks/TickExtensions.cs @@ -63,7 +63,7 @@ namespace mbts { if (ticks_per_base.is_int()) { return true; } - return tick.tick_unit > tick.tick_base && tick.tick_base == 1; + return tick.tick_unit > tick.tick_base && tick.tick_unit_frac().is_int(); } public static bool is_valid(this RegionalTickFactors regional_tick) => @@ -179,10 +179,7 @@ namespace mbts { if (T.IsInfinity(value)) { return value.ToString(); } - return tick?.is_valid() ?? false ? - _format_tick(tick, value, settings) : - _format_no_tick( - value, settings.display_multiplier.as_type(), settings.show_commas); + return _format_tick(tick, value, settings); } public static string format( diff --git a/src/client/spark_api/data/ticks/TickUtils.cs b/src/client/spark_api/data/ticks/TickUtils.cs index 94bae68a7..ec7da71b3 100644 --- a/src/client/spark_api/data/ticks/TickUtils.cs +++ b/src/client/spark_api/data/ticks/TickUtils.cs @@ -6,6 +6,7 @@ using bts.utils; using mbts.user.settings; using Spark.Core; +using Spark.Core.Math; using System; using System.Collections.Generic; @@ -189,52 +190,58 @@ namespace mbts.spark { public static int compare_tick_fallback_to_double(this ContractSpecificationImmutable contract, double x, double y) => tick_equals(contract, x, y) ? 0 : x.CompareTo(y); - public static double round_to_tick(this ContractSpecificationImmutable spec, double value) => - round_to_tick(spec.ticksize(value), value); + public static double round_to_tick(this ContractSpecificationImmutable spec, double value, RoundingMode rounding_mode = RoundingMode.Closest) => + round_to_tick(spec.ticksize(value), value, rounding_mode); - public static decimal round_to_tick(this ContractSpecificationImmutable spec, decimal value) => - round_to_tick((decimal)spec.ticksize((double)value), value); + public static decimal round_to_tick(this ContractSpecificationImmutable spec, decimal value, RoundingMode rounding_mode = RoundingMode.Closest) => + round_to_tick((decimal)spec.ticksize((double)value), value, rounding_mode); - public static double round_to_tick(this RegionalTickFactors rtick, double value) => - round_to_tick(rtick.ticksize(value), value); + public static double round_to_tick(this RegionalTickFactors rtick, double value, RoundingMode rounding_mode = RoundingMode.Closest) => + round_to_tick(rtick.ticksize(value), value, rounding_mode); - public static decimal round_to_tick(this RegionalTickFactors rtick, decimal value) => - round_to_tick((decimal)rtick.ticksize((double)value), value); + public static decimal round_to_tick(this RegionalTickFactors rtick, decimal value, RoundingMode rounding_mode = RoundingMode.Closest) => + round_to_tick((decimal)rtick.ticksize((double)value), value, rounding_mode); - public static double round_to_tick(double tick_size, double value) { - double intpart = (long)value; - double floatpart = value % 1; - floatpart = ((int)Math.Round(floatpart / tick_size)) * tick_size; - return intpart + floatpart; + public static double round_to_tick(double tick_size, double value, RoundingMode rounding_mode = RoundingMode.Closest) { + double n = rounding_mode switch { + RoundingMode.Closest => Math.Round(value / tick_size), + RoundingMode.Up => Math.Ceiling((value - _precision_const) / tick_size), + RoundingMode.Down => Math.Floor((value + _precision_const) / tick_size), + RoundingMode.AbsUp => value < 0 + ? Math.Floor((value + _precision_const) / tick_size) + : Math.Ceiling((value - _precision_const) / tick_size), + RoundingMode.AbsDown => value < 0 + ? Math.Ceiling((value - _precision_const) / tick_size) + : Math.Floor((value + _precision_const) / tick_size), + _ => double.NaN, + }; + return n * tick_size; } - public static decimal round_to_tick(decimal tick_size, decimal value) { - decimal intpart = (long)value; - decimal floatpart = value % 1; - floatpart = ((int)(floatpart / tick_size)) * tick_size; - return intpart + floatpart; + public static decimal round_to_tick(decimal tick_size, decimal value, RoundingMode rounding_mode = RoundingMode.Closest) { + decimal n = rounding_mode switch { + RoundingMode.Closest => Math.Round(value / tick_size), + RoundingMode.Up => Math.Ceiling(value / tick_size), + RoundingMode.Down => Math.Floor(value / tick_size), + RoundingMode.AbsUp => value < 0 + ? Math.Floor(value / tick_size) + : Math.Ceiling(value / tick_size), + RoundingMode.AbsDown => value < 0 + ? Math.Ceiling(value / tick_size) + : Math.Floor(value / tick_size), + _ => throw new ArgumentException("Invalid rounding mode", nameof(rounding_mode)), + }; + return n * tick_size; } - public static long? count_ticks(this RegionalTickFactors rtick, double value) { - if (!rtick.is_valid()) { - return null; - } + public static long? count_ticks(this RegionalTickFactors rtick, double value, RoundingMode rounding_mode = RoundingMode.AbsDown) { + var rounded_value = rtick.round_to_tick(value, rounding_mode); var n = _count_ticks( rtick.low_tick.tick_unit_frac(), rtick.low_tick_inclusive_end, rtick.high_tick.tick_unit_frac(), 0, - value); - var orig_n = n; - // Enforce proper rounding - var rounded_val = rtick.round_to_tick(value); - var half_tick = rtick.get_tick_for(value).tick_unit_frac() / 2; - if (n < 0 && (value - rounded_val) > half_tick) { - ++n; - } else if (n > 0 && (rounded_val - value) > half_tick) { - --n; - } - Log.assert(n == orig_n); + rounded_value); return n; } @@ -253,71 +260,19 @@ namespace mbts.spark { return tick; } - public static RegionalTickFactors multiply_tick_size(RegionalTickFactors spec, uint factor) { - factor = _fit_ticks_per_row_to_dollars(spec, factor) ?? 1; - return new( + public static RegionalTickFactors multiply_tick_size(RegionalTickFactors spec, uint factor) => + new( new(spec.low_tick.tick_base, spec.low_tick.tick_unit * factor), new(spec.high_tick.tick_base, spec.high_tick.tick_unit * factor), spec.low_tick_inclusive_end); - } public static double normalize_price(RegionalTickFactors rtick, double price) { - if (!price.is_real()) { + var maybe_ticks = rtick.count_ticks(price); + if (!maybe_ticks.HasValue) { return price; } - var ticks = rtick.count_ticks(price); - if (!ticks.HasValue) { - return price; - } - var normalized = rtick.tick(0, ticks.Value); - var tick = price > rtick.low_tick_inclusive_end ? rtick.high_tick : rtick.low_tick; - // Diff should always be < 1/2 tick - Log.assert((normalized - price).abs() < tick.tick_unit_frac() * 0.5); - return normalized; - } - - public static uint fit_ticks_per_row_to_dollars(SecurityImmutable sec, uint ticks_per_row) => - _fit_ticks_per_row_to_dollars(sec, ticks_per_row) ?? 1; - - public static uint fit_ticks_per_row_to_dollars(RegionalTickFactors rtick, uint ticks_per_row) => - _fit_ticks_per_row_to_dollars(rtick, ticks_per_row) ?? 1; - - static uint? _fit_ticks_per_row_to_dollars(SecurityImmutable sec, uint ticks_per_row) => - _fit_ticks_per_row_to_dollars(sec.regional_ticks(), ticks_per_row); - - static uint? _fit_ticks_per_row_to_dollars(RegionalTickFactors tf, uint ticks_per_row) { - if (ticks_per_row == 0) - return null; - // it is assumed that low tick will be the same as high tick; - // however, best to double check - return null if this isn't the case (let the caller decide what to do). - if (!tf.low_tick.Equals(tf.high_tick) || !tf.is_valid() || tf.low_tick.is_integer()) - return null; - var ticks_per_dollar = (uint)(tf.low_tick.tick_base / tf.low_tick.tick_unit); - // if ticks_per_row is greater than ticks_per_dollar, round to a multiple of ticks_per_dollar - if (ticks_per_row > ticks_per_dollar) { - if (ticks_per_dollar == 0) { - return null; - } - return (uint)(ticks_per_dollar * Math.Floor((double)(ticks_per_row / ticks_per_dollar))); - } else if (ticks_per_row == ticks_per_dollar) { - return ticks_per_row; - } else { - uint max_decrease_adj = ticks_per_row; - uint max_increase_adj = ticks_per_dollar - ticks_per_row - 1; - for (uint adj = 0; adj < Math.Max(max_decrease_adj, max_increase_adj); adj++) { - if (adj < max_decrease_adj) { - var result = ticks_per_row - adj; - if (ticks_per_dollar % result == 0) - return result; - } - if (adj < max_increase_adj) { - var result = ticks_per_row + adj; - if (ticks_per_dollar % result == 0) - return result; - } - } - } - return null; + var ticks = maybe_ticks.Value; + return rtick.tick(0, (long)ticks); } static long? _count_ticks( @@ -367,8 +322,20 @@ namespace mbts.spark { static long count_single_tick_sz( double tick_sz, double from, double to) { - var from_n = (long)MathUtils.round_fractional_units(from, tick_sz); - var to_n = (long)MathUtils.round_fractional_units(to, tick_sz); + from = round_to_tick(tick_sz, from, RoundingMode.AbsDown); + to = round_to_tick(tick_sz, to, RoundingMode.AbsDown); + if (from < 0) { + from -= _precision_const; + } else { + from += _precision_const; + } + if (to < 0) { + to -= _precision_const; + } else { + to += _precision_const; + } + var from_n = (long)(from / tick_sz); + var to_n = (long)(to / tick_sz); return to_n - from_n; } } diff --git a/src/client/spark_core/Math/RoundingMode.cs b/src/client/spark_core/Math/RoundingMode.cs new file mode 100644 index 000000000..a71ccfacf --- /dev/null +++ b/src/client/spark_core/Math/RoundingMode.cs @@ -0,0 +1,17 @@ +#nullable enable + +namespace Spark.Core.Math; + +public enum RoundingMode { + None, + // Round to the closest integer (up if decimal part is >= 0.5, otherwise down) + Closest, + // Round up + Up, + // Round down + Down, + // Round positive numbers up, and negative numbers down + AbsUp, + // Round positive numbers down, and negative numbers up + AbsDown +} diff --git a/src/client/spark_test/Security/TickTests.cs b/src/client/spark_test/Security/TickTests.cs index 4b5adbc12..dbc46a315 100644 --- a/src/client/spark_test/Security/TickTests.cs +++ b/src/client/spark_test/Security/TickTests.cs @@ -6,6 +6,8 @@ using mbts; using mbts.spark; using mbts.user.settings; +using Spark.Core.Math; + using System; using System.Collections.Generic; using System.Linq; @@ -159,7 +161,7 @@ namespace bts.tests.security { var price_break = tick.low_tick_inclusive_end; foreach (var p in prices) { var expected_ticks_from_zero = TickTestHelper.count_ticks(tick, p); - var actual_ticks_from_zero = TickUtils.count_ticks(tick, p); + var actual_ticks_from_zero = TickUtils.count_ticks(tick, p, RoundingMode.Closest); Assert.That(expected_ticks_from_zero == actual_ticks_from_zero, $"Expected ticks from zero to be '{expected_ticks_from_zero}', actually '{actual_ticks_from_zero}' " + $"(low/high/pricebreak: {tick.low_tick}/{tick.high_tick}/{price_break}, price: {p}).");