From f9fbf9c45a828522efa614d4c62bcf8580259ba6 Mon Sep 17 00:00:00 2001 From: Jake Norbut Date: Mon, 9 Jul 2018 15:40:58 -0500 Subject: [PATCH 01/15] SPARK-1435 --- src/client/spark/view/Spark/PAndL/PAndLVM.cs | 115 ++++++++----- .../spark/view/Spark/PAndL/PAndLView.xaml | 142 +++++++++------ .../spark/view/Spark/PAndL/PnLCalculator.cs | 66 ++++--- src/client/spark/view/Spark/PAndL/PnLData.cs | 12 +- .../spark/view/Spark/PAndL/PnLSummaryRow.cs | 162 ++++++++++++------ 5 files changed, 315 insertions(+), 182 deletions(-) diff --git a/src/client/spark/view/Spark/PAndL/PAndLVM.cs b/src/client/spark/view/Spark/PAndL/PAndLVM.cs index 757b927af..3635b04fa 100644 --- a/src/client/spark/view/Spark/PAndL/PAndLVM.cs +++ b/src/client/spark/view/Spark/PAndL/PAndLVM.cs @@ -2,6 +2,7 @@ using mbts.spark.filters; using mbts.ui; using mbts.ui.shell; +using mbts.ui.utility; using System; using System.Collections.Generic; using System.Collections.ObjectModel; @@ -13,17 +14,23 @@ using static bts.shell.PAndLWindowFactory; namespace mbts.spark { class PAndLVM : DisposableViewModelBase { + readonly Property _selected_pnl_calc_type; public PAndLVM(IBus bus, PAndLModel model, PAndLStartupData state) { _bus = bus; _model = model; + _selected_pnl_calc_type = backing(nameof(selected_pnl_calc_type)); + // get initial value from settings + // else assume waterfall + _selected_pnl_calc_type.Value = pnl_calc_type.midpoint; + _selected_pnl_calc_type.Changed += pnl_calc_type_changed; var pnl = model.on_pnl_data .Sample(_POSITION_UPDATE_PERIOD) .OnDispatcher() .Subscribe(p => { if (p != null) { - PnLCalculator calc = new PnLCalculator(p.state.Values); + PnLCalculator calc = new PnLCalculator(p.state.Values, _selected_pnl_calc_type.Value); var summary_position_rows = calc.get_summary_position(); _pnl_data.sync_with(summary_position_rows); _last_pnl_update_time = DateTime.Now; @@ -48,18 +55,31 @@ namespace mbts.spark { _dispose = Disposable.Create(pnl, DataGridFilterHelper.hook_filters(pnl_view, - security_filter, pnl_filter, - buy_quantity_filter, sell_quantity_filter, - net_position_filter, weighted_average_buy_filter, - weighted_average_sell_filter, pnl_price_filter, - sod_position_filter, account_filter, - exchange_string_filter, symbol_filter), + account_filter, + exchange_string_filter, + symbol_filter, + security_filter, + start_position_filter, + start_pnl_filter, + day_long_quantity_filter, + day_short_quantity_filter, + day_pnl_filter, + total_net_position_filter, + total_pnl_filter, + pnl_price_filter, + weighted_average_buy_filter, + weighted_average_sell_filter), WorkLoop.Start("PAndL", _UPDATE_PERIOD, _calculate_pnl) ); } + private void pnl_calc_type_changed(pnl_calc_type oldval, pnl_calc_type newval) { + _calculate_pnl(); + } + protected override void Dispose(bool disposing) { pnl_view.CollectionChanged -= Pnl_view_CollectionChanged; + _selected_pnl_calc_type.Changed -= pnl_calc_type_changed; } @@ -69,10 +89,10 @@ namespace mbts.spark { void _update_totals() { if (pnl_view != null) { - total_pnl = pnl_view.Cast().Where(r => !Double.IsNaN(r.pnl)).Sum(r => r.pnl); - total_net_pos = pnl_view.Cast().Sum(r => r.net_position); - total_buy_qty = pnl_view.Cast().Sum(r => r.buy_quantity); - total_sell_qty = pnl_view.Cast().Sum(r => r.sell_quantity); + total_aggregate_pnl = pnl_view.Cast().Where(r => !Double.IsNaN(r.total_pnl)).Sum(r => r.total_pnl); + total_aggregate_net_pos = pnl_view.Cast().Sum(r => r.total_net_position); + total_aggregate_buy_qty = pnl_view.Cast().Sum(r => r.day_long_quantity); + total_aggregate_sell_qty = pnl_view.Cast().Sum(r => r.day_short_quantity); } } @@ -81,8 +101,11 @@ namespace mbts.spark { // position update in a while if (DateTime.Now.Subtract(_last_pnl_update_time) > _UPDATE_PERIOD) { foreach (var r in _pnl_data) { - r.update_pnl(pnl_calc_type.waterfall); + if (_selected_pnl_calc_type.Value != pnl_calc_type.none) { + r.update_pnl(_selected_pnl_calc_type.Value); + } } + _update_totals(); } } @@ -90,57 +113,67 @@ namespace mbts.spark { private ObservableCollection _pnl_data = new ObservableCollection(); public ICollectionView pnl_view { get; } - private double _total_pnl; - public double total_pnl { + public List pnl_calc_types { get; } = EnumHelper.get_values_except(pnl_calc_type.none, pnl_calc_type.waterfall, pnl_calc_type.bid_or_ask, pnl_calc_type.open, pnl_calc_type.close).ToList(); + + public pnl_calc_type selected_pnl_calc_type { + get => _selected_pnl_calc_type.Value; + set => _selected_pnl_calc_type.Value = value; + } + + private double _total_aggregate_pnl; + public double total_aggregate_pnl { get { - return _total_pnl; + return _total_aggregate_pnl; } set { - _total_pnl = value; - RaisePropertyChanged(nameof(total_pnl)); + _total_aggregate_pnl = value; + RaisePropertyChanged(nameof(total_aggregate_pnl)); } } - private double _total_net_pos; - public double total_net_pos { - get { return _total_net_pos; } + private double _total_aggregate_net_pos; + public double total_aggregate_net_pos { + get { return _total_aggregate_net_pos; } set { - _total_net_pos = value; - RaisePropertyChanged(nameof(total_net_pos)); + _total_aggregate_net_pos = value; + RaisePropertyChanged(nameof(total_aggregate_net_pos)); } } - private double _total_buy_qty; - public double total_buy_qty { - get { return _total_buy_qty; } + private double _total_aggregate_buy_qty; + public double total_aggregate_buy_qty { + get { return _total_aggregate_buy_qty; } set { - _total_buy_qty = value; - RaisePropertyChanged(nameof(total_buy_qty)); + _total_aggregate_buy_qty = value; + RaisePropertyChanged(nameof(total_aggregate_buy_qty)); } } - private double _total_sell_qty; - public double total_sell_qty { - get { return _total_sell_qty; } + private double _total_aggregate_sell_qty; + public double total_aggregate_sell_qty { + get { return _total_aggregate_sell_qty; } set { - _total_sell_qty = value; - RaisePropertyChanged(nameof(total_sell_qty)); + _total_aggregate_sell_qty = value; + RaisePropertyChanged(nameof(total_aggregate_sell_qty)); } } #region Filters - public IDataGridColumnPersistentFilter security_filter { get; } = new RegexFilterVM(r => r.security_text, nameof(PnLSummaryRow.security_text)); - public IDataGridColumnPersistentFilter pnl_filter { get; } = new DoubleMinMax(r => r.pnl, nameof(PnLSummaryRow.pnl)); - public IDataGridColumnPersistentFilter buy_quantity_filter { get; } = new DoubleMinMax(r => r.buy_quantity, nameof(PnLSummaryRow.buy_quantity)); - public IDataGridColumnPersistentFilter sell_quantity_filter { get; } = new DoubleMinMax(r => r.sell_quantity, nameof(PnLSummaryRow.sell_quantity)); - public IDataGridColumnPersistentFilter net_position_filter { get; } = new DoubleMinMax(r => r.net_position, nameof(PnLSummaryRow.net_position)); - public IDataGridColumnPersistentFilter weighted_average_buy_filter { get; } = new DoubleMinMax(r => r.weighted_average_buy, nameof(PnLSummaryRow.weighted_average_buy)); - public IDataGridColumnPersistentFilter weighted_average_sell_filter { get; } = new DoubleMinMax(r => r.weighted_average_sell, nameof(PnLSummaryRow.weighted_average_sell)); - public IDataGridColumnPersistentFilter pnl_price_filter { get; } = new DoubleMinMax(r => r.pnl_price, nameof(PnLSummaryRow.pnl_price)); - public IDataGridColumnPersistentFilter sod_position_filter { get; } = new DoubleMinMax(r => r.sod_position, nameof(PnLSummaryRow.sod_position)); + public IDataGridColumnPersistentFilter account_filter { get; } = new RegexFilterVM(r => r.account, nameof(PnLSummaryRow.account)); public IDataGridColumnPersistentFilter exchange_string_filter { get; } = new RegexFilterVM(r => r.exchange_string, nameof(PnLSummaryRow.exchange_string)); public IDataGridColumnPersistentFilter symbol_filter { get; } = new RegexFilterVM(r => r.symbol, nameof(PnLSummaryRow.symbol)); + public IDataGridColumnPersistentFilter security_filter { get; } = new RegexFilterVM(r => r.security_text, nameof(PnLSummaryRow.security_text)); + public IDataGridColumnPersistentFilter start_position_filter { get; } = new DoubleMinMax(r => r.start_net_position, nameof(PnLSummaryRow.start_net_position)); + public IDataGridColumnPersistentFilter start_pnl_filter { get; } = new DoubleMinMax(r => r.start_pnl, nameof(PnLSummaryRow.start_pnl)); + public IDataGridColumnPersistentFilter day_long_quantity_filter { get; } = new DoubleMinMax(r => r.day_long_quantity, nameof(PnLSummaryRow.day_long_quantity)); + public IDataGridColumnPersistentFilter day_short_quantity_filter { get; } = new DoubleMinMax(r => r.day_short_quantity, nameof(PnLSummaryRow.day_short_quantity)); + public IDataGridColumnPersistentFilter day_pnl_filter { get; } = new DoubleMinMax(r => r.day_pnl, nameof(PnLSummaryRow.day_pnl)); + public IDataGridColumnPersistentFilter total_net_position_filter { get; } = new DoubleMinMax(r => r.total_net_position, nameof(PnLSummaryRow.total_net_position)); + public IDataGridColumnPersistentFilter total_pnl_filter { get; } = new DoubleMinMax(r => r.total_pnl, nameof(PnLSummaryRow.total_pnl)); + public IDataGridColumnPersistentFilter pnl_price_filter { get; } = new DoubleMinMax(r => r.pnl_price, nameof(PnLSummaryRow.pnl_price)); + public IDataGridColumnPersistentFilter weighted_average_buy_filter { get; } = new DoubleMinMax(r => r.weighted_average_buy, nameof(PnLSummaryRow.weighted_average_buy)); + public IDataGridColumnPersistentFilter weighted_average_sell_filter { get; } = new DoubleMinMax(r => r.weighted_average_sell, nameof(PnLSummaryRow.weighted_average_sell)); #endregion diff --git a/src/client/spark/view/Spark/PAndL/PAndLView.xaml b/src/client/spark/view/Spark/PAndL/PAndLView.xaml index c43ff29c9..01564d81f 100644 --- a/src/client/spark/view/Spark/PAndL/PAndLView.xaml +++ b/src/client/spark/view/Spark/PAndL/PAndLView.xaml @@ -25,13 +25,19 @@ + - + + - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -117,20 +159,13 @@ + - + --> - + - - + + @@ -169,8 +197,8 @@ - - + + @@ -182,8 +210,8 @@ - - + + @@ -195,8 +223,8 @@ - - + + diff --git a/src/client/spark/view/Spark/PAndL/PnLCalculator.cs b/src/client/spark/view/Spark/PAndL/PnLCalculator.cs index 2526ba0b3..e8af91ba9 100644 --- a/src/client/spark/view/Spark/PAndL/PnLCalculator.cs +++ b/src/client/spark/view/Spark/PAndL/PnLCalculator.cs @@ -77,16 +77,18 @@ namespace mbts.spark { class PnLCalculator { readonly IEnumerable _data; + readonly pnl_calc_type _calc_type; - public PnLCalculator(IEnumerable data) { + public PnLCalculator(IEnumerable data, pnl_calc_type calc_type) { _data = data; + _calc_type = calc_type; } public IEnumerable get_summary_position() { return (from pnl_item in _data group pnl_item by (pnl_item.account, pnl_item.exchange, pnl_item.symbol, pnl_item.security, pnl_item.sec_md) into grouping let start_of_day = _get_start_of_day(grouping.Key.symbol) - select new PnLSummaryRow(grouping.Key, + select new PnLSummaryRow(_calc_type, start_of_day, grouping.Key, grouping.Where(y => y.fill.Timestamp.ToDateTime() >= start_of_day).Sum(y => y.buy_quantity), grouping.Where(y => y.fill.Timestamp.ToDateTime() >= start_of_day).Sum(y => y.sell_quantity), grouping.Sum(y => y.buy_quantity - y.sell_quantity), @@ -98,21 +100,23 @@ namespace mbts.spark { ); } - public static double get_driver(SecurityMD sec_md, pnl_calc_type pnl_request) { - ulong unused = 0; - sec_md.md.get_bbo(ref unused, out NativePriceSize bid, out NativePriceSize ask); - sec_md.md.get_last_trade(ref unused, out NativePriceSize last, out DateTime unused1, out ulong unused2); + public static bool get_driver(ref ulong bbo_time, ref ulong last_trade_time, SecurityMD sec_md, pnl_calc_type pnl_request, ref double driver_price) { + // check with eric as I'm not sure if i was every querying md correctly + if (!sec_md.md.get_bbo(ref bbo_time, out NativePriceSize bid, out NativePriceSize ask)) return false; + if (!sec_md.md.get_last_trade(ref last_trade_time, out NativePriceSize last, out DateTime unused1, out ulong unused2)) return false; if (pnl_request.HasFlag(pnl_calc_type.waterfall)) { // last price is available and withing range of available bid and ask if (!Double.IsNaN(last.price) && last.price >= bid.price && last.price <= ask.price) { - return last.price; + driver_price = last.price; + return true; } double mid = TickUtils.mid_tick(sec_md.security.ContractSpec, bid.price, ask.price); // last price is not valid, so try the mid if (!Double.IsNaN(mid)) { - return mid; + driver_price = mid; + return true; } // last bid @@ -120,9 +124,11 @@ namespace mbts.spark { if (!Double.IsNaN(last.price) && !Double.IsNaN(bid.price) && Double.IsNaN(ask.price)) { // if last >= bid then last else bid if (last.price >= bid.price) { - return last.price; + driver_price = last.price; + return true; } else { - return bid.price; + driver_price = bid.price; + return true; } } @@ -131,15 +137,18 @@ namespace mbts.spark { if (!Double.IsNaN(last.price) && !Double.IsNaN(ask.price) && Double.IsNaN(bid.price)) { // if last <= ask then last else ask if (last.price <= ask.price) { - return last.price; + driver_price = last.price; + return true; } else { - return ask.price; + driver_price = ask.price; + return true; } } // last only if (!Double.IsNaN(last.price)) { - return last.price; + driver_price = last.price; + return true; } // indicative, no support yet @@ -148,36 +157,43 @@ namespace mbts.spark { if ((!Double.IsNaN(bid.price) || !Double.IsNaN(ask.price)) && !Double.IsNaN(sec_md.md.settlement_price)) { // if bid and no ask and settle and bid > Settle if (!Double.IsNaN(bid.price) && Double.IsNaN(ask.price) && !Double.IsNaN(sec_md.md.settlement_price) && bid.price > sec_md.md.settlement_price) { - return bid.price; + driver_price = bid.price; + return true; } // if ask and no bid and settle and ask < Settle if (!Double.IsNaN(ask.price) && Double.IsNaN(bid.price) && !Double.IsNaN(sec_md.md.settlement_price) && ask.price < sec_md.md.settlement_price) { - return ask.price; + driver_price = ask.price; + return true; } } // Settlement // neither bid or ask are available if (!Double.IsNaN(sec_md.md.settlement_price)) { - return sec_md.md.settlement_price; + driver_price = sec_md.md.settlement_price; + return true; } // Close - return sec_md.md.close_price; + driver_price = sec_md.md.close_price; + return true; } // end waterfall - if (pnl_request.HasFlag(pnl_calc_type.last)) return last.price; - if (pnl_request.HasFlag(pnl_calc_type.mid)) return TickUtils.mid_tick(sec_md.security.ContractSpec, bid.price, ask.price); - if (pnl_request.HasFlag(pnl_calc_type.open)) return sec_md.md.open_price; - if (pnl_request.HasFlag(pnl_calc_type.close)) return sec_md.md.close_price; - if (pnl_request.HasFlag(pnl_calc_type.settle)) return sec_md.md.settlement_price; - return Double.NaN; + if (pnl_request.HasFlag(pnl_calc_type.last)) { driver_price = last.price; return true; } + // note that bid_or_ask is not considered here since this method only + // supports returning a single driver price; see update_pnl + if (pnl_request.HasFlag(pnl_calc_type.midpoint)) { driver_price = TickUtils.mid_tick(sec_md.security.ContractSpec, bid.price, ask.price); return true; } + if (pnl_request.HasFlag(pnl_calc_type.open)) { driver_price = sec_md.md.open_price; return true; } + if (pnl_request.HasFlag(pnl_calc_type.close)) { driver_price = sec_md.md.close_price; return true; } + if (pnl_request.HasFlag(pnl_calc_type.settle)) { driver_price = sec_md.md.settlement_price; return true; } + driver_price = Double.NaN; + return false; } public static double get_pnl(double bid_for_long, double ask_for_short, FillImmutable fill, double cpp) { - if (fill.Side == Side.Buy) { return _get_long_pnl(bid_for_long, fill.LastPrice, fill.LastShares, cpp); } - if (fill.Side == Side.Sell) { return _get_short_pnl(ask_for_short, fill.LastPrice, fill.LastShares, cpp); } + if (fill.Side == Side.Buy && !Double.IsNaN(bid_for_long)) { return _get_long_pnl(bid_for_long, fill.LastPrice, fill.LastShares, cpp); } + if (fill.Side == Side.Sell && !Double.IsNaN(ask_for_short)) { return _get_short_pnl(ask_for_short, fill.LastPrice, fill.LastShares, cpp); } return Double.NaN; } diff --git a/src/client/spark/view/Spark/PAndL/PnLData.cs b/src/client/spark/view/Spark/PAndL/PnLData.cs index b102b92b8..760d4b3cc 100644 --- a/src/client/spark/view/Spark/PAndL/PnLData.cs +++ b/src/client/spark/view/Spark/PAndL/PnLData.cs @@ -1,18 +1,26 @@ using bts.api; using bts.api.orderman; using System; +using System.ComponentModel; namespace mbts.spark { [Flags] public enum pnl_calc_type { none = 0, + [Description("Last Tradeable Price Avalanche")] waterfall = 1, + [Description("Last")] last = 2, - bid_and_ask = 4, - mid = 8, + [Description("Bid/Ask")] + bid_or_ask = 4, + [Description("Midpoint")] + midpoint = 8, + [Description("Open")] open = 16, + [Description("Close")] close = 32, + [Description("Settle")] settle = 64 } diff --git a/src/client/spark/view/Spark/PAndL/PnLSummaryRow.cs b/src/client/spark/view/Spark/PAndL/PnLSummaryRow.cs index 69ac5f485..32cd9dfa3 100644 --- a/src/client/spark/view/Spark/PAndL/PnLSummaryRow.cs +++ b/src/client/spark/view/Spark/PAndL/PnLSummaryRow.cs @@ -12,27 +12,33 @@ namespace mbts.spark { internal class PnLSummaryRow : ViewModelBase, IEquatable { + DateTime _start_of_day; (string account, Venue? exchange, string symbol, SecurityImmutable? security, SecurityMD? sec_md) key; - double _buy_quantity, _sell_quantity, _net_position, _sod_position, _pnl, _pnl_price, _weighted_average_buy, _weighted_average_sell; + double _day_long_quantity, _day_short_quantity, _total_net_position, _start_net_position, _total_pnl, _sod_pnl, _start_pnl, _pnl_price, _weighted_average_buy, _weighted_average_sell; IEnumerable _fills; + ulong _bbo_ref, _last_ref; + double _driver; //List _schedules = new List() { MarketSchedule.es_schedule }; - public PnLSummaryRow((string, Venue?, string, SecurityImmutable?, SecurityMD?) key, + public PnLSummaryRow(pnl_calc_type calc_type, + DateTime start_of_day, + (string, Venue?, string, SecurityImmutable?, SecurityMD?) key, double buy_quant, double sell_quant, double net_pos, double sod_pos, double wavg_buy, double wavg_sell, IEnumerable fills) { + this._start_of_day = start_of_day; this.key = key; - buy_quantity = buy_quant; - sell_quantity = sell_quant; - net_position = net_pos; - sod_position = sod_pos; + day_long_quantity = buy_quant; + day_short_quantity = sell_quant; + total_net_position = net_pos; + start_net_position = sod_pos; weighted_average_buy = wavg_buy; weighted_average_sell = wavg_sell; _fills = fills; // set the initial pnl and pnl_price when there has been a // position update i.e. this constructor - update_pnl(pnl_calc_type.waterfall); + update_pnl(calc_type); } private double _get_cpp_for_security(SecurityImmutable s) { @@ -56,26 +62,44 @@ namespace mbts.spark { public void update_pnl(pnl_calc_type pnl_request) { if (key.sec_md.HasValue) { double cpp = _get_cpp_for_security(key.security.Value); - if (pnl_request.HasFlag(pnl_calc_type.bid_and_ask)) { - ulong unused = 0; - key.sec_md.Value.md.get_bbo(ref unused, out NativePriceSize bid, out NativePriceSize ask); + if (pnl_request.HasFlag(pnl_calc_type.bid_or_ask)) { + key.sec_md.Value.md.get_bbo(ref _bbo_ref, out NativePriceSize bid, out NativePriceSize ask); double summary_pnl = 0.0; + double start_pnl_total = 0.0; + double day_pnl_total = 0.0; foreach (var fill in _fills) { double _tick_pnl = PnLCalculator.get_pnl(bid.price, ask.price, fill, cpp); summary_pnl += _tick_pnl; + if (fill.Timestamp.ToDateTime() >= _start_of_day) { + day_pnl_total += _tick_pnl; + } else { + start_pnl_total += _tick_pnl; + } } - pnl = summary_pnl; + total_pnl = summary_pnl; + day_pnl = day_pnl_total; + start_pnl = start_pnl_total; + pnl_price = Double.NaN; } else { - double driver = PnLCalculator.get_driver(key.sec_md.Value, pnl_request); - - double summary_pnl = 0.0; - foreach (var fill in _fills) { - double _tick_pnl = PnLCalculator.get_pnl(driver, fill, cpp); - summary_pnl += _tick_pnl; + if (PnLCalculator.get_driver(ref _bbo_ref, ref _last_ref, key.sec_md.Value, pnl_request, ref _driver)) { + double summary_pnl = 0.0; + double start_pnl_total = 0.0; + double day_pnl_total = 0.0; + foreach (var fill in _fills) { + double _tick_pnl = PnLCalculator.get_pnl(_driver, fill, cpp); + summary_pnl += _tick_pnl; + if (fill.Timestamp.ToDateTime() >= _start_of_day) { + day_pnl_total += _tick_pnl; + } else { + start_pnl_total += _tick_pnl; + } + } + total_pnl = summary_pnl; + day_pnl = day_pnl_total; + start_pnl = start_pnl_total; + pnl_price = _driver; } - pnl = summary_pnl; - pnl_price = driver; } } } @@ -89,9 +113,9 @@ namespace mbts.spark { key.exchange == other.exchange && key.security == other.security && key.symbol == other.symbol && - buy_quantity == other.buy_quantity && - sell_quantity == other.sell_quantity && - pnl == other.pnl; + day_long_quantity == other.day_long_quantity && + day_short_quantity == other.day_short_quantity && + total_pnl == other.total_pnl; } public override int GetHashCode() { @@ -104,7 +128,7 @@ namespace mbts.spark { } public override string ToString() { - return $"account: {account} exchange: {exchange_string} symbol: {symbol} security: {security_text} buy_quantity: {buy_quantity} sell_quantity: {sell_quantity} pnl: {pnl}"; + return $"account: {account} exchange: {exchange_string} symbol: {symbol} security: {security_text} buy_quantity: {day_long_quantity} sell_quantity: {day_short_quantity} pnl: {total_pnl}"; } public string account { @@ -140,56 +164,77 @@ namespace mbts.spark { set => ignore(); } - - public double buy_quantity { - get => _buy_quantity; + + public double start_net_position { + get => _start_net_position; set { - if (_buy_quantity != value) { - _buy_quantity = value; - RaisePropertyChanged(nameof(buy_quantity)); + if (_start_net_position != value) { + _start_net_position = value; + RaisePropertyChanged(nameof(start_net_position)); + } + } + } + public double start_pnl { + get => _start_pnl; + set { + if (_start_pnl != value) { + _start_pnl = value; + RaisePropertyChanged(); + } + } + } + public double day_long_quantity { + get => _day_long_quantity; + set { + if (_day_long_quantity != value) { + _day_long_quantity = value; + RaisePropertyChanged(nameof(day_long_quantity)); + } + } + } + public double day_short_quantity { + get => _day_short_quantity; + set { + if (_day_short_quantity != value) { + _day_short_quantity = value; + RaisePropertyChanged(nameof(day_short_quantity)); + } + } + } + public double day_pnl { + get => _sod_pnl; + set { + if (_sod_pnl != value) { + _sod_pnl = value; + RaisePropertyChanged(); } } } - public double sell_quantity { - get => _sell_quantity; + + + public double total_net_position { + get => _total_net_position; set { - if (_sell_quantity != value) { - _sell_quantity = value; - RaisePropertyChanged(nameof(sell_quantity)); + if (_total_net_position != value) { + _total_net_position = value; + RaisePropertyChanged(nameof(total_net_position)); } } } - public double sod_position { - get => _sod_position; + public double total_pnl { + get => _total_pnl; set { - if (_sod_position != value) { - _sod_position = value; - RaisePropertyChanged(nameof(sod_position)); + if (_total_pnl != value) { + _total_pnl = value; + RaisePropertyChanged(nameof(total_pnl)); } } } - public double net_position { - get => _net_position; - set { - if (_net_position != value) { - _net_position = value; - RaisePropertyChanged(nameof(net_position)); - } - } - } - public double pnl { - get => _pnl; - set { - if (_pnl != value) { - _pnl = value; - RaisePropertyChanged(nameof(pnl)); - } - } - } + public double pnl_price { get => _pnl_price; @@ -221,6 +266,9 @@ namespace mbts.spark { } } + //public IEnumerable sod_fills => _fills.Where(f => f.Timestamp.ToDateTime() >= _start_of_day); + //public IEnumerable pos_fills => _fills.Where(f => f.Timestamp.ToDateTime() < _start_of_day); + } From edf5c784050cf1b2a24092ac6a622281fa9bda6d Mon Sep 17 00:00:00 2001 From: Jake Norbut Date: Tue, 10 Jul 2018 16:56:23 -0500 Subject: [PATCH 02/15] part of SPARK-1454; column filters and sort criteria --- .../Modules/Trading/PAndLWindowFactory.cs | 49 +++++++++++++- src/client/spark/view/Spark/PAndL/PAndLVM.cs | 65 ++++++++++++++----- .../spark/view/Spark/PAndL/PAndLWindow.cs | 5 +- .../spark/view/Spark/PAndL/PnLCalculator.cs | 8 +-- .../spark/view/Spark/PAndL/PnLSummaryRow.cs | 14 ++-- 5 files changed, 113 insertions(+), 28 deletions(-) diff --git a/src/client/spark/Modules/Trading/PAndLWindowFactory.cs b/src/client/spark/Modules/Trading/PAndLWindowFactory.cs index b1f022725..f35adfb94 100644 --- a/src/client/spark/Modules/Trading/PAndLWindowFactory.cs +++ b/src/client/spark/Modules/Trading/PAndLWindowFactory.cs @@ -1,6 +1,7 @@ using bts.api; using bts.spark; using mbts.spark; +using mbts.spark.filters; using mbts.ui; using mbts.ui.spark; using ProtoBuf; @@ -20,7 +21,6 @@ namespace bts.shell { _dispose = bus.subscribe(SparkTags.ShowPAndLTag).OnDispatcher().Subscribe(show); } - public override Task load(PAndLStartupData state) { var w = new PAndLWindow(_model, this, _bus, state, SparkCommands.ShowPAndL.icon) as IShellWindow; return Task.FromResult(w); @@ -33,6 +33,53 @@ namespace bts.shell { [ProtoContract] public class PAndLStartupData { + + /// + /// Parameterless constructor for protobuf + /// + public PAndLStartupData() { } + + public PAndLStartupData(List sorting_criteria, FilterStates filters) { + this.sort_criteria = sorting_criteria; + this.filters = filters; + } + + [ProtoMember(5)] + public readonly List sort_criteria; + [ProtoMember(10)] + public FilterStates filters; + + + } + + [ProtoContract] + public class FilterStates { + [ProtoMember(1)] + public string account_regex; + [ProtoMember(2)] + public string exchange_regex; + [ProtoMember(3)] + public string symbol_regex; + [ProtoMember(4)] + public string security_regex; + [ProtoMember(5)] + public IntMinMaxState start_net_pos; + [ProtoMember(6)] + public DoubleMinMaxState start_pnl; + [ProtoMember(7)] + public UIntMinMaxState day_long_pos; + [ProtoMember(8)] + public UIntMinMaxState day_short_pos; + [ProtoMember(9)] + public DoubleMinMaxState day_pnl; + [ProtoMember(10)] + public IntMinMaxState total_net_pos; + [ProtoMember(11)] + public DoubleMinMaxState total_pnl; + [ProtoMember(12)] + public DoubleMinMaxState pnl_price; + + } } diff --git a/src/client/spark/view/Spark/PAndL/PAndLVM.cs b/src/client/spark/view/Spark/PAndL/PAndLVM.cs index 3635b04fa..b9669336f 100644 --- a/src/client/spark/view/Spark/PAndL/PAndLVM.cs +++ b/src/client/spark/view/Spark/PAndL/PAndLVM.cs @@ -37,14 +37,31 @@ namespace mbts.spark { } }); pnl_view = CollectionViewSource.GetDefaultView(_pnl_data); - pnl_view.SetSortingCriteria( - new List() { - new SortingCriteria("account", true) - , new SortingCriteria("exchange_string", true) - , new SortingCriteria("symbol", true) - , new SortingCriteria("security_text", true) - } - ); + + if (state?.filters is FilterStates fs) { + account_filter.load_state(fs.account_regex); + exchange_string_filter.load_state(fs.exchange_regex); + symbol_filter.load_state(fs.symbol_regex); + security_filter.load_state(fs.security_regex); + start_position_filter.load_state(fs.start_net_pos); + start_pnl_filter.load_state(fs.start_pnl); + day_long_quantity_filter.load_state(fs.day_long_pos); + day_short_quantity_filter.load_state(fs.day_short_pos); + day_pnl_filter.load_state(fs.day_pnl); + total_net_position_filter.load_state(fs.total_net_pos); + total_pnl_filter.load_state(fs.total_pnl); + pnl_price_filter.load_state(fs.pnl_price); + } + if (state != null && state.sort_criteria.Any()) { + pnl_view.SetSortingCriteria(state.sort_criteria); + } else { + pnl_view.SetSortingCriteria(new List() { + new SortingCriteria(nameof(PnLSummaryRow.account), true) + , new SortingCriteria(nameof(PnLSummaryRow.exchange_string), true) + , new SortingCriteria(nameof(PnLSummaryRow.symbol), true) + , new SortingCriteria(nameof(PnLSummaryRow.security_text), true) + }); + } pnl_view.CollectionChanged += Pnl_view_CollectionChanged; //Account[] accounts = @@ -127,7 +144,7 @@ namespace mbts.spark { } set { _total_aggregate_pnl = value; - RaisePropertyChanged(nameof(total_aggregate_pnl)); + RaisePropertyChanged(); } } @@ -136,7 +153,7 @@ namespace mbts.spark { get { return _total_aggregate_net_pos; } set { _total_aggregate_net_pos = value; - RaisePropertyChanged(nameof(total_aggregate_net_pos)); + RaisePropertyChanged(); } } @@ -145,7 +162,7 @@ namespace mbts.spark { get { return _total_aggregate_buy_qty; } set { _total_aggregate_buy_qty = value; - RaisePropertyChanged(nameof(total_aggregate_buy_qty)); + RaisePropertyChanged(); } } @@ -154,7 +171,7 @@ namespace mbts.spark { get { return _total_aggregate_sell_qty; } set { _total_aggregate_sell_qty = value; - RaisePropertyChanged(nameof(total_aggregate_sell_qty)); + RaisePropertyChanged(); } } @@ -164,19 +181,35 @@ namespace mbts.spark { public IDataGridColumnPersistentFilter exchange_string_filter { get; } = new RegexFilterVM(r => r.exchange_string, nameof(PnLSummaryRow.exchange_string)); public IDataGridColumnPersistentFilter symbol_filter { get; } = new RegexFilterVM(r => r.symbol, nameof(PnLSummaryRow.symbol)); public IDataGridColumnPersistentFilter security_filter { get; } = new RegexFilterVM(r => r.security_text, nameof(PnLSummaryRow.security_text)); - public IDataGridColumnPersistentFilter start_position_filter { get; } = new DoubleMinMax(r => r.start_net_position, nameof(PnLSummaryRow.start_net_position)); + public IDataGridColumnPersistentFilter start_position_filter { get; } = new IntMinMax(r => r.start_net_position, nameof(PnLSummaryRow.start_net_position)); public IDataGridColumnPersistentFilter start_pnl_filter { get; } = new DoubleMinMax(r => r.start_pnl, nameof(PnLSummaryRow.start_pnl)); - public IDataGridColumnPersistentFilter day_long_quantity_filter { get; } = new DoubleMinMax(r => r.day_long_quantity, nameof(PnLSummaryRow.day_long_quantity)); - public IDataGridColumnPersistentFilter day_short_quantity_filter { get; } = new DoubleMinMax(r => r.day_short_quantity, nameof(PnLSummaryRow.day_short_quantity)); + public IDataGridColumnPersistentFilter day_long_quantity_filter { get; } = new UIntMinMax(r => r.day_long_quantity, nameof(PnLSummaryRow.day_long_quantity)); + public IDataGridColumnPersistentFilter day_short_quantity_filter { get; } = new UIntMinMax(r => r.day_short_quantity, nameof(PnLSummaryRow.day_short_quantity)); public IDataGridColumnPersistentFilter day_pnl_filter { get; } = new DoubleMinMax(r => r.day_pnl, nameof(PnLSummaryRow.day_pnl)); - public IDataGridColumnPersistentFilter total_net_position_filter { get; } = new DoubleMinMax(r => r.total_net_position, nameof(PnLSummaryRow.total_net_position)); + public IDataGridColumnPersistentFilter total_net_position_filter { get; } = new IntMinMax(r => r.total_net_position, nameof(PnLSummaryRow.total_net_position)); public IDataGridColumnPersistentFilter total_pnl_filter { get; } = new DoubleMinMax(r => r.total_pnl, nameof(PnLSummaryRow.total_pnl)); public IDataGridColumnPersistentFilter pnl_price_filter { get; } = new DoubleMinMax(r => r.pnl_price, nameof(PnLSummaryRow.pnl_price)); public IDataGridColumnPersistentFilter weighted_average_buy_filter { get; } = new DoubleMinMax(r => r.weighted_average_buy, nameof(PnLSummaryRow.weighted_average_buy)); public IDataGridColumnPersistentFilter weighted_average_sell_filter { get; } = new DoubleMinMax(r => r.weighted_average_sell, nameof(PnLSummaryRow.weighted_average_sell)); + public FilterStates get_filters_states() => new FilterStates { + account_regex = account_filter.get_state(), + exchange_regex = exchange_string_filter.get_state(), + symbol_regex = exchange_string_filter.get_state(), + security_regex = security_filter.get_state(), + start_net_pos = start_position_filter.get_state(), + start_pnl = start_pnl_filter.get_state(), + day_long_pos = day_long_quantity_filter.get_state(), + day_short_pos = day_short_quantity_filter.get_state(), + day_pnl = day_pnl_filter.get_state(), + total_net_pos = total_net_position_filter.get_state(), + total_pnl = total_pnl_filter.get_state(), + pnl_price = pnl_price_filter.get_state() + }; + #endregion + public List get_sorting_states() => pnl_view.GetSortingCriteria(); readonly IBus _bus; readonly PAndLModel _model; diff --git a/src/client/spark/view/Spark/PAndL/PAndLWindow.cs b/src/client/spark/view/Spark/PAndL/PAndLWindow.cs index a3bb149f1..1c3e34d4d 100644 --- a/src/client/spark/view/Spark/PAndL/PAndLWindow.cs +++ b/src/client/spark/view/Spark/PAndL/PAndLWindow.cs @@ -27,7 +27,10 @@ namespace mbts.spark { public override string window_type => _window_type; public override PAndLWindowFactory.PAndLStartupData SaveState => _state = - new PAndLWindowFactory.PAndLStartupData(); + new PAndLWindowFactory.PAndLStartupData( + _vm.get_sorting_states(), + _vm.get_filters_states() + ); public override UIElement Content => _view; public override double MinWidth => 894; public string thread_id => PNL_THREAD_ID; diff --git a/src/client/spark/view/Spark/PAndL/PnLCalculator.cs b/src/client/spark/view/Spark/PAndL/PnLCalculator.cs index e8af91ba9..e409076c1 100644 --- a/src/client/spark/view/Spark/PAndL/PnLCalculator.cs +++ b/src/client/spark/view/Spark/PAndL/PnLCalculator.cs @@ -89,10 +89,10 @@ namespace mbts.spark { group pnl_item by (pnl_item.account, pnl_item.exchange, pnl_item.symbol, pnl_item.security, pnl_item.sec_md) into grouping let start_of_day = _get_start_of_day(grouping.Key.symbol) select new PnLSummaryRow(_calc_type, start_of_day, grouping.Key, - grouping.Where(y => y.fill.Timestamp.ToDateTime() >= start_of_day).Sum(y => y.buy_quantity), - grouping.Where(y => y.fill.Timestamp.ToDateTime() >= start_of_day).Sum(y => y.sell_quantity), - grouping.Sum(y => y.buy_quantity - y.sell_quantity), - grouping.Where(y => y.fill.Timestamp.ToDateTime() < start_of_day).Sum(y => y.buy_quantity - y.sell_quantity), + grouping.Where(y => y.fill.Timestamp.ToDateTime() >= start_of_day).Sum(y => (uint)y.buy_quantity), + grouping.Where(y => y.fill.Timestamp.ToDateTime() >= start_of_day).Sum(y => (uint)y.sell_quantity), + grouping.Sum(y => (int)(y.buy_quantity - y.sell_quantity)), + grouping.Where(y => y.fill.Timestamp.ToDateTime() < start_of_day).Sum(y => (int)(y.buy_quantity - y.sell_quantity)), grouping.weighted_average(y => y.fill.LastPrice, y => y.buy_quantity), grouping.weighted_average(y => y.fill.LastPrice, y => y.sell_quantity), grouping.Select(i => i.fill) diff --git a/src/client/spark/view/Spark/PAndL/PnLSummaryRow.cs b/src/client/spark/view/Spark/PAndL/PnLSummaryRow.cs index 32cd9dfa3..52f2f8120 100644 --- a/src/client/spark/view/Spark/PAndL/PnLSummaryRow.cs +++ b/src/client/spark/view/Spark/PAndL/PnLSummaryRow.cs @@ -14,7 +14,9 @@ namespace mbts.spark { internal class PnLSummaryRow : ViewModelBase, IEquatable { DateTime _start_of_day; (string account, Venue? exchange, string symbol, SecurityImmutable? security, SecurityMD? sec_md) key; - double _day_long_quantity, _day_short_quantity, _total_net_position, _start_net_position, _total_pnl, _sod_pnl, _start_pnl, _pnl_price, _weighted_average_buy, _weighted_average_sell; + int _start_net_position, _total_net_position; + uint _day_long_quantity, _day_short_quantity; + double _total_pnl, _sod_pnl, _start_pnl, _pnl_price, _weighted_average_buy, _weighted_average_sell; IEnumerable _fills; ulong _bbo_ref, _last_ref; double _driver; @@ -25,7 +27,7 @@ namespace mbts.spark { public PnLSummaryRow(pnl_calc_type calc_type, DateTime start_of_day, (string, Venue?, string, SecurityImmutable?, SecurityMD?) key, - double buy_quant, double sell_quant, double net_pos, double sod_pos, double wavg_buy, double wavg_sell, IEnumerable fills) { + uint buy_quant, uint sell_quant, int net_pos, int sod_pos, double wavg_buy, double wavg_sell, IEnumerable fills) { this._start_of_day = start_of_day; this.key = key; day_long_quantity = buy_quant; @@ -165,7 +167,7 @@ namespace mbts.spark { } - public double start_net_position { + public int start_net_position { get => _start_net_position; set { if (_start_net_position != value) { @@ -183,7 +185,7 @@ namespace mbts.spark { } } } - public double day_long_quantity { + public uint day_long_quantity { get => _day_long_quantity; set { if (_day_long_quantity != value) { @@ -192,7 +194,7 @@ namespace mbts.spark { } } } - public double day_short_quantity { + public uint day_short_quantity { get => _day_short_quantity; set { if (_day_short_quantity != value) { @@ -213,7 +215,7 @@ namespace mbts.spark { - public double total_net_position { + public int total_net_position { get => _total_net_position; set { if (_total_net_position != value) { From 54676d5aa90d55439ad4ed4ad1cb8206c1f2c220 Mon Sep 17 00:00:00 2001 From: Jake Norbut Date: Wed, 11 Jul 2018 09:12:06 -0500 Subject: [PATCH 03/15] Adding pnl_calc_type to state proro; tidying up VM --- .../Modules/Trading/PAndLWindowFactory.cs | 9 ++- src/client/spark/view/Spark/PAndL/PAndLVM.cs | 55 ++++++++++--------- .../spark/view/Spark/PAndL/PAndLWindow.cs | 13 +++-- 3 files changed, 42 insertions(+), 35 deletions(-) diff --git a/src/client/spark/Modules/Trading/PAndLWindowFactory.cs b/src/client/spark/Modules/Trading/PAndLWindowFactory.cs index f35adfb94..783b8550a 100644 --- a/src/client/spark/Modules/Trading/PAndLWindowFactory.cs +++ b/src/client/spark/Modules/Trading/PAndLWindowFactory.cs @@ -39,16 +39,21 @@ namespace bts.shell { /// public PAndLStartupData() { } - public PAndLStartupData(List sorting_criteria, FilterStates filters) { + public PAndLStartupData(List sorting_criteria, FilterStates filters) : + this(sorting_criteria, filters, pnl_calc_type.midpoint) { } + + public PAndLStartupData(List sorting_criteria, FilterStates filters, pnl_calc_type calc_type) { this.sort_criteria = sorting_criteria; this.filters = filters; + this.calc_type = calc_type; } [ProtoMember(5)] public readonly List sort_criteria; [ProtoMember(10)] public FilterStates filters; - + [ProtoMember(15)] + public pnl_calc_type calc_type; } diff --git a/src/client/spark/view/Spark/PAndL/PAndLVM.cs b/src/client/spark/view/Spark/PAndL/PAndLVM.cs index b9669336f..493b376eb 100644 --- a/src/client/spark/view/Spark/PAndL/PAndLVM.cs +++ b/src/client/spark/view/Spark/PAndL/PAndLVM.cs @@ -14,16 +14,18 @@ using static bts.shell.PAndLWindowFactory; namespace mbts.spark { class PAndLVM : DisposableViewModelBase { - readonly Property _selected_pnl_calc_type; - - - public PAndLVM(IBus bus, PAndLModel model, PAndLStartupData state) { + + public PAndLVM(IBus bus, PAndLModel model, PAndLStartupData startup_data) { _bus = bus; _model = model; _selected_pnl_calc_type = backing(nameof(selected_pnl_calc_type)); // get initial value from settings - // else assume waterfall - _selected_pnl_calc_type.Value = pnl_calc_type.midpoint; + // else default to midpoint + // TODO: + // need to respond to settings change somehow as the + // combobox that selected_pnl_calc_type is bound to will be + // gone from this form. + _selected_pnl_calc_type.Value = (startup_data != null && startup_data.calc_type != pnl_calc_type.none) ? startup_data.calc_type : pnl_calc_type.midpoint; _selected_pnl_calc_type.Changed += pnl_calc_type_changed; var pnl = model.on_pnl_data .Sample(_POSITION_UPDATE_PERIOD) @@ -38,7 +40,8 @@ namespace mbts.spark { }); pnl_view = CollectionViewSource.GetDefaultView(_pnl_data); - if (state?.filters is FilterStates fs) { + // restore filter state + if (startup_data?.filters is FilterStates fs) { account_filter.load_state(fs.account_regex); exchange_string_filter.load_state(fs.exchange_regex); symbol_filter.load_state(fs.symbol_regex); @@ -52,8 +55,9 @@ namespace mbts.spark { total_pnl_filter.load_state(fs.total_pnl); pnl_price_filter.load_state(fs.pnl_price); } - if (state != null && state.sort_criteria.Any()) { - pnl_view.SetSortingCriteria(state.sort_criteria); + // restore sort state or supply default value + if (startup_data?.sort_criteria?.Any() == true) { + pnl_view.SetSortingCriteria(startup_data.sort_criteria); } else { pnl_view.SetSortingCriteria(new List() { new SortingCriteria(nameof(PnLSummaryRow.account), true) @@ -64,12 +68,8 @@ namespace mbts.spark { } pnl_view.CollectionChanged += Pnl_view_CollectionChanged; - //Account[] accounts = - - - #region Create grid filters and load state - #endregion - + // setup the main Disposable and + // hook up grid filters _dispose = Disposable.Create(pnl, DataGridFilterHelper.hook_filters(pnl_view, account_filter, @@ -90,6 +90,10 @@ namespace mbts.spark { ); } + private void Pnl_view_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e) { + _update_totals(); + } + private void pnl_calc_type_changed(pnl_calc_type oldval, pnl_calc_type newval) { _calculate_pnl(); } @@ -98,12 +102,7 @@ namespace mbts.spark { pnl_view.CollectionChanged -= Pnl_view_CollectionChanged; _selected_pnl_calc_type.Changed -= pnl_calc_type_changed; } - - - private void Pnl_view_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e) { - _update_totals(); - } - + void _update_totals() { if (pnl_view != null) { total_aggregate_pnl = pnl_view.Cast().Where(r => !Double.IsNaN(r.total_pnl)).Sum(r => r.total_pnl); @@ -126,8 +125,8 @@ namespace mbts.spark { } } - private DateTime _last_pnl_update_time = DateTime.MinValue; - private ObservableCollection _pnl_data = new ObservableCollection(); + #region Properties + public ICollectionView pnl_view { get; } public List pnl_calc_types { get; } = EnumHelper.get_values_except(pnl_calc_type.none, pnl_calc_type.waterfall, pnl_calc_type.bid_or_ask, pnl_calc_type.open, pnl_calc_type.close).ToList(); @@ -137,7 +136,6 @@ namespace mbts.spark { set => _selected_pnl_calc_type.Value = value; } - private double _total_aggregate_pnl; public double total_aggregate_pnl { get { return _total_aggregate_pnl; @@ -148,7 +146,6 @@ namespace mbts.spark { } } - private double _total_aggregate_net_pos; public double total_aggregate_net_pos { get { return _total_aggregate_net_pos; } set { @@ -157,7 +154,6 @@ namespace mbts.spark { } } - private double _total_aggregate_buy_qty; public double total_aggregate_buy_qty { get { return _total_aggregate_buy_qty; } set { @@ -166,7 +162,6 @@ namespace mbts.spark { } } - private double _total_aggregate_sell_qty; public double total_aggregate_sell_qty { get { return _total_aggregate_sell_qty; } set { @@ -211,11 +206,17 @@ namespace mbts.spark { public List get_sorting_states() => pnl_view.GetSortingCriteria(); + #endregion + readonly IBus _bus; readonly PAndLModel _model; static readonly TimeSpan _UPDATE_PERIOD = TimeSpan.FromSeconds(1); static readonly TimeSpan _POSITION_UPDATE_PERIOD = TimeSpan.FromMilliseconds(333); + readonly Property _selected_pnl_calc_type; + double _total_aggregate_pnl, _total_aggregate_net_pos, _total_aggregate_buy_qty, _total_aggregate_sell_qty; + DateTime _last_pnl_update_time = DateTime.MinValue; + ObservableCollection _pnl_data = new ObservableCollection(); } diff --git a/src/client/spark/view/Spark/PAndL/PAndLWindow.cs b/src/client/spark/view/Spark/PAndL/PAndLWindow.cs index 1c3e34d4d..0fa58bd01 100644 --- a/src/client/spark/view/Spark/PAndL/PAndLWindow.cs +++ b/src/client/spark/view/Spark/PAndL/PAndLWindow.cs @@ -14,29 +14,30 @@ namespace mbts.spark { internal class PAndLWindow : SparkWindow, ISharedWindow { const string _window_type = "PAndL", PNL_THREAD_ID = "PnL"; - PAndLWindowFactory.PAndLStartupData _state; + PAndLWindowFactory.PAndLStartupData _startup_data; PAndLModel _model; PAndLView _view; PAndLVM _vm; PAndLWindowFactory _factory; - public PAndLWindow(PAndLModel model, PAndLWindowFactory factory, IBus bus, PAndLWindowFactory.PAndLStartupData state, ImageSource Icon ) : base("P&L", bus, factory, SparkCommands.ShowPAndL.icon) { + public PAndLWindow(PAndLModel model, PAndLWindowFactory factory, IBus bus, PAndLWindowFactory.PAndLStartupData startup_data, ImageSource Icon ) : base("P&L", bus, factory, SparkCommands.ShowPAndL.icon) { _model = model; _factory = factory; - _state = state; + _startup_data = startup_data; } public override string window_type => _window_type; - public override PAndLWindowFactory.PAndLStartupData SaveState => _state = + public override PAndLWindowFactory.PAndLStartupData SaveState => _startup_data = new PAndLWindowFactory.PAndLStartupData( _vm.get_sorting_states(), - _vm.get_filters_states() + _vm.get_filters_states(), + _vm.selected_pnl_calc_type ); public override UIElement Content => _view; public override double MinWidth => 894; public string thread_id => PNL_THREAD_ID; public void thread_init() { - _vm = new PAndLVM(_bus, _model, _state); + _vm = new PAndLVM(_bus, _model, _startup_data); _view = new PAndLView(_vm); _view.DataContext = _vm; } From a233451333eeaccd0c1b71d3bb7023cceff8406b Mon Sep 17 00:00:00 2001 From: Jake Norbut Date: Wed, 11 Jul 2018 12:55:15 -0500 Subject: [PATCH 04/15] add start of day to pnl settings --- .../Modules/Trading/PAndLWindowFactory.cs | 8 +++---- src/client/spark/view/Spark/PAndL/PAndLVM.cs | 4 +++- .../spark/view/Spark/PAndL/PAndLWindow.cs | 3 ++- .../spark/view/Spark/PAndL/PnLCalculator.cs | 21 ++++++++++--------- 4 files changed, 20 insertions(+), 16 deletions(-) diff --git a/src/client/spark/Modules/Trading/PAndLWindowFactory.cs b/src/client/spark/Modules/Trading/PAndLWindowFactory.cs index 783b8550a..17344d270 100644 --- a/src/client/spark/Modules/Trading/PAndLWindowFactory.cs +++ b/src/client/spark/Modules/Trading/PAndLWindowFactory.cs @@ -39,13 +39,11 @@ namespace bts.shell { /// public PAndLStartupData() { } - public PAndLStartupData(List sorting_criteria, FilterStates filters) : - this(sorting_criteria, filters, pnl_calc_type.midpoint) { } - - public PAndLStartupData(List sorting_criteria, FilterStates filters, pnl_calc_type calc_type) { + public PAndLStartupData(List sorting_criteria, FilterStates filters, pnl_calc_type calc_type, TimeSpan start_of_day_time) { this.sort_criteria = sorting_criteria; this.filters = filters; this.calc_type = calc_type; + this.start_of_day_time = start_of_day_time; } [ProtoMember(5)] @@ -54,6 +52,8 @@ namespace bts.shell { public FilterStates filters; [ProtoMember(15)] public pnl_calc_type calc_type; + [ProtoMember(20)] + public TimeSpan? start_of_day_time; } diff --git a/src/client/spark/view/Spark/PAndL/PAndLVM.cs b/src/client/spark/view/Spark/PAndL/PAndLVM.cs index 493b376eb..453ade6d4 100644 --- a/src/client/spark/view/Spark/PAndL/PAndLVM.cs +++ b/src/client/spark/view/Spark/PAndL/PAndLVM.cs @@ -25,14 +25,16 @@ namespace mbts.spark { // need to respond to settings change somehow as the // combobox that selected_pnl_calc_type is bound to will be // gone from this form. + // ditto start of day changes _selected_pnl_calc_type.Value = (startup_data != null && startup_data.calc_type != pnl_calc_type.none) ? startup_data.calc_type : pnl_calc_type.midpoint; _selected_pnl_calc_type.Changed += pnl_calc_type_changed; + var start_of_day_ts = (startup_data != null && startup_data.start_of_day_time.HasValue) ? startup_data.start_of_day_time.Value : new TimeSpan(17, 0, 0); var pnl = model.on_pnl_data .Sample(_POSITION_UPDATE_PERIOD) .OnDispatcher() .Subscribe(p => { if (p != null) { - PnLCalculator calc = new PnLCalculator(p.state.Values, _selected_pnl_calc_type.Value); + PnLCalculator calc = new PnLCalculator(p.state.Values, _selected_pnl_calc_type.Value, start_of_day_ts); var summary_position_rows = calc.get_summary_position(); _pnl_data.sync_with(summary_position_rows); _last_pnl_update_time = DateTime.Now; diff --git a/src/client/spark/view/Spark/PAndL/PAndLWindow.cs b/src/client/spark/view/Spark/PAndL/PAndLWindow.cs index 0fa58bd01..ee394c947 100644 --- a/src/client/spark/view/Spark/PAndL/PAndLWindow.cs +++ b/src/client/spark/view/Spark/PAndL/PAndLWindow.cs @@ -30,7 +30,8 @@ namespace mbts.spark { new PAndLWindowFactory.PAndLStartupData( _vm.get_sorting_states(), _vm.get_filters_states(), - _vm.selected_pnl_calc_type + _vm.selected_pnl_calc_type, + new TimeSpan(17,0,0) ); public override UIElement Content => _view; public override double MinWidth => 894; diff --git a/src/client/spark/view/Spark/PAndL/PnLCalculator.cs b/src/client/spark/view/Spark/PAndL/PnLCalculator.cs index e409076c1..49280eed8 100644 --- a/src/client/spark/view/Spark/PAndL/PnLCalculator.cs +++ b/src/client/spark/view/Spark/PAndL/PnLCalculator.cs @@ -78,21 +78,26 @@ namespace mbts.spark { class PnLCalculator { readonly IEnumerable _data; readonly pnl_calc_type _calc_type; + readonly DateTime _start_of_trading_day; - public PnLCalculator(IEnumerable data, pnl_calc_type calc_type) { + public PnLCalculator(IEnumerable data, pnl_calc_type calc_type, TimeSpan start_of_day_ts) { _data = data; _calc_type = calc_type; + // Note that this isn't the acutal start of the trading day + // but it's close enough for pnl purposes. + // In reality, instruments have different schedules + _start_of_trading_day = DateTime.Now.Date.Add(start_of_day_ts).AddDays(-1); } public IEnumerable get_summary_position() { return (from pnl_item in _data group pnl_item by (pnl_item.account, pnl_item.exchange, pnl_item.symbol, pnl_item.security, pnl_item.sec_md) into grouping - let start_of_day = _get_start_of_day(grouping.Key.symbol) - select new PnLSummaryRow(_calc_type, start_of_day, grouping.Key, - grouping.Where(y => y.fill.Timestamp.ToDateTime() >= start_of_day).Sum(y => (uint)y.buy_quantity), - grouping.Where(y => y.fill.Timestamp.ToDateTime() >= start_of_day).Sum(y => (uint)y.sell_quantity), + /* let start_of_day = _get_start_of_day(grouping.Key.symbol) */ + select new PnLSummaryRow(_calc_type, _start_of_trading_day, grouping.Key, + grouping.Where(y => y.fill.Timestamp.ToDateTime() < _start_of_trading_day).Sum(y => (uint)y.buy_quantity), + grouping.Where(y => y.fill.Timestamp.ToDateTime() < _start_of_trading_day).Sum(y => (uint)y.sell_quantity), grouping.Sum(y => (int)(y.buy_quantity - y.sell_quantity)), - grouping.Where(y => y.fill.Timestamp.ToDateTime() < start_of_day).Sum(y => (int)(y.buy_quantity - y.sell_quantity)), + grouping.Where(y => y.fill.Timestamp.ToDateTime() >= _start_of_trading_day).Sum(y => (int)(y.buy_quantity - y.sell_quantity)), grouping.weighted_average(y => y.fill.LastPrice, y => y.buy_quantity), grouping.weighted_average(y => y.fill.LastPrice, y => y.sell_quantity), grouping.Select(i => i.fill) @@ -213,10 +218,6 @@ namespace mbts.spark { return (price - driver) * quantity * cpp; } - private static DateTime _get_start_of_day(string symbool) { - // I rekcon this will change according to the symbol's session - return DateTime.Today; - } } } From b5950ab8c07d959bf7760f7cb1a73038fa97474a Mon Sep 17 00:00:00 2001 From: Jake Norbut Date: Wed, 11 Jul 2018 13:04:34 -0500 Subject: [PATCH 05/15] actually save the start of day rather than overwriting it anew each time --- src/client/spark/view/Spark/PAndL/PAndLVM.cs | 12 +++++++++--- src/client/spark/view/Spark/PAndL/PAndLWindow.cs | 2 +- 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/src/client/spark/view/Spark/PAndL/PAndLVM.cs b/src/client/spark/view/Spark/PAndL/PAndLVM.cs index 453ade6d4..ed7e1b948 100644 --- a/src/client/spark/view/Spark/PAndL/PAndLVM.cs +++ b/src/client/spark/view/Spark/PAndL/PAndLVM.cs @@ -25,16 +25,17 @@ namespace mbts.spark { // need to respond to settings change somehow as the // combobox that selected_pnl_calc_type is bound to will be // gone from this form. - // ditto start of day changes + // ditto start of day changes, but this will be a bit more involved + // since we'll need to create a new PnLCalculator when this changes. (infrequent, if ever) _selected_pnl_calc_type.Value = (startup_data != null && startup_data.calc_type != pnl_calc_type.none) ? startup_data.calc_type : pnl_calc_type.midpoint; _selected_pnl_calc_type.Changed += pnl_calc_type_changed; - var start_of_day_ts = (startup_data != null && startup_data.start_of_day_time.HasValue) ? startup_data.start_of_day_time.Value : new TimeSpan(17, 0, 0); + _start_of_day_ts = (startup_data != null && startup_data.start_of_day_time.HasValue) ? startup_data.start_of_day_time.Value : new TimeSpan(17, 0, 0); var pnl = model.on_pnl_data .Sample(_POSITION_UPDATE_PERIOD) .OnDispatcher() .Subscribe(p => { if (p != null) { - PnLCalculator calc = new PnLCalculator(p.state.Values, _selected_pnl_calc_type.Value, start_of_day_ts); + PnLCalculator calc = new PnLCalculator(p.state.Values, _selected_pnl_calc_type.Value, _start_of_day_ts); var summary_position_rows = calc.get_summary_position(); _pnl_data.sync_with(summary_position_rows); _last_pnl_update_time = DateTime.Now; @@ -172,6 +173,10 @@ namespace mbts.spark { } } + public TimeSpan start_of_day { + get { return _start_of_day_ts; } + } + #region Filters public IDataGridColumnPersistentFilter account_filter { get; } = new RegexFilterVM(r => r.account, nameof(PnLSummaryRow.account)); @@ -217,6 +222,7 @@ namespace mbts.spark { readonly Property _selected_pnl_calc_type; double _total_aggregate_pnl, _total_aggregate_net_pos, _total_aggregate_buy_qty, _total_aggregate_sell_qty; + TimeSpan _start_of_day_ts; DateTime _last_pnl_update_time = DateTime.MinValue; ObservableCollection _pnl_data = new ObservableCollection(); diff --git a/src/client/spark/view/Spark/PAndL/PAndLWindow.cs b/src/client/spark/view/Spark/PAndL/PAndLWindow.cs index ee394c947..9b2d09dc0 100644 --- a/src/client/spark/view/Spark/PAndL/PAndLWindow.cs +++ b/src/client/spark/view/Spark/PAndL/PAndLWindow.cs @@ -31,7 +31,7 @@ namespace mbts.spark { _vm.get_sorting_states(), _vm.get_filters_states(), _vm.selected_pnl_calc_type, - new TimeSpan(17,0,0) + _vm.start_of_day ); public override UIElement Content => _view; public override double MinWidth => 894; From 77ad9ca011391e29ad4f3154cd287d52e52bb35d Mon Sep 17 00:00:00 2001 From: Jake Norbut Date: Thu, 12 Jul 2018 12:00:46 -0500 Subject: [PATCH 06/15] fixing no UTC to UTC time comparison bug; also, somehow swapped day vs start of day comparison --- src/client/spark/view/Spark/PAndL/PnLCalculator.cs | 12 ++++++------ src/client/spark/view/Spark/PAndL/PnLSummaryRow.cs | 6 +++--- 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/src/client/spark/view/Spark/PAndL/PnLCalculator.cs b/src/client/spark/view/Spark/PAndL/PnLCalculator.cs index 49280eed8..af042874e 100644 --- a/src/client/spark/view/Spark/PAndL/PnLCalculator.cs +++ b/src/client/spark/view/Spark/PAndL/PnLCalculator.cs @@ -78,7 +78,7 @@ namespace mbts.spark { class PnLCalculator { readonly IEnumerable _data; readonly pnl_calc_type _calc_type; - readonly DateTime _start_of_trading_day; + readonly DateTime _start_of_trading_day_utc; public PnLCalculator(IEnumerable data, pnl_calc_type calc_type, TimeSpan start_of_day_ts) { _data = data; @@ -86,18 +86,18 @@ namespace mbts.spark { // Note that this isn't the acutal start of the trading day // but it's close enough for pnl purposes. // In reality, instruments have different schedules - _start_of_trading_day = DateTime.Now.Date.Add(start_of_day_ts).AddDays(-1); + _start_of_trading_day_utc = DateTime.Now.Date.Add(start_of_day_ts).AddDays(-1).ToUniversalTime(); } public IEnumerable get_summary_position() { return (from pnl_item in _data group pnl_item by (pnl_item.account, pnl_item.exchange, pnl_item.symbol, pnl_item.security, pnl_item.sec_md) into grouping /* let start_of_day = _get_start_of_day(grouping.Key.symbol) */ - select new PnLSummaryRow(_calc_type, _start_of_trading_day, grouping.Key, - grouping.Where(y => y.fill.Timestamp.ToDateTime() < _start_of_trading_day).Sum(y => (uint)y.buy_quantity), - grouping.Where(y => y.fill.Timestamp.ToDateTime() < _start_of_trading_day).Sum(y => (uint)y.sell_quantity), + select new PnLSummaryRow(_calc_type, _start_of_trading_day_utc, grouping.Key, + grouping.Where(y => y.fill.Timestamp.ToDateTime() >= _start_of_trading_day_utc).Sum(y => (uint)y.buy_quantity), + grouping.Where(y => y.fill.Timestamp.ToDateTime() >= _start_of_trading_day_utc).Sum(y => (uint)y.sell_quantity), grouping.Sum(y => (int)(y.buy_quantity - y.sell_quantity)), - grouping.Where(y => y.fill.Timestamp.ToDateTime() >= _start_of_trading_day).Sum(y => (int)(y.buy_quantity - y.sell_quantity)), + grouping.Where(y => y.fill.Timestamp.ToDateTime() < _start_of_trading_day_utc).Sum(y => (int)(y.buy_quantity - y.sell_quantity)), grouping.weighted_average(y => y.fill.LastPrice, y => y.buy_quantity), grouping.weighted_average(y => y.fill.LastPrice, y => y.sell_quantity), grouping.Select(i => i.fill) diff --git a/src/client/spark/view/Spark/PAndL/PnLSummaryRow.cs b/src/client/spark/view/Spark/PAndL/PnLSummaryRow.cs index 52f2f8120..2d4b3b05c 100644 --- a/src/client/spark/view/Spark/PAndL/PnLSummaryRow.cs +++ b/src/client/spark/view/Spark/PAndL/PnLSummaryRow.cs @@ -27,11 +27,11 @@ namespace mbts.spark { public PnLSummaryRow(pnl_calc_type calc_type, DateTime start_of_day, (string, Venue?, string, SecurityImmutable?, SecurityMD?) key, - uint buy_quant, uint sell_quant, int net_pos, int sod_pos, double wavg_buy, double wavg_sell, IEnumerable fills) { + uint day_buy_quant, uint day_sell_quant, int net_pos, int sod_pos, double wavg_buy, double wavg_sell, IEnumerable fills) { this._start_of_day = start_of_day; this.key = key; - day_long_quantity = buy_quant; - day_short_quantity = sell_quant; + day_long_quantity = day_buy_quant; + day_short_quantity = day_sell_quant; total_net_position = net_pos; start_net_position = sod_pos; weighted_average_buy = wavg_buy; From 6f39705d4fab2157449820fc072225d02fcc1b80 Mon Sep 17 00:00:00 2001 From: Jake Norbut Date: Thu, 12 Jul 2018 13:26:47 -0500 Subject: [PATCH 07/15] PnL will now use cpp from config rather than security --- .../spark/view/Spark/PAndL/PnLSummaryRow.cs | 22 ++++++++++++++----- 1 file changed, 16 insertions(+), 6 deletions(-) diff --git a/src/client/spark/view/Spark/PAndL/PnLSummaryRow.cs b/src/client/spark/view/Spark/PAndL/PnLSummaryRow.cs index 2d4b3b05c..a59c27111 100644 --- a/src/client/spark/view/Spark/PAndL/PnLSummaryRow.cs +++ b/src/client/spark/view/Spark/PAndL/PnLSummaryRow.cs @@ -20,8 +20,7 @@ namespace mbts.spark { IEnumerable _fills; ulong _bbo_ref, _last_ref; double _driver; - //List _schedules = new List() { MarketSchedule.es_schedule }; - + static readonly Dictionary cpp_dict = config.Configuration.get().cpp_entry; public PnLSummaryRow(pnl_calc_type calc_type, @@ -46,18 +45,29 @@ namespace mbts.spark { private double _get_cpp_for_security(SecurityImmutable s) { if (s.security_type() == SecurityType.Spread) { var distinct_cpps = s.Spread.Legs - .Select(l => l.Security.ContractSpec.CashPerPoint) + .Select(l => get_cpp_for_symbol(l.Security)) .Distinct(); bool all_legs_have_same_cpp = distinct_cpps.Count() < 2; if (all_legs_have_same_cpp) { - return s.Spread.Legs.First().Security.ContractSpec.CashPerPoint; + return distinct_cpps.First(); } else { - Logger.error(bts.log.Subsystem.Ui, + Logger.error(bts.log.Subsystem.Ui, $"Security {s} contains legs with the following cash multipliers: { string.Join(",", distinct_cpps.Select(d => d.ToString())) } "); return Double.NaN; } + } else { + return get_cpp_for_symbol(s); + } + + // local function for looking up cpp for a single SecurityImmutable + double get_cpp_for_symbol(SecurityImmutable si) { + if (cpp_dict.TryGetValue(si.Symbol, out double cpp_out)) { + return cpp_out; + } else { + Logger.error(bts.log.Subsystem.Ui, $"No cash multiplier found for Security {si}, Symbol {si.Symbol}"); + } + return double.NaN; } - return s.ContractSpec.CashPerPoint; } From edcb5a5a249a4eea4242b17c2fa140c3f8f33b8b Mon Sep 17 00:00:00 2001 From: Jake Norbut Date: Thu, 12 Jul 2018 13:29:21 -0500 Subject: [PATCH 08/15] Changing default day start time to 4:30 as a result of new info from dev call --- src/client/spark/view/Spark/PAndL/PAndLVM.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/client/spark/view/Spark/PAndL/PAndLVM.cs b/src/client/spark/view/Spark/PAndL/PAndLVM.cs index ed7e1b948..f1ff1b131 100644 --- a/src/client/spark/view/Spark/PAndL/PAndLVM.cs +++ b/src/client/spark/view/Spark/PAndL/PAndLVM.cs @@ -29,7 +29,7 @@ namespace mbts.spark { // since we'll need to create a new PnLCalculator when this changes. (infrequent, if ever) _selected_pnl_calc_type.Value = (startup_data != null && startup_data.calc_type != pnl_calc_type.none) ? startup_data.calc_type : pnl_calc_type.midpoint; _selected_pnl_calc_type.Changed += pnl_calc_type_changed; - _start_of_day_ts = (startup_data != null && startup_data.start_of_day_time.HasValue) ? startup_data.start_of_day_time.Value : new TimeSpan(17, 0, 0); + _start_of_day_ts = (startup_data != null && startup_data.start_of_day_time.HasValue) ? startup_data.start_of_day_time.Value : new TimeSpan(16, 30, 0); var pnl = model.on_pnl_data .Sample(_POSITION_UPDATE_PERIOD) .OnDispatcher() From a6426e7a98e3a684e79a3cf2bad5ac176695f600 Mon Sep 17 00:00:00 2001 From: John Colvin Date: Sat, 14 Jul 2018 17:48:21 -0400 Subject: [PATCH 09/15] SPARK-1455 Tick display wrong for ZB, likely others --- .../Market/MarketView/MarketViewRow.cs | 6 +- .../Modules/Market/MarketView/MarketViewVM.cs | 2 +- .../Market/TimeAndSales/TimeAndSalesVM.cs | 2 +- .../Spreader/ExecutionStrategyEditor.xaml | 4 +- .../Modules/Spreader/VM/SyntheticEditorVM.cs | 16 +- .../spark/Orders/OrderActivitySummarizer.cs | 52 +-- .../Orders/OrderModificationControl.xaml | 6 +- .../spark/Orders/OrderModificationDialog.xaml | 4 +- src/client/spark/Orders/OrderTicket.xaml | 4 +- .../Orders/OrderTypeVMs/StopLimitOrderVM.cs | 7 +- .../core/GlobalExtensions/TickExtensions.cs | 2 +- .../core/user/settings/ticks/TickFactors.cs | 25 +- .../Controls/DIYGrid/CellRender/PriceCell.cs | 24 +- .../FrameworkElementColumns/PriceColumn.cs | 2 +- .../Order/OrderDetailsPopupControl.xaml | 4 +- .../view/Controls/PriceEntryControl.xaml.cs | 26 +- .../view/Converters/TickDisplayConverter.cs | 20 +- .../spark/view/Spark/Core/OrderUtils.cs | 26 +- src/client/spark/view/Spark/Core/TickUtils.cs | 312 ++++++++++-------- .../spark/view/Spark/Grid/ISecurityRow.cs | 2 +- .../spark/view/Spark/Ladder/LadderGridHost.cs | 22 +- .../spark/view/Spark/Ladder/LadderOrderVM.cs | 5 +- .../spark/view/Spark/Ladder/LadderView.xaml | 10 +- .../spark/view/Spark/Ladder/LaderRender.cs | 24 +- .../view/Spark/Ladder/RecenterCountdown.cs | 4 - .../spark/view/Spark/PAndL/PAndLView.xaml | 4 +- .../Shell/CVOrderBook/CVOrderBookRowVM.cs | 2 +- .../Spark/Shell/OrderBook/OrderBookColumns.cs | 2 +- .../spark/view/Spark/Utilities/MathUtils.cs | 20 ++ .../Spark/Utilities/SecurityDataHelper.cs | 2 + src/lib/CMakeDeps.cmake | 2 +- 31 files changed, 345 insertions(+), 298 deletions(-) diff --git a/src/client/spark/Modules/Market/MarketView/MarketViewRow.cs b/src/client/spark/Modules/Market/MarketView/MarketViewRow.cs index 2d782efa7..b87ccf35f 100644 --- a/src/client/spark/Modules/Market/MarketView/MarketViewRow.cs +++ b/src/client/spark/Modules/Market/MarketView/MarketViewRow.cs @@ -42,7 +42,7 @@ namespace mbts.spark { _orders_model = orders_model; _security_text = smd.security.ToString(); _security_key_text = security_key.ToString(); - string format_price(double price) => security.ContractSpec.format(price); + string format_price(double price) => security.format(price); _position = new CellProperty(0); _bid_price = backing(nameof(bid_price), double.NaN); _ask_price = backing(nameof(ask_price), double.NaN); @@ -106,8 +106,8 @@ namespace mbts.spark { public double session_high => _session_high.Value; public int working_bid_volume => _working_bid_volume.value; public int working_ask_volume => _working_ask_volume.value; - public string working_bids_text => OrderUtils.order_collection_summary(_order_summarizer.best_working_bid, _order_summarizer.best_working_bid_qty, _order_summarizer.working_bid_qty, security.ContractSpec); - public string working_asks_text => OrderUtils.order_collection_summary(_order_summarizer.best_working_ask, _order_summarizer.best_working_ask_qty, _order_summarizer.working_ask_qty, security.ContractSpec); + public string working_bids_text => OrderUtils.order_collection_summary(_order_summarizer.best_working_bid, _order_summarizer.best_working_bid_qty, _order_summarizer.working_bid_qty, security); + public string working_asks_text => OrderUtils.order_collection_summary(_order_summarizer.best_working_ask, _order_summarizer.best_working_ask_qty, _order_summarizer.working_ask_qty, security); public double working_best_bid => _working_best_bid.value; public double working_best_ask => _working_best_ask.value; public IList animations => _animation.get_animations().ToList(); diff --git a/src/client/spark/Modules/Market/MarketView/MarketViewVM.cs b/src/client/spark/Modules/Market/MarketView/MarketViewVM.cs index 24100958e..a4209a52e 100644 --- a/src/client/spark/Modules/Market/MarketView/MarketViewVM.cs +++ b/src/client/spark/Modules/Market/MarketView/MarketViewVM.cs @@ -76,7 +76,7 @@ namespace mbts.spark { BindingBase price_binding(string prop) { var mb = new MultiBinding { Converter = price_converter }; mb.Bindings.Add(new Binding(prop) { Mode = BindingMode.OneWay }); - mb.Bindings.Add(new Binding($"{nameof(Row.security)}.{nameof(SecurityImmutable.ContractSpec)}") { Mode = BindingMode.OneWay }); + mb.Bindings.Add(new Binding($"{nameof(Row.security)}") { Mode = BindingMode.OneWay }); return mb; } // diff --git a/src/client/spark/Modules/Market/TimeAndSales/TimeAndSalesVM.cs b/src/client/spark/Modules/Market/TimeAndSales/TimeAndSalesVM.cs index 2d5a8ea8e..86c7db401 100644 --- a/src/client/spark/Modules/Market/TimeAndSales/TimeAndSalesVM.cs +++ b/src/client/spark/Modules/Market/TimeAndSales/TimeAndSalesVM.cs @@ -101,7 +101,7 @@ namespace mbts.spark { show_ladder = new DelegateCommand(() => parent._show_ladder_async(this).ignore()); _security_text = security.ToString(); _time_text = time.ToString("M/d h:mm:ss tt"); - _price_text = security.ContractSpec.format(price); + _price_text = security.format(price); _size_text = size.ToString(); _trade_key_text = _trade_key.ToString(); _security_key_text = security_key.ToString(); diff --git a/src/client/spark/Modules/Spreader/ExecutionStrategyEditor.xaml b/src/client/spark/Modules/Spreader/ExecutionStrategyEditor.xaml index 6055d5bfe..07fe26515 100644 --- a/src/client/spark/Modules/Spreader/ExecutionStrategyEditor.xaml +++ b/src/client/spark/Modules/Spreader/ExecutionStrategyEditor.xaml @@ -367,7 +367,7 @@ /> @@ -375,7 +375,7 @@ - + diff --git a/src/client/spark/Modules/Spreader/VM/SyntheticEditorVM.cs b/src/client/spark/Modules/Spreader/VM/SyntheticEditorVM.cs index 60e6bae60..5c552197e 100644 --- a/src/client/spark/Modules/Spreader/VM/SyntheticEditorVM.cs +++ b/src/client/spark/Modules/Spreader/VM/SyntheticEditorVM.cs @@ -1,6 +1,7 @@ using bts.api; using bts.shell; using bts.spark; +using mbts.spark.utilities; using mbts.ui; using mbts.ui.shell; using mbts.ui.spark; @@ -23,7 +24,7 @@ namespace mbts.spark { /// The view model designed to serve as the DataContext for the SyntheticEditorView /// partial class SyntheticEditorVM : DisposableViewModelBase, IRequestViewClose, IRequestBindingSourceUpdate, IDisposable { - readonly ObservableCollection _available_tick_factors = new ObservableCollection(TickUtils.all_present_ticks()); + readonly ObservableCollection _available_tick_factors = new ObservableCollection(TickUtils.all_present_ticks().Select(tf => new TickFactorsVM(tf))); readonly QuantityModel _quantity_model; readonly PriceMultiplierModel _price_mult_model; readonly List _resources = new List(); @@ -41,7 +42,7 @@ namespace mbts.spark { public SyntheticEditorVM(SpreaderModel model, SecurityImmutable synthetic, ExecutionStrategyImmutable strategy, IObservable security_has_working_orders) : this(synthetic, strategy, false) { ExceptionAssert.InvalidOperation.That(synthetic.Id != 0, "This constructor may only be used for already-existing synthetic securities (id must be non-zero)."); - _tick_factors = TickUtils.get_regional_ticks(synthetic.ContractSpec).low_tick; + _tick_factors = TickUtils.get_regional_ticks(synthetic).low_tick; title = $"Edit '{synthetic.Synthetic.Name}'"; icon = Icons.ModifySynthetic; _has_working_orders = backing(nameof(has_working_orders), security_has_working_orders.OnDispatcher()); @@ -94,7 +95,7 @@ namespace mbts.spark { _set_ticks_automatically = false; _set_quantities_automatically = false; _set_price_mults_automatically = false; - _tick_factors = TickUtils.get_regional_ticks(_synthetic.ContractSpec).low_tick; + _tick_factors = TickUtils.get_regional_ticks(_synthetic).low_tick; } else { _deduce_name(); _deduce_ticks(); @@ -121,7 +122,7 @@ namespace mbts.spark { flash_error_msg("Name already taken", SparkUtils.UI.MessageFlashDuration, nameof(name)).ignore(); valid = false; } - if (_tick_factors == null || !_tick_factors.is_valid() || !_available_tick_factors.Contains(_tick_factors)) { + if (_tick_factors == null || !_tick_factors.is_valid() || !_available_tick_factors.Any(vm => vm.value.Equals(_tick_factors))) { flash_error_msg("Please select ticks", SparkUtils.UI.MessageFlashDuration, nameof(tick_factors)).ignore(); valid = false; } @@ -153,7 +154,8 @@ namespace mbts.spark { _set_quantities_automatically = is_new; _set_price_mults_automatically = is_new; available_tick_factors_view = CollectionViewSource.GetDefaultView(_available_tick_factors); - available_tick_factors_view.GroupDescriptions.Add(new PropertyGroupDescription(nameof(TickFactors.tick_base))); + ((ListCollectionView)available_tick_factors_view).CustomSort = Comparer.Default; + available_tick_factors_view.GroupDescriptions.Add(new PropertyGroupDescription(nameof(TickFactorsVM.reduced_base))); _quantity_model = new QuantityModel(!is_new); _price_mult_model = new PriceMultiplierModel(!is_new); @@ -328,8 +330,8 @@ namespace mbts.spark { void _deduce_ticks() { _tick_factors = TickUtils.deduce_ticks(leg_tuples.Select(l => l.leg.Security.ContractSpec)); - if (_tick_factors != null && !_available_tick_factors.Contains(tick_factors)) - _available_tick_factors.Add(_tick_factors); + if (_tick_factors != null && !_available_tick_factors.Any(vm => vm.value.Equals(tick_factors))) + _available_tick_factors.Add(new TickFactorsVM(_tick_factors)); RaisePropertyChanged(nameof(tick_factors)); } diff --git a/src/client/spark/Orders/OrderActivitySummarizer.cs b/src/client/spark/Orders/OrderActivitySummarizer.cs index 98e6d7375..1ea102cac 100644 --- a/src/client/spark/Orders/OrderActivitySummarizer.cs +++ b/src/client/spark/Orders/OrderActivitySummarizer.cs @@ -38,23 +38,23 @@ namespace bts.spark { #region formatting - (SecurityImmutable?, ContractSpecificationImmutable?) get_security(uint security_key) { + SecurityImmutable? get_security(uint security_key) { if (_security.TryGetValue(security_key, out SecurityMD md)) { - return (md.security, md.security.ContractSpec); + return md.security; } - return (null, null); + return null; } - string format_order_success(uint key, double price, uint size, Side side, ContractSpecificationImmutable? spec) { - return $"({key}) {side.ToString().ToLower()} {size} @ {spec.format(price)}"; + string format_order_success(uint key, double price, uint size, Side side, SecurityImmutable? security) { + return $"({key}) {side.ToString().ToLower()} {size} @ {security.format(price)}"; } - string format_order_fail(double price, uint size, Side side, ContractSpecificationImmutable? spec, string error) { - return $"Failed to {side.ToString().ToLower()} {size} @ {spec.format(price)}. {error}"; + string format_order_fail(double price, uint size, Side side, SecurityImmutable? security, string error) { + return $"Failed to {side.ToString().ToLower()} {size} @ {security.format(price)}. {error}"; } - string format_cancel_success(OrderRecordImmutable order, ContractSpecificationImmutable? spec) { - return $"({order.Key}) Canceled {order.short_description(spec)}, was working {order.working_quantity()}"; + string format_cancel_success(OrderRecordImmutable order, SecurityImmutable? security) { + return $"({order.Key}) Canceled {order.short_description(security)}, was working {order.working_quantity()}"; } - string format_cancel_error(OrderRecordImmutable order, ContractSpecificationImmutable? spec, string error) { - return $"({order.Key}) Failed to cancel {order.short_description(spec)}: {error}"; + string format_cancel_error(OrderRecordImmutable order, SecurityImmutable? security, string error) { + return $"({order.Key}) Failed to cancel {order.short_description(security)}: {error}"; } string format_fill_summary(OrderRecordImmutable before, OrderRecordImmutable after) { int fb = (int)before.State.FilledQuantity; @@ -65,14 +65,14 @@ namespace bts.spark { return $"({key}) Status changed from {old_status} to {new_status}"; } - public static string modified_description(OrderRecordImmutable old_order, OrderRecordImmutable new_order, ContractSpecificationImmutable? spec) { + public static string modified_description(OrderRecordImmutable old_order, OrderRecordImmutable new_order, SecurityImmutable? security) { double old_price = old_order.State.Price, new_price = new_order.State.Price; uint old_size = old_order.State.Quantity, new_size = new_order.State.Quantity; string modified_size_partial_description(int working_size) { return $"size from {old_size} to {new_size}, working {working_size}"; } string modified_price_partial_description() { - return $"price from {spec.format(old_price)} to {spec.format(new_price)}"; + return $"price from {security.format(old_price)} to {security.format(new_price)}"; } if (old_price != new_price || old_size != new_size) { StringBuilder sb = new StringBuilder($"({old_order.Key}) Changed "); @@ -102,7 +102,7 @@ namespace bts.spark { foreach (var order in added) { if (!string.IsNullOrEmpty(order.State.LastMsg) && order.State.Created.ToDateTime().Date == DateTime.Today) { - (var security, var spec) = get_security(order.Def.SecurityKey); + var security = get_security(order.Def.SecurityKey); if (security.HasValue) { log_status(ActivityLogCategory.warn, security, order.State.LastMsg); } @@ -111,10 +111,10 @@ namespace bts.spark { foreach (var neworder in changed) { var oldorder = removed[neworder.Key]; - (var security, var spec) = get_security(neworder.Def.SecurityKey); + var security = get_security(neworder.Def.SecurityKey); // // description - var mod_desc = modified_description(oldorder, neworder, spec); + var mod_desc = modified_description(oldorder, neworder, security); if (!string.IsNullOrEmpty(mod_desc)) { log_status(ActivityLogCategory.modify, security, mod_desc); } @@ -145,31 +145,31 @@ namespace bts.spark { } internal void on_send_order(OrderDefinitionImmutable order, double price, uint size, uint? key, string error) { - (var security, var spec) = get_security(order.SecurityKey); + var security = get_security(order.SecurityKey); log_status(ActivityLogCategory.order, security, key.HasValue ? - format_order_success(key.Value, price, size, order.Side, spec) : - format_order_fail(price, size, order.Side, spec, error)); + format_order_success(key.Value, price, size, order.Side, security) : + format_order_fail(price, size, order.Side, security, error)); } internal void on_cancel_order(OrderRecordImmutable order, bool success, string error) { - (var security, var spec) = get_security(order.Def.SecurityKey); + var security = get_security(order.Def.SecurityKey); log_status(ActivityLogCategory.cancel, security, success ? - format_cancel_success(order, spec): - format_cancel_error(order, spec, error)); + format_cancel_success(order, security): + format_cancel_error(order, security, error)); } internal void update_order(OrderRecordImmutable order, double price, uint size) { - (var security, var spec) = get_security(order.Def.SecurityKey); + var security = get_security(order.Def.SecurityKey); log_status(ActivityLogCategory.modify, security, - $"({order.Key}) change from {order.State.Quantity}@{spec.format(order.State.Price)} to {size}@{spec.format(price)}"); + $"({order.Key}) change from {order.State.Quantity}@{security.format(order.State.Price)} to {size}@{security.format(price)}"); } internal void update_order_failed(OrderRecordImmutable order, double price, uint size) { - (var security, var spec) = get_security(order.Def.SecurityKey); + var security = get_security(order.Def.SecurityKey); log_status(ActivityLogCategory.modify, security, - $"({order.Key}) failed to change from {order.State.Quantity}@{spec.format(order.State.Price)} to {size}@{spec.format(price)}"); + $"({order.Key}) failed to change from {order.State.Quantity}@{security.format(order.State.Price)} to {size}@{security.format(price)}"); } } diff --git a/src/client/spark/Orders/OrderModificationControl.xaml b/src/client/spark/Orders/OrderModificationControl.xaml index 5aedfca87..15b07348b 100644 --- a/src/client/spark/Orders/OrderModificationControl.xaml +++ b/src/client/spark/Orders/OrderModificationControl.xaml @@ -74,7 +74,7 @@ - + diff --git a/src/client/spark/Orders/OrderModificationDialog.xaml b/src/client/spark/Orders/OrderModificationDialog.xaml index d35448046..c329b2372 100644 --- a/src/client/spark/Orders/OrderModificationDialog.xaml +++ b/src/client/spark/Orders/OrderModificationDialog.xaml @@ -77,7 +77,7 @@ - + @@ -85,7 +85,7 @@ - + diff --git a/src/client/spark/Orders/OrderTicket.xaml b/src/client/spark/Orders/OrderTicket.xaml index c51185737..907b8a094 100644 --- a/src/client/spark/Orders/OrderTicket.xaml +++ b/src/client/spark/Orders/OrderTicket.xaml @@ -126,7 +126,7 @@ - + @@ -134,7 +134,7 @@ - + diff --git a/src/client/spark/Orders/OrderTypeVMs/StopLimitOrderVM.cs b/src/client/spark/Orders/OrderTypeVMs/StopLimitOrderVM.cs index c2fb47863..582ca2663 100644 --- a/src/client/spark/Orders/OrderTypeVMs/StopLimitOrderVM.cs +++ b/src/client/spark/Orders/OrderTypeVMs/StopLimitOrderVM.cs @@ -1,7 +1,6 @@ using bts.api; using bts.api.orderman; -using mbts.spark.utilities; -using mbts.utils; + namespace mbts.spark { static partial class OrderTypeVMFactory { private class StopLimitOrderVM : OrderTypeVMBase { @@ -17,8 +16,8 @@ namespace mbts.spark { } } - public ContractSpecificationImmutable spec { get; private set; } = - SecurityDataHelper.Defaults.ContractSpecificationImmutable; + public SecurityImmutable security { get; private set; } = + SecurityDataHelper.Defaults.Security; public override void assign_to(CustomOrderDefinition value) { if (!HasErrors) { diff --git a/src/client/spark/core/GlobalExtensions/TickExtensions.cs b/src/client/spark/core/GlobalExtensions/TickExtensions.cs index 7468f9903..b1b0cc305 100644 --- a/src/client/spark/core/GlobalExtensions/TickExtensions.cs +++ b/src/client/spark/core/GlobalExtensions/TickExtensions.cs @@ -18,7 +18,7 @@ namespace mbts { tick.tick_unit / tick.tick_base; public static string format(this TickFactors tick, double value) => - format(tick, value, double.NaN, true, _nan_text); + format(tick, value, double.NaN, false, _nan_text); public static string format(this TickFactors tick, double value, bool show_commas) => format(tick, value, double.NaN, show_commas, _nan_text); diff --git a/src/client/spark/core/user/settings/ticks/TickFactors.cs b/src/client/spark/core/user/settings/ticks/TickFactors.cs index 9d941acc9..6514287d4 100644 --- a/src/client/spark/core/user/settings/ticks/TickFactors.cs +++ b/src/client/spark/core/user/settings/ticks/TickFactors.cs @@ -1,4 +1,5 @@ -using mbts.ui; +using mbts.spark.utilities; +using mbts.ui; using ProtoBuf; using System; using System.ComponentModel; @@ -48,4 +49,26 @@ namespace mbts.user.settings { public static bool operator !=(TickFactors x, TickFactors y) => !(x == y); } + + class TickFactorsVM : IComparable, IEquatable { + public TickFactorsVM(TickFactors value) => + this.value = value; + + public TickFactors value { get; } + public double reduced_base => MathUtils.factor_out(value.tick_base, 10); + + public int CompareTo(TickFactorsVM other) { + int comp = reduced_base.CompareTo(other.reduced_base); + if (comp != 0) + return comp; + comp = value.tick_base.CompareTo(other.value.tick_base); + if (comp != 0) + return comp; + return value.tick_unit.CompareTo(other.value.tick_unit); + } + + public bool Equals(TickFactorsVM other) => value == other?.value; + public override bool Equals(object obj) => Equals(obj as TickFactorsVM); + public override int GetHashCode() => value.GetHashCode(); + } } \ No newline at end of file diff --git a/src/client/spark/view/Controls/DIYGrid/CellRender/PriceCell.cs b/src/client/spark/view/Controls/DIYGrid/CellRender/PriceCell.cs index 52578cdf8..14af77732 100644 --- a/src/client/spark/view/Controls/DIYGrid/CellRender/PriceCell.cs +++ b/src/client/spark/view/Controls/DIYGrid/CellRender/PriceCell.cs @@ -21,7 +21,7 @@ namespace mbts.ui.controls { double _glyph_width, _font_size, _value; GlyphRun _glyph_run; GlyphContext _glyph_context; - ContractSpecificationImmutable _spec; + SecurityImmutable _security; static PriceCell() => WPFHelper.override_metadata( @@ -41,7 +41,7 @@ namespace mbts.ui.controls { _padding = Padding; _font_size = FontSize; _value = Value; - _spec = ContractSpec; + _security = Security; _glyph_context = GlyphContext.create(FontFamily, FontWeight); } @@ -147,20 +147,20 @@ namespace mbts.ui.controls { public double Value { get => (double)GetValue(ValueProperty); set => SetValue(ValueProperty, value); } #endregion - #region ContractSpec - public static readonly DependencyProperty ContractSpecProperty = - WPFHelper.create_dp( - nameof(ContractSpec), + #region Security + public static readonly DependencyProperty SecurityProperty = + WPFHelper.create_dp( + nameof(Security), FrameworkPropertyMetadataOptions.AffectsMeasure | FrameworkPropertyMetadataOptions.AffectsRender, (p, v) => { - p._spec = v; + p._security = v; p._glyph_run = null; - }, SecurityDataHelper.Defaults.ContractSpecificationImmutable); + }, SecurityDataHelper.Defaults.SecurityImmutable); - public ContractSpecificationImmutable ContractSpec { - get => (ContractSpecificationImmutable)GetValue(ContractSpecProperty); - set => SetValue(ContractSpecProperty, value); + public SecurityImmutable Security { + get => (SecurityImmutable)GetValue(SecurityProperty); + set => SetValue(SecurityProperty, value); } #endregion @@ -178,7 +178,7 @@ namespace mbts.ui.controls { } void _set_glyph(Size size) { - _glyph_run = _glyph_context.get_glyph_run(_spec.format(_value), _font_size, size, _horizontal_alignment, VerticalAlignment.Center, _padding); + _glyph_run = _glyph_context.get_glyph_run(_security.format(_value), _font_size, size, _horizontal_alignment, VerticalAlignment.Center, _padding); _glyph_width = _glyph_run == null ? 0 : _glyph_run.AdvanceWidths.Sum(); } diff --git a/src/client/spark/view/Controls/DIYGrid/Columns/FrameworkElementColumns/PriceColumn.cs b/src/client/spark/view/Controls/DIYGrid/Columns/FrameworkElementColumns/PriceColumn.cs index d38b95eef..98740af1f 100644 --- a/src/client/spark/view/Controls/DIYGrid/Columns/FrameworkElementColumns/PriceColumn.cs +++ b/src/client/spark/view/Controls/DIYGrid/Columns/FrameworkElementColumns/PriceColumn.cs @@ -22,7 +22,7 @@ namespace mbts.ui.controls { public override FrameworkElement view_factory() { var v = new PriceCell(); v.SetBinding(PriceCell.ValueProperty, _binding_factory()); - v.SetBinding(PriceCell.ContractSpecProperty, _spec_binding_factory()); + v.SetBinding(PriceCell.SecurityProperty, _spec_binding_factory()); return v; } } diff --git a/src/client/spark/view/Controls/Order/OrderDetailsPopupControl.xaml b/src/client/spark/view/Controls/Order/OrderDetailsPopupControl.xaml index fe7082c06..d73ba0daa 100644 --- a/src/client/spark/view/Controls/Order/OrderDetailsPopupControl.xaml +++ b/src/client/spark/view/Controls/Order/OrderDetailsPopupControl.xaml @@ -70,7 +70,7 @@ Stop Price - + @@ -82,7 +82,7 @@ Stop Price - + diff --git a/src/client/spark/view/Controls/PriceEntryControl.xaml.cs b/src/client/spark/view/Controls/PriceEntryControl.xaml.cs index 52cb3a8ac..270fcb327 100644 --- a/src/client/spark/view/Controls/PriceEntryControl.xaml.cs +++ b/src/client/spark/view/Controls/PriceEntryControl.xaml.cs @@ -1,12 +1,10 @@ using bts.api; using mbts.spark; -using mbts.ui.extensions; using mbts.ui.spark.converters; using System; using System.Windows; using System.Windows.Controls; using System.Windows.Input; -using static mbts.ui.utility.text.TextUtils; namespace mbts.ui.spark { /// @@ -18,7 +16,7 @@ namespace mbts.ui.spark { #region Value public static readonly DependencyProperty ValueProperty = DependencyProperty.Register("Value", typeof(double), typeof(PriceEntryControl),new FrameworkPropertyMetadata(double.NaN, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, null, CoerceValue)); - private static object CoerceValue(DependencyObject d, object baseValue) { return TickUtils.get_regional_ticks((ContractSpecificationImmutable)d.GetValue(ContractSpecProperty)).round((double)baseValue); } + private static object CoerceValue(DependencyObject d, object baseValue) { return TickUtils.get_regional_ticks((SecurityImmutable)d.GetValue(SecurityProperty)).round((double)baseValue); } public double Value { get => (double)GetValue(ValueProperty); set => SetValue(ValueProperty, value); } #endregion @@ -39,11 +37,11 @@ namespace mbts.ui.spark { public ICommand TickDownCommand { get => GetValue(TickDownCommandProperty) as ICommand; private set => SetValue(TickDownCommandPropertyKey, value); } #endregion - #region ContractSpec - public static readonly DependencyProperty ContractSpecProperty = DependencyProperty.Register("ContractSpec", typeof(ContractSpecificationImmutable), typeof(PriceEntryControl), - new PropertyMetadata(SecurityDataHelper.Defaults.ContractSpecificationImmutable, OnContractSpecChanged)); - static void OnContractSpecChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) => ((PriceEntryControl)d)._update_text_binding(); - public ContractSpecificationImmutable? ContractSpec { get => GetValue(ContractSpecProperty) as ContractSpecificationImmutable?; set => SetValue(ContractSpecProperty, value); } + #region Security + public static readonly DependencyProperty SecurityProperty = DependencyProperty.Register( + nameof(Security), typeof(SecurityImmutable), typeof(PriceEntryControl), new PropertyMetadata(SecurityDataHelper.Defaults.SecurityImmutable, OnSecurityChanged)); + static void OnSecurityChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) => ((PriceEntryControl)d)._update_text_binding(); + public SecurityImmutable? Security { get => GetValue(SecurityProperty) as SecurityImmutable?; set => SetValue(SecurityProperty, value); } #endregion TextBox _text; @@ -71,8 +69,8 @@ namespace mbts.ui.spark { if (double.IsNaN(v)) { SetCurrentValue(ValueProperty, TickDefaultValue); } else { - var spec = ContractSpec; - if (spec.HasValue) SetCurrentValue(ValueProperty, spec.Value.tickup(v)); + var sec = Security; + if (sec.HasValue) SetCurrentValue(ValueProperty, sec.Value.tickup(v)); else SetCurrentValue(ValueProperty, TickDefaultValue); } } @@ -85,21 +83,21 @@ namespace mbts.ui.spark { if (double.IsNaN(v)) { SetCurrentValue(ValueProperty, TickDefaultValue); } else { - var spec = ContractSpec; - if (spec.HasValue) SetCurrentValue(ValueProperty, spec.Value.tickdown(v)); + var sec = Security; + if (sec.HasValue) SetCurrentValue(ValueProperty, sec.Value.tickdown(v)); else SetCurrentValue(ValueProperty, TickDefaultValue); } } void _update_text_binding() { if (_text != null) { - var spec = ContractSpec; + var spec = Security; if (spec != null) { var be = _text.GetBindingExpression(TextBox.TextProperty); if (be != null) { var converter = be.ParentBinding.Converter as TickDisplayTwoWayConverter; if (converter != null) { - converter.ContractSpec = spec; + converter.Security = spec; be.UpdateTarget(); } } diff --git a/src/client/spark/view/Converters/TickDisplayConverter.cs b/src/client/spark/view/Converters/TickDisplayConverter.cs index e0da66705..822ea1008 100644 --- a/src/client/spark/view/Converters/TickDisplayConverter.cs +++ b/src/client/spark/view/Converters/TickDisplayConverter.cs @@ -16,9 +16,9 @@ namespace mbts.ui.spark.converters { } public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) { var price = get_val(values, 0); - var spec = get_val(values, 1); - if (spec == null) return price.ToString(); - return spec.Value.format(price); + var security = get_val(values, 1); + if (security == null) return price.ToString(); + return security.Value.format(price); } public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture) => @@ -26,23 +26,17 @@ namespace mbts.ui.spark.converters { } class TickDisplayTwoWayConverter : IValueConverter { - public ContractSpecificationImmutable? ContractSpec { get; set; } = - new ContractSpecification { - CashPerPoint = 1.0, - LowTick = 0.01, - HighTick = 0.01, - PriceBreak = double.MaxValue, - PriceMultiplier = 1.0 - }; + public SecurityImmutable? Security { get; set; } = + SecurityDataHelper.Defaults.SecurityImmutable; public double DisplayMultiplier { get; set; } = double.NaN; public bool ShowCommas { get; set; } = false; public string NaNText { get; set; } = string.Empty; public object Convert(object value, Type targetType, object parameter, CultureInfo culture) => - ContractSpec.Value.format((double)value, DisplayMultiplier, ShowCommas, NaNText); + Security.format((double)value, DisplayMultiplier, ShowCommas, NaNText); public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) => - ContractSpec.Value.parse(value as string, DisplayMultiplier, NaNText); + Security.parse(value as string, DisplayMultiplier, NaNText); } } \ No newline at end of file diff --git a/src/client/spark/view/Spark/Core/OrderUtils.cs b/src/client/spark/view/Spark/Core/OrderUtils.cs index c2ce9379c..bcff6111e 100644 --- a/src/client/spark/view/Spark/Core/OrderUtils.cs +++ b/src/client/spark/view/Spark/Core/OrderUtils.cs @@ -1,8 +1,6 @@ using bts.api; using bts.api.orderman; using System; -using System.Collections.Generic; -using System.Linq; using System.Text; using System.Text.RegularExpressions; using static mbts.ui.utilities.DisplayNameHelper; @@ -75,7 +73,7 @@ namespace mbts.spark { if (order.HasDef) { sec_key_text = $"Security: {order.Def.SecurityKey}"; if (order.HasState) { - sb.AppendLine($"{order.Def.Side}: {TickUtils.format(security.ContractSpec, order.State.Price)}"); + sb.AppendLine($"{order.Def.Side}: {security.format(order.State.Price)}"); sb.AppendLine($"Filled: {filled(order)} / {order.State.Quantity}"); } else { sb.AppendLine($"{order.Def.Side}: (price-unknown)"); @@ -97,8 +95,8 @@ namespace mbts.spark { return sb.ToString(); } - public static string short_description(this OrderRecordImmutable order, ContractSpecificationImmutable? spec) => - $"{(order.HasDef ? order.Def.Side.ToString() : "(unknown-side)")} {(order.HasState ? ($@"{spec.format(order.State.Price)} @ {order.State.Quantity}") : "(unknown-price) @ (unknown-quantity)")}"; + public static string short_description(this OrderRecordImmutable order, SecurityImmutable? security) => + $"{(order.HasDef ? order.Def.Side.ToString() : "(unknown-side)")} {(order.HasState ? ($@"{security.format(order.State.Price)} @ {order.State.Quantity}") : "(unknown-price) @ (unknown-quantity)")}"; public static bool has_parent(this OrderRecordImmutable order) => order.ParentKey != 0; @@ -121,24 +119,12 @@ namespace mbts.spark { public static string order_type_display_name(CustomOrderDefinition.CustomOneofCase order_type) => camel_to_title_case(Regex.Replace(order_type.ToString(), "Order", string.Empty, RegexOptions.IgnoreCase)); - public static string order_collection_summary(ICollection orders, Comparison compare_price, ContractSpecificationImmutable spec) { - if (orders.Count == 0) return string.Empty; - var price_lookup = orders.ToLookup(o => o.State.Price); - var best_price = price_lookup.MaxElement(g => g.Key, compare_price); - var best_price_volume = best_price.Sum(o => o.working_quantity()); - return order_collection_summary( - best_price.Key, - best_price_volume, - best_price_volume + price_lookup.Where(g => g.Key != best_price.Key).SelectMany(g => g).Sum(o => o.working_quantity()), - spec); - } - - public static string order_collection_summary(double best_price, int best_price_volume, int total_volume, ContractSpecificationImmutable spec) { + public static string order_collection_summary(double best_price, int best_price_volume, int total_volume, SecurityImmutable security) { if (total_volume == 0) return string.Empty; return total_volume == best_price_volume ? - $"{best_price_volume} @ {spec.format(best_price)}" : - $"{best_price_volume} ({total_volume}) @ {spec.format(best_price)}"; + $"{best_price_volume} @ {security.format(best_price)}" : + $"{best_price_volume} ({total_volume}) @ {security.format(best_price)}"; } public static string past_tense(this Side side) { diff --git a/src/client/spark/view/Spark/Core/TickUtils.cs b/src/client/spark/view/Spark/Core/TickUtils.cs index 2e43a3da8..22498d531 100644 --- a/src/client/spark/view/Spark/Core/TickUtils.cs +++ b/src/client/spark/view/Spark/Core/TickUtils.cs @@ -10,101 +10,26 @@ using System.Linq; namespace mbts.spark { static class TickUtils { - #region TickFactors Cache - static readonly TickFactors _default_tick = new TickFactors(100, 1); - - static readonly ConcurrentDictionary _resolved_unknown_ticks = new ConcurrentDictionary(); - - static readonly ConcurrentDictionary<(double low_tick, double high_tick, double price_break), RegionalTickFactors> _regional_ticks_cache = - new ConcurrentDictionary<(double low_tick, double high_tick, double price_break), RegionalTickFactors>(); - - static readonly double[] _descending_tick_fractional_units; - - static readonly IReadOnlyDictionary _ticks_cache = new[] { - // 100 based - new { tick_unit = 0.01, tick_factors = new TickFactors(100, 1) }, // 1/100 - new { tick_unit = 0.05, tick_factors = new TickFactors(100, 5) }, // 1/20 - new { tick_unit = 0.10, tick_factors = new TickFactors(100, 10) }, // 1/10 - new { tick_unit = 0.25, tick_factors = new TickFactors(100, 25) }, // 1/4 - new { tick_unit = 0.50, tick_factors = new TickFactors(100, 50) }, // 1/2 - // 1,000 based - new { tick_unit = 0.001, tick_factors = new TickFactors(1000, 1) }, // 1/1,000 - new { tick_unit = 0.005, tick_factors = new TickFactors(1000, 5) }, // 1/200 - new { tick_unit = 0.025, tick_factors = new TickFactors(1000, 25) }, // 1/40 - // 10,000 based - new { tick_unit = 0.0001, tick_factors = new TickFactors(10000, 1) }, // 1/10,000 - new { tick_unit = 0.0005, tick_factors = new TickFactors(10000, 5) }, // 1/2,000 - new { tick_unit = 0.0025, tick_factors = new TickFactors(10000, 25) }, // 1/400 - // 64 based - new { tick_unit = 0.015625, tick_factors = new TickFactors(64, 1) }, // 1/64 - new { tick_unit = 0.03125, tick_factors = new TickFactors(64, 2) }, // 1/32 - new { tick_unit = 0.0625, tick_factors = new TickFactors(64, 4) }, // 1/16 - new { tick_unit = 0.125, tick_factors = new TickFactors(64, 8) }, // 1/8 - // 640 based - new { tick_unit = 0.0015625, tick_factors = new TickFactors(640, 1) }, // 1/640 - new { tick_unit = 0.003125, tick_factors = new TickFactors(640, 2) }, // 1/320 - new { tick_unit = 0.00625, tick_factors = new TickFactors(640, 4) }, // 1/160 - new { tick_unit = 0.0078125, tick_factors = new TickFactors(640, 5) }, // 1/128 - new { tick_unit = 0.0125, tick_factors = new TickFactors(640, 8) }, // 1/80 - new { tick_unit = 0.0390625, tick_factors = new TickFactors(640, 25) }, // 5/128 - new { tick_unit = 0.078125, tick_factors = new TickFactors(640, 50) }, // 5/64 - // 6,400 based - new { tick_unit = 0.00015625, tick_factors = new TickFactors(6400, 1) }, // 1/6,400 - new { tick_unit = 0.0003125, tick_factors = new TickFactors(6400, 2) }, // 1/3,200 - new { tick_unit = 0.000625, tick_factors = new TickFactors(6400, 4) }, // 1/1,600 - new { tick_unit = 0.00078125, tick_factors = new TickFactors(6400, 5) }, // 1/1,280 - new { tick_unit = 0.00125, tick_factors = new TickFactors(6400, 8) }, // 1/800 - new { tick_unit = 0.00390625, tick_factors = new TickFactors(6400, 25) }, // 1/256 - // 64,000 based - new { tick_unit = 0.000015625, tick_factors = new TickFactors(64000, 1) }, // 1/6,400 - new { tick_unit = 0.00003125, tick_factors = new TickFactors(64000, 2) }, // 1/3,200 - new { tick_unit = 0.0000625, tick_factors = new TickFactors(64000, 4) }, // 1/1,600 - new { tick_unit = 0.000078125, tick_factors = new TickFactors(64000, 5) }, // 1/12,800 - new { tick_unit = 0.000125, tick_factors = new TickFactors(64000, 8) }, // 1/8,000 - new { tick_unit = 0.000390625, tick_factors = new TickFactors(64000, 25) }, // 1/2,560 - new { tick_unit = 0.001953125, tick_factors = new TickFactors(64000, 125) },// 1/512 - }.ToReadOnlyDictionary(obj => obj.tick_unit, obj => obj.tick_factors, EqualityComparer.Create(MathUtils.epsilon_equals)); - #endregion - - static TickUtils() { - // overkill? Maybe, but ticks are fundamental to the entire application. - // Any changes to the tick defaults must be deliberate, and scrutinized. - Logger.assert(_ticks_cache.Count == 35); - foreach(var kv in _ticks_cache) { - double result = kv.Value.tick_unit / kv.Value.tick_base; - Logger.assert(result == kv.Key, $"{kv.Value.tick_unit}/{kv.Value.tick_base} ({result} != {kv.Key})"); - } - _descending_tick_fractional_units = _ticks_cache.Keys.Ordered(new ReverseComparer(Comparer.Default)).ToLArray(); - } - public static double ticksize(this ContractSpecificationImmutable spec, double price) => Math.Abs(price) > spec.PriceBreak ? spec.HighTick : spec.LowTick; - public static string format(this ContractSpecificationImmutable spec, double price) { - var tick_factors = _get_tick_factors(spec.ticksize(price)); - return tick_factors.format(price, false); - } - public static string format(this ContractSpecificationImmutable? spec, double price) { - if (spec.HasValue) { - return spec.Value.format(price); - } - return price.ToString("0.00000"); - } + public static string format(this SecurityImmutable security, double price) => + TickStore.get(security).format(price); - public static string format(this ContractSpecificationImmutable spec, double price, double display_multiplier, bool show_commas, string nan_text) { - var tick_factors = _get_tick_factors(spec.ticksize(price)); - return tick_factors.format(price, display_multiplier, show_commas, nan_text); - } + public static string format(this SecurityImmutable? security, double price) => + security.HasValue ? security.Value.format(price) : price.ToString("0.00000"); - public static double parse(this ContractSpecificationImmutable spec, string text) { - var regional_tfs = get_regional_ticks(spec); - return regional_tfs.parse(text); - } + public static string format(this SecurityImmutable security, double price, double display_multiplier, bool show_commas, string nan_text) => + TickStore.get(security).format(price, display_multiplier, show_commas, nan_text); - public static double parse(this ContractSpecificationImmutable spec, string text, double display_multiplier, string nan_text) { - var regional_tfs = get_regional_ticks(spec); - return regional_tfs.parse(text, display_multiplier, nan_text); - } + public static string format(this SecurityImmutable? security, double price, double display_multiplier, bool show_commas, string nan_text) => + TickStore.get(security).format(price, display_multiplier, show_commas, nan_text); + + public static double parse(this SecurityImmutable security, string text, double display_multiplier, string nan_text) => + TickStore.get(security).parse(text, display_multiplier, nan_text); + + public static double parse(this SecurityImmutable? security, string text, double display_multiplier, string nan_text) => + TickStore.get(security).parse(text, display_multiplier, nan_text); public static double low_tick(NativePriceSize[] bids, NativePriceSize[] asks) { double low = bids[bids.Length - 1].price; @@ -124,11 +49,11 @@ namespace mbts.spark { return high; } - public static (int n_low, int n_high) tick_diff(ContractSpecificationImmutable spec, double x, double y) => - get_regional_ticks(spec).tickdiff(x, y); + public static (int n_low, int n_high) tick_diff(SecurityImmutable security, double x, double y) => + get_regional_ticks(security).tickdiff(x, y); - public static int normalized_tick_diff(ContractSpecificationImmutable spec, double x, double y) { - var (n_low, n_high) = tick_diff(spec, x, y); + public static int normalized_tick_diff(SecurityImmutable security, double x, double y) { + var (n_low, n_high) = tick_diff(security, x, y); return n_low + n_high; } @@ -147,7 +72,7 @@ namespace mbts.spark { } public static IReadOnlyList all_present_ticks() => - _ticks_cache.Values.ToReadOnlyList(); + TickStore.all_present_ticks(); public static TickFactors deduce_ticks(IEnumerable contract_specs) { var gcd = MathUtils.GCD(contract_specs.Select(s => s.LowTick)); @@ -155,27 +80,29 @@ namespace mbts.spark { return _try_get_tick_factors(gcd); } - public static double tickup(this ContractSpecificationImmutable contract, double value) => - get_regional_ticks(contract).tickup(value); + public static double tickup(this SecurityImmutable security, double value) => + TickStore.get(security).tickup(value); - public static double tickup(this ContractSpecificationImmutable contract, double value, int count) => - get_regional_ticks(contract).tickup(value, (uint)count); + public static double tickup(this SecurityImmutable security, double value, int count) => + TickStore.get(security).tickup(value, (uint)count); - public static double tickdown(this ContractSpecificationImmutable contract, double value) => - get_regional_ticks(contract).tickdown(value); + public static double tickdown(this SecurityImmutable security, double value) => + TickStore.get(security).tickdown(value); - public static double tickdown(this ContractSpecificationImmutable contract, double value, int count) => - get_regional_ticks(contract).tickdown(value, (uint)count); + public static double tickdown(this SecurityImmutable security, double value, int count) => + TickStore.get(security).tickdown(value, (uint)count); + + public static bool tick_equals(this SecurityImmutable security, double x, double y) => + tick_equals(security.ContractSpec, x, y); public static bool tick_equals(this ContractSpecificationImmutable contract, double x, double y) => MathUtils.RoundFractionalUnits(x, contract.LowTick) == MathUtils.RoundFractionalUnits(y, contract.LowTick); - public static IEqualityComparer tick_equality_comparer(this ContractSpecificationImmutable contract) - { - var eq = EqualityComparer.Create((double a, double b) => TickUtils.tick_equals(contract, a, b), - x => MathUtils.RoundFractionalUnits(x, contract.LowTick)); - return eq; - } + public static IEqualityComparer tick_equality_comparer(this SecurityImmutable security) => + security.ContractSpec.tick_equality_comparer(); + + public static IEqualityComparer tick_equality_comparer(this ContractSpecificationImmutable contract) => + EqualityComparer.Create((double a, double b) => tick_equals(contract, a, b), x => MathUtils.RoundFractionalUnits(x, contract.LowTick)); public static double round_to_tick(this ContractSpecificationImmutable spec, double value) { double intpart = (long)value; @@ -185,47 +112,148 @@ namespace mbts.spark { return intpart + floatpart; } - public static RegionalTickFactors get_regional_ticks(ContractSpecificationImmutable spec) => - _regional_ticks_cache.GetOrAdd((spec.LowTick, spec.HighTick, spec.PriceBreak), _create_regional_ticks); + public static RegionalTickFactors get_regional_ticks(SecurityImmutable security) => + TickStore.get(security); - public static RegionalTickFactors get_regional_ticks(ContractSpecification spec) => - _regional_ticks_cache.GetOrAdd((spec.LowTick, spec.HighTick, spec.PriceBreak), _create_regional_ticks); + static TickFactors _try_get_tick_factors(double tick) => + TickStore.get(tick); - static RegionalTickFactors _create_regional_ticks((double low_tick, double high_tick, double price_break) def) => - new RegionalTickFactors(_get_tick_factors(def.low_tick), _get_tick_factors(def.high_tick), def.price_break); + static class TickStore { + static readonly RegionalTickFactors _default_rtf = new RegionalTickFactors(new TickFactors(1000, 1), new TickFactors(1000, 1), double.MaxValue); + static readonly ConcurrentDictionary _known_ticks = new ConcurrentDictionary(); + static readonly ConcurrentDictionary _unit_map = new ConcurrentDictionary(); - static TickFactors _get_tick_factors(double tick) { - if (_ticks_cache.TryGetValue(tick, out TickFactors result)) - return result; - // try to return the largest known tick that is divisible by this tick - foreach (var tfu in _descending_tick_fractional_units) { - double mod = tick % tfu; - if (MathUtils.epsilon_equals(mod, 0)) { - if (_resolved_unknown_ticks.TryAdd(tick, true)) - Logger.warn(bts.log.Subsystem.Ui, $"Resolved unknown tick {tick} to {tfu}, if this tick is expected, talk to John about adding it to the hard-coded defaults ASAP."); - return _ticks_cache[tfu]; + public static RegionalTickFactors get(SecurityImmutable security) => + security.HasGlbx && security.HasContractSpec ? + _known_ticks.GetOrAdd(new SpecKey(security.ContractSpec, security.Glbx), _create_rtf) : _default_rtf; + + public static RegionalTickFactors get(SecurityImmutable? security) => + security.HasValue ? get(security.Value) : _default_rtf; + + public static TickFactors get(double unit) => + _unit_map.GetOrAdd(unit, _create_tf); + + public static IReadOnlyList all_present_ticks() { + var set = new HashSet(); + foreach (var kv in _known_ticks) { + set.Add(kv.Value.low_tick); + set.Add(kv.Value.high_tick); } + return set.ToList(); } - Logger.assert(false, $"Unable to resolve tick ({tick}): going down because the application cannot run properly with unresolved ticks. " + - $"FOR DEVS: If this tick was not caused by a bug, please talk to John about adding it to the hard-coded defaults. " + - $"If you believe this tick belongs to a synthetic security, and should not be in the defaults, please delete said synthetic from the db " + - $"(note: the synthetic creation dialog has changed to only allow known ticks from now on, so if you get the latest code and delete old synthetics from the db, this will not happen again). " + - $"Direct any further questions to John."); - return null; - } - // Almost the same function as _get_tick_factors, only difference being no assert/log. - // This seemed more practical than trying to factor this behavior out, it's only a few lines of code. - static TickFactors _try_get_tick_factors(double tick) { - if (_ticks_cache.TryGetValue(tick, out TickFactors result)) - return result; - // try to return the largest known tick that is divisible by this tick - foreach (var tfu in _descending_tick_fractional_units) { - double mod = tick % tfu; - if (MathUtils.epsilon_equals(mod, 0)) - return _ticks_cache[tfu]; + static RegionalTickFactors _create_rtf(SpecKey key) { + double tick_base = key.denominator; + if (tick_base == 0) { + // indicates tick is a decimal + tick_base = 100; + } + int inherrent_display_digits = (int)Math.Ceiling(Math.Log10(tick_base)); + int display_digit_diff = (int)key.display_digits - inherrent_display_digits; + if (display_digit_diff > 0) + tick_base *= Math.Pow(10, display_digit_diff); + return _create_rtf(key.low_tick, key.high_tick, key.price_break, tick_base); + } + + static RegionalTickFactors _create_rtf(double low_tick, double high_tick, double price_break, double reduced_target_base) { + var low_tf = _try_create_tf(low_tick, reduced_target_base); + var high_tf = _try_create_tf(high_tick, reduced_target_base); + if (low_tf == null) { + low_tf = high_tf ?? (high_tf = _default_rtf.low_tick); + } else if (high_tf == null) + high_tf = low_tf; + else { + // if low/high tick-bases do not match, inflate the smaller base so they do + // Note: this assumes the tick-bases are related by factors of 10 (i.e. they have all the same prime factors except for a different number of pairs of 5 and 2, e.g. 64 and 640) + if (low_tf.tick_base > high_tf.tick_base) { + high_tf = _inflate_to_base(high_tf, low_tf.tick_base); + } else if (low_tf.tick_base < high_tf.tick_base) { + low_tf = _inflate_to_base(low_tf, high_tf.tick_base); + } + } + return new RegionalTickFactors(low_tf, high_tf, price_break); + } + + /// + /// Creates TickFactors with a base equal to "reduced_target_base * 10^n," where 'n' is a natural number (including 0). + /// + /// The raw tick-size. + /// The smallest acceptable tick-base. + /// Well-defined TickFactors + static TickFactors _try_create_tf(double tick_size, double reduced_target_base) { + if (!_check_tick_size(tick_size)) + return null; + double raw_base = 1 / tick_size; + double raw_base_log10 = Math.Log10(raw_base); + double reduced_target_base_log10 = Math.Log10(reduced_target_base); + double log10_diff = raw_base_log10 - reduced_target_base_log10; + if (MathUtils.is_int(log10_diff)) + return raw_base > reduced_target_base ? new TickFactors(raw_base, 1) : new TickFactors(reduced_target_base, Math.Pow(10, -log10_diff)); + int count = 0; + double factored_base = log10_diff > 0 ? reduced_target_base * Math.Pow(10, Math.Ceiling(log10_diff)) : reduced_target_base; + do { + if (factored_base % raw_base == 0) + return new TickFactors(factored_base, factored_base / raw_base); + factored_base *= 10; + } while (++count < 10); + return null; + } + + static TickFactors _create_tf(double tick_size) { + if (!_check_tick_size(tick_size)) + return _default_rtf.low_tick; + double matched_unit = double.MinValue; + TickFactors matched_tf = null; + foreach (var kv in _known_ticks) { + if (kv.Key.high_tick == tick_size) { + return kv.Value.high_tick; + } else if (kv.Key.low_tick == tick_size) { + return kv.Value.low_tick; + } else if (is_match(kv.Key.high_tick)) { + matched_unit = kv.Key.high_tick; + matched_tf = kv.Value.high_tick; + } else if (is_match(kv.Key.low_tick)) { + matched_unit = kv.Key.low_tick; + matched_tf = kv.Value.low_tick; + } + } + return matched_tf ?? new TickFactors(1.0 / tick_size, 1); + + bool is_match(double known_unit) => + known_unit < tick_size && known_unit > matched_unit && tick_size % known_unit == 0; + } + + static bool _check_tick_size(double tick_size) => + tick_size > 0 && tick_size < 0.5; + + static TickFactors _inflate_to_base(TickFactors tick_factors, double new_base) => + new TickFactors(new_base, tick_factors.tick_unit * new_base / tick_factors.tick_base); + + struct SpecKey : IEquatable { + public readonly uint denominator, display_digits; + public readonly double low_tick, high_tick, price_break; + + public SpecKey(ContractSpecificationImmutable spec, GLBXExchangeDataImmutable glbx_data) { + denominator = glbx_data.MainFraction; + display_digits = glbx_data.PriceDisplayFormat; + low_tick = spec.LowTick; + high_tick = spec.HighTick; + price_break = spec.PriceBreak; + } + + public bool Equals(SpecKey other) => + denominator == other.denominator && + display_digits == other.display_digits && + low_tick == other.low_tick && + high_tick == other.high_tick && + price_break == other.price_break; + + public override bool Equals(object obj) => + obj is SpecKey sk && Equals(sk); + + public override int GetHashCode() => + EqualityComparer.aggregate_hash((int)denominator, (int)display_digits, low_tick.GetHashCode(), high_tick.GetHashCode(), price_break.GetHashCode()); } - return null; } } } \ No newline at end of file diff --git a/src/client/spark/view/Spark/Grid/ISecurityRow.cs b/src/client/spark/view/Spark/Grid/ISecurityRow.cs index 681460b68..88c97b79d 100644 --- a/src/client/spark/view/Spark/Grid/ISecurityRow.cs +++ b/src/client/spark/view/Spark/Grid/ISecurityRow.cs @@ -14,6 +14,6 @@ namespace mbts.spark { static class SecurityRowExtensions { public static string format_price(this ISecurityRow row, double price) => - row.security.ContractSpec.format(price); + row.security.format(price); } } \ No newline at end of file diff --git a/src/client/spark/view/Spark/Ladder/LadderGridHost.cs b/src/client/spark/view/Spark/Ladder/LadderGridHost.cs index f2a4b069f..4f9fc21b9 100644 --- a/src/client/spark/view/Spark/Ladder/LadderGridHost.cs +++ b/src/client/spark/view/Spark/Ladder/LadderGridHost.cs @@ -306,13 +306,13 @@ namespace mbts.spark { _settings.row_height, _price_list, column.settings, - security.ContractSpec); + security); break; case ColumnType.Ask: render_market_col(_asks); break; } void render_market_col(NativePriceSize[] depth) { var mid = LadderRender.index_of(_price_list, _last_origin_price, _price_comparer); - LadderRender.render_sizes(column.visual_tup.visual, column.visual_tup.glyph_context, mid, _price_list, depth, _settings.row_height, security.ContractSpec, column.settings); + LadderRender.render_sizes(column.visual_tup.visual, column.visual_tup.glyph_context, mid, _price_list, depth, _settings.row_height, security, column.settings); } } _apply_column_visual_offset(); @@ -390,8 +390,8 @@ namespace mbts.spark { SparkUtils.lazy_warn(!double.IsNaN(_mkt_break_lines.origin) && _mkt_break_lines.origin >= low && _mkt_break_lines.origin <= high, () => fmt_log_msg($"market break ({_mkt_break_lines.origin}) is unacceptable for the market range ({low} - {high})")); int prev_row_count = _row_count; - int n_ticks_to_low = TickUtils.normalized_tick_diff(security.ContractSpec, _mkt_break_lines.origin, low); - int n_ticks_to_high = TickUtils.normalized_tick_diff(security.ContractSpec, high, _mkt_break_lines.origin); + int n_ticks_to_low = TickUtils.normalized_tick_diff(security, _mkt_break_lines.origin, low); + int n_ticks_to_high = TickUtils.normalized_tick_diff(security, high, _mkt_break_lines.origin); int desired_row_count = Math.Max(n_ticks_to_low, n_ticks_to_high) * 2 + 1; _row_count = Math.Min(_max_row_count, desired_row_count); if (_row_count != prev_row_count) { @@ -412,7 +412,7 @@ namespace mbts.spark { } if (update_prices) { var prev_price_list = _price_list; - _price_list = 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); + _price_list = 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); _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 @@ -447,8 +447,8 @@ namespace mbts.spark { if (update_prices || depth_changed) { Logger.assert_d(_price_list != null); int origin_index = LadderRender.index_of(_price_list, _mkt_break_lines.origin, _price_comparer); - LadderRender.render_sizes(_bid_vis_tup.visual, _bid_vis_tup.glyph_context, origin_index, _price_list, _bids, _settings.row_height, security.ContractSpec, _settings.bid_column); - LadderRender.render_sizes(_ask_vis_tup.visual, _ask_vis_tup.glyph_context, origin_index, _price_list, _asks, _settings.row_height, security.ContractSpec, _settings.ask_column); + LadderRender.render_sizes(_bid_vis_tup.visual, _bid_vis_tup.glyph_context, origin_index, _price_list, _bids, _settings.row_height, security, _settings.bid_column); + LadderRender.render_sizes(_ask_vis_tup.visual, _ask_vis_tup.glyph_context, origin_index, _price_list, _asks, _settings.row_height, security, _settings.ask_column); } _last_origin_price = _mkt_break_lines.origin; _price_dirty = false; @@ -472,7 +472,7 @@ namespace mbts.spark { double best_bid = _get_top_price(_bids); double best_ask = _get_top_price(_asks); return double.IsNaN(best_bid) ? - double.IsNaN(best_ask) ? _vm.low : security.ContractSpec.tickdown(best_ask) : + double.IsNaN(best_ask) ? _vm.low : security.tickdown(best_ask) : best_bid; } @@ -480,15 +480,15 @@ namespace mbts.spark { double best_bid = _get_top_price(_bids); double best_ask = _get_top_price(_asks); return double.IsNaN(best_ask) ? - double.IsNaN(best_bid) ? security.ContractSpec.tickdown(_vm.high) : best_bid : - security.ContractSpec.tickdown(best_ask); + double.IsNaN(best_bid) ? security.tickdown(_vm.high) : best_bid : + security.tickdown(best_ask); } double _get_mid_market_break() { double best_bid = _get_top_price(_bids); double best_ask = _get_top_price(_asks); return double.IsNaN(best_bid) ? - double.IsNaN(best_ask) ? 0.5 * (_vm.low + _vm.high) : security.ContractSpec.tickdown(best_ask) : + double.IsNaN(best_ask) ? 0.5 * (_vm.low + _vm.high) : security.tickdown(best_ask) : double.IsNaN(best_ask) ? best_bid : TickUtils.mid_tick(security.ContractSpec, best_bid, best_ask); } diff --git a/src/client/spark/view/Spark/Ladder/LadderOrderVM.cs b/src/client/spark/view/Spark/Ladder/LadderOrderVM.cs index cf7f4e8bc..ef4189c3b 100644 --- a/src/client/spark/view/Spark/Ladder/LadderOrderVM.cs +++ b/src/client/spark/view/Spark/Ladder/LadderOrderVM.cs @@ -1,6 +1,5 @@ using bts.api; using bts.api.orderman; -using bts.spark; using mbts.ui; using mbts.ui.shell; using System; @@ -99,7 +98,7 @@ namespace mbts.spark { if (_orders.Count > 0) { - summary = _orders.Values.Select(order => order.short_description(_parent.security.ContractSpec)).Aggregate((s1, s2) => $"{s1}{Environment.NewLine}{Environment.NewLine}{s2}"); + summary = _orders.Values.Select(order => order.short_description(_parent.security)).Aggregate((s1, s2) => $"{s1}{Environment.NewLine}{Environment.NewLine}{s2}"); description = _orders.Values.Select(order => order.full_description(_parent.security)).Aggregate((s1, s2) => $"{s1}{Environment.NewLine}{Environment.NewLine}{s2}"); } _set_badge_text(); @@ -197,4 +196,4 @@ namespace mbts.spark { return $"Price: {this.price} Order Count: {this.orders.Count()}"; } } -} +} \ No newline at end of file diff --git a/src/client/spark/view/Spark/Ladder/LadderView.xaml b/src/client/spark/view/Spark/Ladder/LadderView.xaml index def88911b..385151bf8 100644 --- a/src/client/spark/view/Spark/Ladder/LadderView.xaml +++ b/src/client/spark/view/Spark/Ladder/LadderView.xaml @@ -317,7 +317,7 @@ - + @@ -325,7 +325,7 @@ - + @@ -333,7 +333,7 @@ - + @@ -341,7 +341,7 @@ - + @@ -349,7 +349,7 @@ - + diff --git a/src/client/spark/view/Spark/Ladder/LaderRender.cs b/src/client/spark/view/Spark/Ladder/LaderRender.cs index 8458c5702..4218865bc 100644 --- a/src/client/spark/view/Spark/Ladder/LaderRender.cs +++ b/src/client/spark/view/Spark/Ladder/LaderRender.cs @@ -57,7 +57,7 @@ namespace mbts.spark { 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 double[] gen_prices(double mid, int row_count, ContractSpecificationImmutable spec) { + public static double[] gen_prices(double mid, int row_count, SecurityImmutable security) { // require odd number Logger.assert(row_count % 2 == 1); var result = new double[row_count]; @@ -67,32 +67,32 @@ namespace mbts.spark { double up = mid, down = mid; // Starting from the middle iterate out to the edges for (int x = 1; x <= range; ++x) { - up = TickUtils.tickup(spec, up); - down = TickUtils.tickdown(spec, down); + up = security.tickup(up); + down = security.tickdown(down); result[middle - x] = up; result[middle + x] = down; } 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, SecurityImmutable security) { 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(security.format(prices[i]), i, row_height, settings, glyph_context)); return result; } public static double[] render_prices(DrawingVisual price, GlyphContext glyph_context, double mid, int row_count, double row_height, - LadderColumnSettings settings, ContractSpecificationImmutable spec) { - var dprices = gen_prices(mid, row_count, spec); - render_prices(price, glyph_context, row_count, row_height, dprices, settings, spec); + LadderColumnSettings settings, SecurityImmutable security) { + var dprices = gen_prices(mid, row_count, security); + render_prices(price, glyph_context, row_count, row_height, dprices, settings, security); return dprices; } - 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, SecurityImmutable security) { 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, security); 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)); @@ -126,7 +126,7 @@ namespace mbts.spark { double[] prices, NativePriceSize[] rungs, double row_height, - ContractSpecificationImmutable spec, + SecurityImmutable security, LadderColumnSettings settings ) { //var background = new SolidColorBrush(settings.background.rgb_color()); @@ -143,7 +143,7 @@ namespace mbts.spark { double price = nps.price; ushort size = nps.size; // prices are in descending order, so get diff from curr_price - price - int tick_diff = TickUtils.normalized_tick_diff(spec, curr_price, price); + int tick_diff = TickUtils.normalized_tick_diff(security, curr_price, price); curr_index += tick_diff; curr_price = price; if (curr_index >= 0 && curr_index < prices.Length) { diff --git a/src/client/spark/view/Spark/Ladder/RecenterCountdown.cs b/src/client/spark/view/Spark/Ladder/RecenterCountdown.cs index 3e97c523d..bf1ffaeba 100644 --- a/src/client/spark/view/Spark/Ladder/RecenterCountdown.cs +++ b/src/client/spark/view/Spark/Ladder/RecenterCountdown.cs @@ -30,10 +30,6 @@ namespace mbts.spark { _seconds_to_center = TimeSpan.FromSeconds(config.Configuration.get().seconds_to_recenter); } - static (double,double) tick_range(double price, int tick_count, ContractSpecificationImmutable spec) { - return (TickUtils.tickdown(spec, price, tick_count), TickUtils.tickup(spec, price, tick_count)); - } - private void _timer_Tick(object sender, EventArgs e) { if (_security != null) { var mid = _handle.mid(); diff --git a/src/client/spark/view/Spark/PAndL/PAndLView.xaml b/src/client/spark/view/Spark/PAndL/PAndLView.xaml index c43ff29c9..ac770efc4 100644 --- a/src/client/spark/view/Spark/PAndL/PAndLView.xaml +++ b/src/client/spark/view/Spark/PAndL/PAndLView.xaml @@ -94,7 +94,7 @@ - + @@ -113,7 +113,7 @@ - + diff --git a/src/client/spark/view/Spark/Shell/CVOrderBook/CVOrderBookRowVM.cs b/src/client/spark/view/Spark/Shell/CVOrderBook/CVOrderBookRowVM.cs index 877f21089..e1480170a 100644 --- a/src/client/spark/view/Spark/Shell/CVOrderBook/CVOrderBookRowVM.cs +++ b/src/client/spark/view/Spark/Shell/CVOrderBook/CVOrderBookRowVM.cs @@ -76,7 +76,7 @@ namespace mbts.spark { _status_store = CellFactory.create(this, _book_vm.columns.status_column, nameof(status), r => _order.status(), r => r._status_store); _last_msg_store = CellFactory.create(this, _book_vm.columns.last_message_column, nameof(last_msg), r => _order.last_msg(), r => r._last_msg_store); // - string format_price(double v) => _security.HasValue ? _security.Value.ContractSpec.format(v) : + string format_price(double v) => _security.HasValue ? _security.Value.format(v) : Math.Round(v, _unknown_security_price_num_fractional_digits, MidpointRounding.AwayFromZero).ToString(_unknown_security_price_format_string); string format_date(DateTime v) => $"{v:M/d} {v:h:mm:ss.fff tt}"; string format_sub_type(OrderSubType v) { diff --git a/src/client/spark/view/Spark/Shell/OrderBook/OrderBookColumns.cs b/src/client/spark/view/Spark/Shell/OrderBook/OrderBookColumns.cs index 401900572..ccab878e8 100644 --- a/src/client/spark/view/Spark/Shell/OrderBook/OrderBookColumns.cs +++ b/src/client/spark/view/Spark/Shell/OrderBook/OrderBookColumns.cs @@ -41,7 +41,7 @@ namespace mbts.spark { public static GlyphContext get_glyph_context(OrderBookRowVM r) => r.is_child ? _child_glyph_context : TextUtils.StandardGlyphContext; public static Brush get_side_brush(OrderBookRowVM r) => r.side == Side.Buy ? BTSColors.MarketData.bid : BTSColors.MarketData.ask; public static BindingBase get_font_weight_binding() => new Binding(nameof(OrderBookRowVM.is_child)) { Converter = _font_weight_converter }; - public static string format_price(OrderBookRowVM row, double price) => row.security.HasValue ? row.security.Value.ContractSpec.format(price) : row.price.ToString(); + public static string format_price(OrderBookRowVM row, double price) => row.security.HasValue ? row.security.Value.format(price) : row.price.ToString(); } abstract class OrderbookColumnBase : ColumnBase, IKeyedColumn, IFilterableColumn { diff --git a/src/client/spark/view/Spark/Utilities/MathUtils.cs b/src/client/spark/view/Spark/Utilities/MathUtils.cs index 16a295c45..83cf83dbe 100644 --- a/src/client/spark/view/Spark/Utilities/MathUtils.cs +++ b/src/client/spark/view/Spark/Utilities/MathUtils.cs @@ -61,7 +61,27 @@ namespace mbts.spark.utilities { if (value > max) return max; return value; } + public static bool is_within_range(double min, double max, double value) => + value >= min && value <= max; + public static int RoundFractionalUnits(double value, double fractional_unit) => (int)Math.Round(value / fractional_unit); + + public static bool is_int(double d) => + epsilon_equals(d, (int)d); + + public static double factor_out(double value, double factor) => + factor_out(value, factor, out int _); + + public static double factor_out(double value, double factor, out int log10_reduction) { + log10_reduction = 0; + double quotient = value / factor; + while (is_int(quotient)) { + value = quotient; + ++log10_reduction; + quotient /= factor; + } + return value; + } } } \ No newline at end of file diff --git a/src/client/spark/view/Spark/Utilities/SecurityDataHelper.cs b/src/client/spark/view/Spark/Utilities/SecurityDataHelper.cs index 8e3f476d9..b8bfb5d6e 100644 --- a/src/client/spark/view/Spark/Utilities/SecurityDataHelper.cs +++ b/src/client/spark/view/Spark/Utilities/SecurityDataHelper.cs @@ -15,11 +15,13 @@ namespace mbts.spark public static class Defaults { public static ContractSpecification ContractSpecification => new ContractSpecification { CashPerPoint = 1.0, LowTick = 0.01, HighTick = 0.01, PriceBreak = double.MaxValue, PriceMultiplier = 1.0 }; + public static GLBXExchangeData GlbxExchangeData => new GLBXExchangeData { MainFraction = 1000, PriceDisplayFormat = 3 }; public static readonly ContractSpecificationImmutable ContractSpecificationImmutable = new ContractSpecificationImmutable(ContractSpecification); public static Security Security => new Security { Symbol = string.Empty, Exchange = Venue.Bts, ContractSpec = ContractSpecification, + Glbx = GlbxExchangeData }; public static readonly SecurityImmutable SecurityImmutable = new SecurityImmutable(Security); } diff --git a/src/lib/CMakeDeps.cmake b/src/lib/CMakeDeps.cmake index 5e1985320..fc06362b7 100644 --- a/src/lib/CMakeDeps.cmake +++ b/src/lib/CMakeDeps.cmake @@ -1 +1 @@ -set(sources api/apicore.proto;api/apigateway.proto;api/apioptions.proto;api/core/ApiClientInterop.cpp;api/core/ApiServerInterop.cpp;api/public/ApiServer.cpp;api/public/ClientChannel.cpp;api/public/QuickbusClientChannel.cpp;api/public/ServerChannel.cpp;api/public/ServiceContext.cpp;api/service_helpers/AdminServiceUtils.cpp;api/services/AdminService.proto;api/services/ApiUnitTestService.proto;api/services/ErrorReportService.proto;api/services/HelloService.proto;api/services/MarketDataRelay.proto;api/services/OrderService.proto;api/services/OutOfProcessURLListener.proto;api/services/PersistenceService.proto;api/services/ShellDiagnosticService.proto;api/services/ShellLatencyService.proto;api/services/SyntheticSecurityService.proto;api/services/UserService.proto;api/test/ApiTests.cpp;api/test/HelloServiceServer.cpp;config/ConfigCheck.cpp;config/ConfigDownloader.cpp;config/ConfigErrorCollector.cpp;config/ConfigLog.cpp;config/ConfigPropertyEvaluator.cpp;config/ConfigValueQueue.cpp;config/ConfigurationException.cpp;config/ConfigurationState.cpp;config/PreprocessInputStream.cpp;config/config.cpp;config/defaults/Executor.conf;config/defaults/MarketData.conf;config/defaults/Ports.conf;config/defaults/Symbols.conf;config/defaults/edge.conf;config/defaults/expiration_display_offset.conf;config/defaults/jetfix.conf;config/defaults/logging.conf;config/defaults/testkeys.conf;config/defaults/toggles.conf;config/extensions/extensions.proto;config/invalid/invalid.proto;config/protos/ExchangeSimCfg.proto;config/protos/MarketData.proto;config/protos/Ports.proto;config/protos/Symbols.proto;config/protos/UI.proto;config/protos/environment.proto;config/protos/expiration_display_offset.proto;config/protos/jetfix.proto;config/protos/logging.proto;config/protos/quickbus_cfg.proto;config/protos/system.proto;config/protos/testkeys.proto;config/protos/toggles.proto;config/tests/HTTPServer.cpp;config/tests/config_ref_tests.cpp;config/tests/config_tests.cpp;config/text_format/text_format.cpp;domain_model/Security.cpp;domain_model/Security.proto;domain_model/SecurityTests.cpp;expression/BooleanGrammar.cpp;expression/ExpressionEvaluator.cpp;expression/ParserExceptions.cpp;expression/Value.cpp;expression/tests/expression_parser_tests.cpp;logging/LoggerHub.cpp;logging/Sink.cpp;logging/logging.cpp;logging/tests/logging_tests.cpp;md/Diag/MDPriceLantencyTester.cpp;md/Diag/ShmDumper.cpp;md/MDConsumer.cpp;md/MDConsumerHandle.cpp;md/MDConsumerInterop.cpp;md/MDProducer.cpp;md/MDProducerHandle.cpp;md/MDRecoverableConsumer.cpp;md/MemorySegmentUtils.cpp;md/PlatformLoader.cpp;md/PriceSize.cpp;md/SecurityDB.cpp;md/SecurityIDRecorder.cpp;md/SettlementRecorder.cpp;md/Shm/FixedSecurity.cpp;md/SyntheticSecurityService.cpp;md/common.cpp;md/protos/co2.proto;md/relay/QueryServer.cpp;md/relay/RelayClient.cpp;md/relay/RelayRecorder.cpp;md/test/Co2TestInstrument.cpp;md/test/md2_tests.cpp;md/test/synthetic_book_merge_tests.cpp;os/os.cpp;os/tests/os_tests.cpp;quickbus/core/LocalNode.cpp;quickbus/core/Quickbus.cpp;quickbus/core/SubscriptionID.cpp;quickbus/core/TableID.cpp;quickbus/message_model/Update.cpp;quickbus/message_model/merge_updates.cpp;quickbus/network/QBConnection.cpp;quickbus/network/QBConnectionManager.cpp;quickbus/network/endpoint_description.cpp;quickbus/network/quickbus_msgs.proto;quickbus/pubsub/TablePublisher.cpp;quickbus/pubsub/TableSubscriber.cpp;quickbus/pubsub/tests/qb_pubsub_tests.cpp;quickbus/routing/INode.cpp;quickbus/routing/NodeID.cpp;quickbus/routing/Router.cpp;quickbus/rpc/RPCClient.cpp;quickbus/rpc/RPCServer.cpp;quickbus/rpc/RPCSessionID.cpp;quickbus/rpc/rpc_utils.cpp;quickbus/rpc/tests/qb_rpc_tests.cpp;quickbus/tests/quickbus_tests.cpp;sparkproto/SparkProtos.proto;testing/catch_test_runner.cpp;utils/Dispatcher.cpp;utils/HTTPStream.cpp;utils/PBUtils.cpp;utils/Puid.cpp;utils/SecureLogon.cpp;utils/SharedMemory.cpp;utils/Sqlite_utils.cpp;utils/Uuid.cpp;utils/datetime.cpp;utils/download.cpp;utils/file_utils.cpp;utils/init_spark_lib.cpp;utils/is_unittest_environment.cpp) \ No newline at end of file +set(sources api/apicore.proto;api/apigateway.proto;api/apioptions.proto;api/core/ApiClientInterop.cpp;api/core/ApiServerInterop.cpp;api/public/ApiServer.cpp;api/public/ClientChannel.cpp;api/public/QuickbusClientChannel.cpp;api/public/ServerChannel.cpp;api/public/ServiceContext.cpp;api/service_helpers/AdminServiceUtils.cpp;api/services/AdminService.proto;api/services/ApiUnitTestService.proto;api/services/ErrorReportService.proto;api/services/HelloService.proto;api/services/MarketDataRelay.proto;api/services/OrderService.proto;api/services/OutOfProcessURLListener.proto;api/services/PersistenceService.proto;api/services/ShellDiagnosticService.proto;api/services/ShellLatencyService.proto;api/services/SyntheticSecurityService.proto;api/services/UserService.proto;api/test/ApiTests.cpp;api/test/HelloServiceServer.cpp;config/ConfigCheck.cpp;config/ConfigDownloader.cpp;config/ConfigErrorCollector.cpp;config/ConfigLog.cpp;config/ConfigPropertyEvaluator.cpp;config/ConfigValueQueue.cpp;config/ConfigurationException.cpp;config/ConfigurationState.cpp;config/PreprocessInputStream.cpp;config/config.cpp;config/defaults/Executor.conf;config/defaults/MarketData.conf;config/defaults/Ports.conf;config/defaults/Symbols.conf;config/defaults/cpp_config.conf;config/defaults/edge.conf;config/defaults/expiration_display_offset.conf;config/defaults/jetfix.conf;config/defaults/logging.conf;config/defaults/testkeys.conf;config/defaults/toggles.conf;config/extensions/extensions.proto;config/invalid/invalid.proto;config/protos/ExchangeSimCfg.proto;config/protos/MarketData.proto;config/protos/Ports.proto;config/protos/Symbols.proto;config/protos/UI.proto;config/protos/cpp_config.proto;config/protos/environment.proto;config/protos/expiration_display_offset.proto;config/protos/jetfix.proto;config/protos/logging.proto;config/protos/quickbus_cfg.proto;config/protos/system.proto;config/protos/testkeys.proto;config/protos/toggles.proto;config/tests/HTTPServer.cpp;config/tests/config_ref_tests.cpp;config/tests/config_tests.cpp;config/text_format/text_format.cpp;domain_model/Security.cpp;domain_model/Security.proto;domain_model/SecurityTests.cpp;expression/BooleanGrammar.cpp;expression/ExpressionEvaluator.cpp;expression/ParserExceptions.cpp;expression/Value.cpp;expression/tests/expression_parser_tests.cpp;logging/LoggerHub.cpp;logging/Sink.cpp;logging/logging.cpp;logging/tests/logging_tests.cpp;md/Diag/MDPriceLantencyTester.cpp;md/Diag/ShmDumper.cpp;md/MDConsumer.cpp;md/MDConsumerHandle.cpp;md/MDConsumerInterop.cpp;md/MDProducer.cpp;md/MDProducerHandle.cpp;md/MDRecoverableConsumer.cpp;md/MemorySegmentUtils.cpp;md/PlatformLoader.cpp;md/PriceSize.cpp;md/SecurityDB.cpp;md/SecurityIDRecorder.cpp;md/SettlementRecorder.cpp;md/Shm/FixedSecurity.cpp;md/SyntheticSecurityService.cpp;md/common.cpp;md/protos/co2.proto;md/relay/QueryServer.cpp;md/relay/RelayClient.cpp;md/relay/RelayRecorder.cpp;md/test/Co2TestInstrument.cpp;md/test/md2_tests.cpp;md/test/synthetic_book_merge_tests.cpp;os/os.cpp;os/tests/os_tests.cpp;quickbus/core/LocalNode.cpp;quickbus/core/Quickbus.cpp;quickbus/core/SubscriptionID.cpp;quickbus/core/TableID.cpp;quickbus/message_model/Update.cpp;quickbus/message_model/merge_updates.cpp;quickbus/network/QBConnection.cpp;quickbus/network/QBConnectionManager.cpp;quickbus/network/endpoint_description.cpp;quickbus/network/quickbus_msgs.proto;quickbus/pubsub/TablePublisher.cpp;quickbus/pubsub/TableSubscriber.cpp;quickbus/pubsub/tests/qb_pubsub_tests.cpp;quickbus/routing/INode.cpp;quickbus/routing/NodeID.cpp;quickbus/routing/Router.cpp;quickbus/rpc/RPCClient.cpp;quickbus/rpc/RPCServer.cpp;quickbus/rpc/RPCSessionID.cpp;quickbus/rpc/rpc_utils.cpp;quickbus/rpc/tests/qb_rpc_tests.cpp;quickbus/tests/quickbus_tests.cpp;sparkproto/SparkProtos.proto;testing/catch_test_runner.cpp;utils/Dispatcher.cpp;utils/HTTPStream.cpp;utils/PBUtils.cpp;utils/Puid.cpp;utils/SecureLogon.cpp;utils/SharedMemory.cpp;utils/Sqlite_utils.cpp;utils/Uuid.cpp;utils/datetime.cpp;utils/download.cpp;utils/file_utils.cpp;utils/init_spark_lib.cpp;utils/is_unittest_environment.cpp) \ No newline at end of file From bd2e2674bf3a7805c899f5b9b64438fdddba29a6 Mon Sep 17 00:00:00 2001 From: Jake Norbut Date: Mon, 16 Jul 2018 13:09:02 -0500 Subject: [PATCH 10/15] PR suggestion --- src/client/spark/view/Spark/PAndL/PAndLVM.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/client/spark/view/Spark/PAndL/PAndLVM.cs b/src/client/spark/view/Spark/PAndL/PAndLVM.cs index f1ff1b131..8ba4b505c 100644 --- a/src/client/spark/view/Spark/PAndL/PAndLVM.cs +++ b/src/client/spark/view/Spark/PAndL/PAndLVM.cs @@ -44,7 +44,8 @@ namespace mbts.spark { pnl_view = CollectionViewSource.GetDefaultView(_pnl_data); // restore filter state - if (startup_data?.filters is FilterStates fs) { + var fs = startup_data?.filters; + if (startup_data != null) { account_filter.load_state(fs.account_regex); exchange_string_filter.load_state(fs.exchange_regex); symbol_filter.load_state(fs.symbol_regex); From c6be4dad17820567ab32b73544d7eb021b749e30 Mon Sep 17 00:00:00 2001 From: John Colvin Date: Mon, 16 Jul 2018 14:19:43 -0400 Subject: [PATCH 11/15] Exchange Ticks - truncate display-digits --- .../core/GlobalExtensions/TickExtensions.cs | 13 ++++++--- .../Converters/TickFactorsTextConverter.cs | 2 +- src/client/spark/view/Spark/Core/TickUtils.cs | 29 ++++++++++++++----- 3 files changed, 31 insertions(+), 13 deletions(-) diff --git a/src/client/spark/core/GlobalExtensions/TickExtensions.cs b/src/client/spark/core/GlobalExtensions/TickExtensions.cs index b1b0cc305..e04493d15 100644 --- a/src/client/spark/core/GlobalExtensions/TickExtensions.cs +++ b/src/client/spark/core/GlobalExtensions/TickExtensions.cs @@ -176,9 +176,10 @@ namespace mbts { if (DoubleHelper.IsNaNOrInfinity(input)) return input; return input <= regional_tick.low_tick_inclusive_end ? regional_tick.low_tick.round(input) : regional_tick.high_tick.round(input); } + public static int display_digits(this TickFactors tick) => display_digits(tick.tick_base); #endregion - public static int n_display_digits(double tick_base) { + public static int display_digits(double tick_base) { double log_tick_base = Math.Log10(tick_base); int floor = (int)Math.Floor(log_tick_base); double dec = log_tick_base - floor; @@ -216,7 +217,7 @@ namespace mbts { if (numerator_part >= tick_base) numerator_part /= Math.Pow(10, Math.Ceiling(Math.Log10(numerator_part) - Math.Log10(tick_base))); else { //e.g [tick_base 640] 1989-8 == 1989-80, or 1989-32 == 1989-320 - int ndd_diff = n_display_digits(tick_base) - numerator_text.Length; + int ndd_diff = display_digits(tick_base) - numerator_text.Length; if (ndd_diff > 0) numerator_part *= Math.Pow(10, ndd_diff); if (numerator_part >= tick_base) numerator_part /= 10; } @@ -255,14 +256,18 @@ namespace mbts { double numerator_dec = value - integer_part; double unit_frac = tick.tick_unit / tick.tick_base; int n_units = (int)Math.Round(numerator_dec / unit_frac); - if (n_units == tick.tick_base) return (integer_part + 1).ToString() + tick.separator() + new string('0', n_display_digits(tick.tick_base)); + if (n_units == tick.tick_base) return (integer_part + 1).ToString() + tick.separator() + new string('0', display_digits(tick.tick_base)); double decimal_part = n_units * tick.tick_unit; if (decimal_part == tick.tick_base) { ++integer_part; decimal_part = 0; + } else { + // some ticks are not formatted with 100% precision, using less than the required display_digits + // for such cases, we need to truncate the decimal part rather than round it. + decimal_part = Math.Floor(decimal_part); } string integer_part_text = show_commas ? integer_part.ToString("#,0") : integer_part.ToString(); - return integer_part_text + tick.separator() + decimal_part.ToString(new string('0', n_display_digits(tick.tick_base))); + return integer_part_text + tick.separator() + decimal_part.ToString(new string('0', display_digits(tick.tick_base))); } } catch (OverflowException ex) { Logger.warn(bts.log.Subsystem.Ui, $"Arithmetic overflow exception in format_tick (tick:{tick}, value:{value}):{ex}"); diff --git a/src/client/spark/view/Converters/TickFactorsTextConverter.cs b/src/client/spark/view/Converters/TickFactorsTextConverter.cs index eddc36f3f..3e0eb72f2 100644 --- a/src/client/spark/view/Converters/TickFactorsTextConverter.cs +++ b/src/client/spark/view/Converters/TickFactorsTextConverter.cs @@ -7,7 +7,7 @@ namespace mbts.ui.converters { class TickFactorsTextConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (value is TickFactors tf) { - int n_digits = TickExtensions.n_display_digits(tf.tick_base); + int n_digits = tf.display_digits(); if (n_digits > 1) { string n_digits_format = new string('0', n_digits); string format = "{0:" + n_digits_format + "}/{1}"; diff --git a/src/client/spark/view/Spark/Core/TickUtils.cs b/src/client/spark/view/Spark/Core/TickUtils.cs index 22498d531..ebf1cb55e 100644 --- a/src/client/spark/view/Spark/Core/TickUtils.cs +++ b/src/client/spark/view/Spark/Core/TickUtils.cs @@ -148,16 +148,12 @@ namespace mbts.spark { // indicates tick is a decimal tick_base = 100; } - int inherrent_display_digits = (int)Math.Ceiling(Math.Log10(tick_base)); - int display_digit_diff = (int)key.display_digits - inherrent_display_digits; - if (display_digit_diff > 0) - tick_base *= Math.Pow(10, display_digit_diff); - return _create_rtf(key.low_tick, key.high_tick, key.price_break, tick_base); + return _create_rtf(key.low_tick, key.high_tick, key.price_break, tick_base, key.display_digits); } - static RegionalTickFactors _create_rtf(double low_tick, double high_tick, double price_break, double reduced_target_base) { - var low_tf = _try_create_tf(low_tick, reduced_target_base); - var high_tf = _try_create_tf(high_tick, reduced_target_base); + static RegionalTickFactors _create_rtf(double low_tick, double high_tick, double price_break, double reduced_target_base, uint display_digits_override) { + var low_tf = _try_create_tf(low_tick, reduced_target_base, display_digits_override); + var high_tf = _try_create_tf(high_tick, reduced_target_base, display_digits_override); if (low_tf == null) { low_tf = high_tf ?? (high_tf = _default_rtf.low_tick); } else if (high_tf == null) @@ -174,6 +170,23 @@ namespace mbts.spark { return new RegionalTickFactors(low_tf, high_tf, price_break); } + /// + /// Creates TickFactors with a base equal to " * 10^n," where 'n' is a natural number (including 0). + /// Note: If is non-zero, 'n' will be " - Math.Ceiling(Log10())" + /// + /// The raw tick-size. + /// The raw tick-base. + /// Well-defined TickFactors + static TickFactors _try_create_tf(double tick_size, double tick_base, uint display_digits_override) { + var tf = _try_create_tf(tick_size, tick_base); + if (tf != null && display_digits_override > 0) { + int display_digit_diff = (int)display_digits_override - tf.display_digits(); + if (display_digit_diff != 0) + tf = _inflate_to_base(tf, tf.tick_base * Math.Pow(10, display_digit_diff)); + } + return tf; + } + /// /// Creates TickFactors with a base equal to "reduced_target_base * 10^n," where 'n' is a natural number (including 0). /// From 9c6993d70cb744734268da21475b08a6d970151d Mon Sep 17 00:00:00 2001 From: John Colvin Date: Mon, 16 Jul 2018 14:32:20 -0400 Subject: [PATCH 12/15] Exchange Ticks - pr edits --- src/client/spark/view/Controls/PriceEntryControl.xaml.cs | 6 +++--- src/client/spark/view/Spark/Core/TickUtils.cs | 8 ++++---- src/client/spark/view/Spark/Utilities/MathUtils.cs | 6 +++--- 3 files changed, 10 insertions(+), 10 deletions(-) diff --git a/src/client/spark/view/Controls/PriceEntryControl.xaml.cs b/src/client/spark/view/Controls/PriceEntryControl.xaml.cs index 270fcb327..44edd0ac6 100644 --- a/src/client/spark/view/Controls/PriceEntryControl.xaml.cs +++ b/src/client/spark/view/Controls/PriceEntryControl.xaml.cs @@ -91,13 +91,13 @@ namespace mbts.ui.spark { void _update_text_binding() { if (_text != null) { - var spec = Security; - if (spec != null) { + var sec = Security; + if (sec != null) { var be = _text.GetBindingExpression(TextBox.TextProperty); if (be != null) { var converter = be.ParentBinding.Converter as TickDisplayTwoWayConverter; if (converter != null) { - converter.Security = spec; + converter.Security = sec; be.UpdateTarget(); } } diff --git a/src/client/spark/view/Spark/Core/TickUtils.cs b/src/client/spark/view/Spark/Core/TickUtils.cs index ebf1cb55e..f0f3b879f 100644 --- a/src/client/spark/view/Spark/Core/TickUtils.cs +++ b/src/client/spark/view/Spark/Core/TickUtils.cs @@ -222,22 +222,22 @@ namespace mbts.spark { return kv.Value.high_tick; } else if (kv.Key.low_tick == tick_size) { return kv.Value.low_tick; - } else if (is_match(kv.Key.high_tick)) { + } else if (is_better_match(kv.Key.high_tick)) { matched_unit = kv.Key.high_tick; matched_tf = kv.Value.high_tick; - } else if (is_match(kv.Key.low_tick)) { + } else if (is_better_match(kv.Key.low_tick)) { matched_unit = kv.Key.low_tick; matched_tf = kv.Value.low_tick; } } return matched_tf ?? new TickFactors(1.0 / tick_size, 1); - bool is_match(double known_unit) => + bool is_better_match(double known_unit) => known_unit < tick_size && known_unit > matched_unit && tick_size % known_unit == 0; } static bool _check_tick_size(double tick_size) => - tick_size > 0 && tick_size < 0.5; + tick_size > 0 && tick_size <= 0.5; static TickFactors _inflate_to_base(TickFactors tick_factors, double new_base) => new TickFactors(new_base, tick_factors.tick_unit * new_base / tick_factors.tick_base); diff --git a/src/client/spark/view/Spark/Utilities/MathUtils.cs b/src/client/spark/view/Spark/Utilities/MathUtils.cs index 83cf83dbe..45dd61e02 100644 --- a/src/client/spark/view/Spark/Utilities/MathUtils.cs +++ b/src/client/spark/view/Spark/Utilities/MathUtils.cs @@ -73,12 +73,12 @@ namespace mbts.spark.utilities { public static double factor_out(double value, double factor) => factor_out(value, factor, out int _); - public static double factor_out(double value, double factor, out int log10_reduction) { - log10_reduction = 0; + public static double factor_out(double value, double factor, out int n_factors_removed) { + n_factors_removed = 0; double quotient = value / factor; while (is_int(quotient)) { value = quotient; - ++log10_reduction; + ++n_factors_removed; quotient /= factor; } return value; From 47730bd3d40e65461a6961dc964c2197f0d06582 Mon Sep 17 00:00:00 2001 From: Eric Harding Date: Mon, 16 Jul 2018 21:59:55 -0400 Subject: [PATCH 13/15] Make cmake happy --- src/lib/CMakeDeps.cmake | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/lib/CMakeDeps.cmake b/src/lib/CMakeDeps.cmake index 5e1985320..fc06362b7 100644 --- a/src/lib/CMakeDeps.cmake +++ b/src/lib/CMakeDeps.cmake @@ -1 +1 @@ -set(sources api/apicore.proto;api/apigateway.proto;api/apioptions.proto;api/core/ApiClientInterop.cpp;api/core/ApiServerInterop.cpp;api/public/ApiServer.cpp;api/public/ClientChannel.cpp;api/public/QuickbusClientChannel.cpp;api/public/ServerChannel.cpp;api/public/ServiceContext.cpp;api/service_helpers/AdminServiceUtils.cpp;api/services/AdminService.proto;api/services/ApiUnitTestService.proto;api/services/ErrorReportService.proto;api/services/HelloService.proto;api/services/MarketDataRelay.proto;api/services/OrderService.proto;api/services/OutOfProcessURLListener.proto;api/services/PersistenceService.proto;api/services/ShellDiagnosticService.proto;api/services/ShellLatencyService.proto;api/services/SyntheticSecurityService.proto;api/services/UserService.proto;api/test/ApiTests.cpp;api/test/HelloServiceServer.cpp;config/ConfigCheck.cpp;config/ConfigDownloader.cpp;config/ConfigErrorCollector.cpp;config/ConfigLog.cpp;config/ConfigPropertyEvaluator.cpp;config/ConfigValueQueue.cpp;config/ConfigurationException.cpp;config/ConfigurationState.cpp;config/PreprocessInputStream.cpp;config/config.cpp;config/defaults/Executor.conf;config/defaults/MarketData.conf;config/defaults/Ports.conf;config/defaults/Symbols.conf;config/defaults/edge.conf;config/defaults/expiration_display_offset.conf;config/defaults/jetfix.conf;config/defaults/logging.conf;config/defaults/testkeys.conf;config/defaults/toggles.conf;config/extensions/extensions.proto;config/invalid/invalid.proto;config/protos/ExchangeSimCfg.proto;config/protos/MarketData.proto;config/protos/Ports.proto;config/protos/Symbols.proto;config/protos/UI.proto;config/protos/environment.proto;config/protos/expiration_display_offset.proto;config/protos/jetfix.proto;config/protos/logging.proto;config/protos/quickbus_cfg.proto;config/protos/system.proto;config/protos/testkeys.proto;config/protos/toggles.proto;config/tests/HTTPServer.cpp;config/tests/config_ref_tests.cpp;config/tests/config_tests.cpp;config/text_format/text_format.cpp;domain_model/Security.cpp;domain_model/Security.proto;domain_model/SecurityTests.cpp;expression/BooleanGrammar.cpp;expression/ExpressionEvaluator.cpp;expression/ParserExceptions.cpp;expression/Value.cpp;expression/tests/expression_parser_tests.cpp;logging/LoggerHub.cpp;logging/Sink.cpp;logging/logging.cpp;logging/tests/logging_tests.cpp;md/Diag/MDPriceLantencyTester.cpp;md/Diag/ShmDumper.cpp;md/MDConsumer.cpp;md/MDConsumerHandle.cpp;md/MDConsumerInterop.cpp;md/MDProducer.cpp;md/MDProducerHandle.cpp;md/MDRecoverableConsumer.cpp;md/MemorySegmentUtils.cpp;md/PlatformLoader.cpp;md/PriceSize.cpp;md/SecurityDB.cpp;md/SecurityIDRecorder.cpp;md/SettlementRecorder.cpp;md/Shm/FixedSecurity.cpp;md/SyntheticSecurityService.cpp;md/common.cpp;md/protos/co2.proto;md/relay/QueryServer.cpp;md/relay/RelayClient.cpp;md/relay/RelayRecorder.cpp;md/test/Co2TestInstrument.cpp;md/test/md2_tests.cpp;md/test/synthetic_book_merge_tests.cpp;os/os.cpp;os/tests/os_tests.cpp;quickbus/core/LocalNode.cpp;quickbus/core/Quickbus.cpp;quickbus/core/SubscriptionID.cpp;quickbus/core/TableID.cpp;quickbus/message_model/Update.cpp;quickbus/message_model/merge_updates.cpp;quickbus/network/QBConnection.cpp;quickbus/network/QBConnectionManager.cpp;quickbus/network/endpoint_description.cpp;quickbus/network/quickbus_msgs.proto;quickbus/pubsub/TablePublisher.cpp;quickbus/pubsub/TableSubscriber.cpp;quickbus/pubsub/tests/qb_pubsub_tests.cpp;quickbus/routing/INode.cpp;quickbus/routing/NodeID.cpp;quickbus/routing/Router.cpp;quickbus/rpc/RPCClient.cpp;quickbus/rpc/RPCServer.cpp;quickbus/rpc/RPCSessionID.cpp;quickbus/rpc/rpc_utils.cpp;quickbus/rpc/tests/qb_rpc_tests.cpp;quickbus/tests/quickbus_tests.cpp;sparkproto/SparkProtos.proto;testing/catch_test_runner.cpp;utils/Dispatcher.cpp;utils/HTTPStream.cpp;utils/PBUtils.cpp;utils/Puid.cpp;utils/SecureLogon.cpp;utils/SharedMemory.cpp;utils/Sqlite_utils.cpp;utils/Uuid.cpp;utils/datetime.cpp;utils/download.cpp;utils/file_utils.cpp;utils/init_spark_lib.cpp;utils/is_unittest_environment.cpp) \ No newline at end of file +set(sources api/apicore.proto;api/apigateway.proto;api/apioptions.proto;api/core/ApiClientInterop.cpp;api/core/ApiServerInterop.cpp;api/public/ApiServer.cpp;api/public/ClientChannel.cpp;api/public/QuickbusClientChannel.cpp;api/public/ServerChannel.cpp;api/public/ServiceContext.cpp;api/service_helpers/AdminServiceUtils.cpp;api/services/AdminService.proto;api/services/ApiUnitTestService.proto;api/services/ErrorReportService.proto;api/services/HelloService.proto;api/services/MarketDataRelay.proto;api/services/OrderService.proto;api/services/OutOfProcessURLListener.proto;api/services/PersistenceService.proto;api/services/ShellDiagnosticService.proto;api/services/ShellLatencyService.proto;api/services/SyntheticSecurityService.proto;api/services/UserService.proto;api/test/ApiTests.cpp;api/test/HelloServiceServer.cpp;config/ConfigCheck.cpp;config/ConfigDownloader.cpp;config/ConfigErrorCollector.cpp;config/ConfigLog.cpp;config/ConfigPropertyEvaluator.cpp;config/ConfigValueQueue.cpp;config/ConfigurationException.cpp;config/ConfigurationState.cpp;config/PreprocessInputStream.cpp;config/config.cpp;config/defaults/Executor.conf;config/defaults/MarketData.conf;config/defaults/Ports.conf;config/defaults/Symbols.conf;config/defaults/cpp_config.conf;config/defaults/edge.conf;config/defaults/expiration_display_offset.conf;config/defaults/jetfix.conf;config/defaults/logging.conf;config/defaults/testkeys.conf;config/defaults/toggles.conf;config/extensions/extensions.proto;config/invalid/invalid.proto;config/protos/ExchangeSimCfg.proto;config/protos/MarketData.proto;config/protos/Ports.proto;config/protos/Symbols.proto;config/protos/UI.proto;config/protos/cpp_config.proto;config/protos/environment.proto;config/protos/expiration_display_offset.proto;config/protos/jetfix.proto;config/protos/logging.proto;config/protos/quickbus_cfg.proto;config/protos/system.proto;config/protos/testkeys.proto;config/protos/toggles.proto;config/tests/HTTPServer.cpp;config/tests/config_ref_tests.cpp;config/tests/config_tests.cpp;config/text_format/text_format.cpp;domain_model/Security.cpp;domain_model/Security.proto;domain_model/SecurityTests.cpp;expression/BooleanGrammar.cpp;expression/ExpressionEvaluator.cpp;expression/ParserExceptions.cpp;expression/Value.cpp;expression/tests/expression_parser_tests.cpp;logging/LoggerHub.cpp;logging/Sink.cpp;logging/logging.cpp;logging/tests/logging_tests.cpp;md/Diag/MDPriceLantencyTester.cpp;md/Diag/ShmDumper.cpp;md/MDConsumer.cpp;md/MDConsumerHandle.cpp;md/MDConsumerInterop.cpp;md/MDProducer.cpp;md/MDProducerHandle.cpp;md/MDRecoverableConsumer.cpp;md/MemorySegmentUtils.cpp;md/PlatformLoader.cpp;md/PriceSize.cpp;md/SecurityDB.cpp;md/SecurityIDRecorder.cpp;md/SettlementRecorder.cpp;md/Shm/FixedSecurity.cpp;md/SyntheticSecurityService.cpp;md/common.cpp;md/protos/co2.proto;md/relay/QueryServer.cpp;md/relay/RelayClient.cpp;md/relay/RelayRecorder.cpp;md/test/Co2TestInstrument.cpp;md/test/md2_tests.cpp;md/test/synthetic_book_merge_tests.cpp;os/os.cpp;os/tests/os_tests.cpp;quickbus/core/LocalNode.cpp;quickbus/core/Quickbus.cpp;quickbus/core/SubscriptionID.cpp;quickbus/core/TableID.cpp;quickbus/message_model/Update.cpp;quickbus/message_model/merge_updates.cpp;quickbus/network/QBConnection.cpp;quickbus/network/QBConnectionManager.cpp;quickbus/network/endpoint_description.cpp;quickbus/network/quickbus_msgs.proto;quickbus/pubsub/TablePublisher.cpp;quickbus/pubsub/TableSubscriber.cpp;quickbus/pubsub/tests/qb_pubsub_tests.cpp;quickbus/routing/INode.cpp;quickbus/routing/NodeID.cpp;quickbus/routing/Router.cpp;quickbus/rpc/RPCClient.cpp;quickbus/rpc/RPCServer.cpp;quickbus/rpc/RPCSessionID.cpp;quickbus/rpc/rpc_utils.cpp;quickbus/rpc/tests/qb_rpc_tests.cpp;quickbus/tests/quickbus_tests.cpp;sparkproto/SparkProtos.proto;testing/catch_test_runner.cpp;utils/Dispatcher.cpp;utils/HTTPStream.cpp;utils/PBUtils.cpp;utils/Puid.cpp;utils/SecureLogon.cpp;utils/SharedMemory.cpp;utils/Sqlite_utils.cpp;utils/Uuid.cpp;utils/datetime.cpp;utils/download.cpp;utils/file_utils.cpp;utils/init_spark_lib.cpp;utils/is_unittest_environment.cpp) \ No newline at end of file From 7403057c5815e5279016fb2e54a6d76cb2e943a3 Mon Sep 17 00:00:00 2001 From: Eric Harding Date: Mon, 16 Jul 2018 22:02:45 -0400 Subject: [PATCH 14/15] Threading tweak to ShellDiagnosticService --- .../ShellDiagnosticsServiceServer.cs | 82 ++++++++++++------- 1 file changed, 54 insertions(+), 28 deletions(-) diff --git a/src/client/spark/core/Diagnostics/ShellDiagnosticsServiceServer.cs b/src/client/spark/core/Diagnostics/ShellDiagnosticsServiceServer.cs index 01a98bfcc..6a846fe87 100644 --- a/src/client/spark/core/Diagnostics/ShellDiagnosticsServiceServer.cs +++ b/src/client/spark/core/Diagnostics/ShellDiagnosticsServiceServer.cs @@ -6,6 +6,7 @@ using System.Reflection; using System.Text; using System.Threading; using System.Threading.Tasks; +using System.Windows.Threading; using bts.api.core; using IronPython.Runtime.Types; using mbts; @@ -49,6 +50,9 @@ namespace bts.api.diagnostic { readonly StringBuilder _pending = new StringBuilder(); readonly OutputPublisher _out; + readonly Thread _thread; + Dispatcher _dispatcher; + public ShellScriptServer(ServiceContext context, ShellDiagnosticsServiceServer parent, string qualifier) : base(context, qualifier) { _parent = parent; _out = make_output_publisher(); @@ -59,11 +63,19 @@ namespace bts.api.diagnostic { _scope.SetVariable("shell_objects", new Func(o => get_exports(o,null))); _scope.SetVariable("shell_named_object", new Func(get_export)); _scope.SetVariable("shell_named_objects", new Func(get_exports)); + + _thread = new Thread(_ => { + _dispatcher = Dispatcher.CurrentDispatcher; + Thread.CurrentThread.Name = $"ShellScriptServer-{qualifier}"; + Dispatcher.Run(); + }); } + public override Task dispose(VoidMessage request) { log("Finished", true); _parent.terminate(this); + _dispatcher.BeginInvokeShutdown(DispatcherPriority.ApplicationIdle); return Task.FromResult(new VoidMessage()); } @@ -124,44 +136,58 @@ namespace bts.api.diagnostic { }); } - Task run_code(ScriptSource code) { + ScriptResultMessage run_code(ScriptSource code) { try { object result = code.Execute(_scope); - return Task.FromResult(new ScriptResultMessage { Res = ScriptResult.Complete, Message = (result?.ToString()) ?? "" }); + return new ScriptResultMessage { Res = ScriptResult.Complete, Message = (result?.ToString()) ?? "" }; } catch (Exception e) { //log($"Exception: {e.Message}"); - return Task.FromResult(new ScriptResultMessage { Res = ScriptResult.RunError, Message = e.Message }); + return (new ScriptResultMessage { Res = ScriptResult.RunError, Message = e.Message }); } } public override Task run(ScriptLines request) { - // append lines to _pending - foreach (var line in request.Lines) { - _pending.AppendLine(line); - } - // CreateScriptSource from pending - var code = _engine.CreateScriptSourceFromString(_pending.ToString().TrimStart(' ', '\n', '\r'), SourceCodeKind.InteractiveCode); - var parse_result = code.GetCodeProperties(); - if (parse_result == ScriptCodeParseResult.IncompleteStatement && code.GetCode().EndsWith(Environment.NewLine+Environment.NewLine)) { - parse_result = Microsoft.Scripting.ScriptCodeParseResult.Complete; - } - // todo: If code is 'incomplete' but we have 2 blank lines run it! - switch (parse_result) { - // If 'complete' run code - case ScriptCodeParseResult.Complete: - _pending.Clear(); - return run_code(code); - // if 'invalid' return error - case ScriptCodeParseResult.Invalid: - Console.WriteLine("Invalid"); - _pending.Clear(); - return Task.FromResult(new ScriptResultMessage { Res = ScriptResult.Invalid, Message = code.GetCode() }); - // otherwise continue buffering - default: - Console.WriteLine("Incomplete"); - return Task.FromResult(new ScriptResultMessage { Res = ScriptResult.Incomplete }); + + var tcs = new TaskCompletionSource(); + void ret(ScriptResultMessage r) { + tcs.TrySetResult(r); } + + _dispatcher.BeginInvoke(() => { + + // append lines to _pending + foreach (var line in request.Lines) { + _pending.AppendLine(line); + } + // CreateScriptSource from pending + var code = _engine.CreateScriptSourceFromString(_pending.ToString().TrimStart(' ', '\n', '\r'), SourceCodeKind.InteractiveCode); + var parse_result = code.GetCodeProperties(); + if (parse_result == ScriptCodeParseResult.IncompleteStatement && code.GetCode().EndsWith(Environment.NewLine+Environment.NewLine)) { + parse_result = Microsoft.Scripting.ScriptCodeParseResult.Complete; + } + // todo: If code is 'incomplete' but we have 2 blank lines run it! + switch (parse_result) { + // If 'complete' run code + case ScriptCodeParseResult.Complete: + _pending.Clear(); + ret(run_code(code)); + break; + // if 'invalid' return error + case ScriptCodeParseResult.Invalid: + Console.WriteLine("Invalid"); + _pending.Clear(); + ret(new ScriptResultMessage { Res = ScriptResult.Invalid, Message = code.GetCode() }); + break; + // otherwise continue buffering + default: + Console.WriteLine("Incomplete"); + ret(new ScriptResultMessage { Res = ScriptResult.Incomplete }); + break; + } + }); + + return tcs.Task; } } } From e004580d998f58975030b4c0ee897b6c1204ed33 Mon Sep 17 00:00:00 2001 From: John Colvin Date: Mon, 16 Jul 2018 22:24:26 -0400 Subject: [PATCH 15/15] Exchange Ticks - pr edits --- .../Spreader/ExecutionStrategyEditor.xaml | 4 +- .../Modules/Spreader/VM/SyntheticEditorVM.cs | 12 +- .../core/GlobalExtensions/TickExtensions.cs | 2 + src/client/spark/core/Utility/CompareUtils.cs | 16 +++ .../core/user/settings/ticks/TickFactors.cs | 25 +--- src/client/spark/view/Spark/Core/TickUtils.cs | 114 +++++++++++++++--- 6 files changed, 122 insertions(+), 51 deletions(-) diff --git a/src/client/spark/Modules/Spreader/ExecutionStrategyEditor.xaml b/src/client/spark/Modules/Spreader/ExecutionStrategyEditor.xaml index 07fe26515..6055d5bfe 100644 --- a/src/client/spark/Modules/Spreader/ExecutionStrategyEditor.xaml +++ b/src/client/spark/Modules/Spreader/ExecutionStrategyEditor.xaml @@ -367,7 +367,7 @@ /> @@ -375,7 +375,7 @@ - + diff --git a/src/client/spark/Modules/Spreader/VM/SyntheticEditorVM.cs b/src/client/spark/Modules/Spreader/VM/SyntheticEditorVM.cs index 5c552197e..e9996aa90 100644 --- a/src/client/spark/Modules/Spreader/VM/SyntheticEditorVM.cs +++ b/src/client/spark/Modules/Spreader/VM/SyntheticEditorVM.cs @@ -24,7 +24,7 @@ namespace mbts.spark { /// The view model designed to serve as the DataContext for the SyntheticEditorView /// partial class SyntheticEditorVM : DisposableViewModelBase, IRequestViewClose, IRequestBindingSourceUpdate, IDisposable { - readonly ObservableCollection _available_tick_factors = new ObservableCollection(TickUtils.all_present_ticks().Select(tf => new TickFactorsVM(tf))); + readonly ObservableCollection _available_tick_factors = new ObservableCollection(TickUtils.synthetic_presets); readonly QuantityModel _quantity_model; readonly PriceMultiplierModel _price_mult_model; readonly List _resources = new List(); @@ -122,7 +122,7 @@ namespace mbts.spark { flash_error_msg("Name already taken", SparkUtils.UI.MessageFlashDuration, nameof(name)).ignore(); valid = false; } - if (_tick_factors == null || !_tick_factors.is_valid() || !_available_tick_factors.Any(vm => vm.value.Equals(_tick_factors))) { + if (_tick_factors == null || !_tick_factors.is_valid() || !_available_tick_factors.Contains(_tick_factors)) { flash_error_msg("Please select ticks", SparkUtils.UI.MessageFlashDuration, nameof(tick_factors)).ignore(); valid = false; } @@ -154,8 +154,8 @@ namespace mbts.spark { _set_quantities_automatically = is_new; _set_price_mults_automatically = is_new; available_tick_factors_view = CollectionViewSource.GetDefaultView(_available_tick_factors); - ((ListCollectionView)available_tick_factors_view).CustomSort = Comparer.Default; - available_tick_factors_view.GroupDescriptions.Add(new PropertyGroupDescription(nameof(TickFactorsVM.reduced_base))); + ((ListCollectionView)available_tick_factors_view).CustomSort = TickUtils.CompareUtils.base_unit_comparer.as_non_generic(); + available_tick_factors_view.GroupDescriptions.Add(new PropertyGroupDescription(nameof(TickFactors.tick_base))); _quantity_model = new QuantityModel(!is_new); _price_mult_model = new PriceMultiplierModel(!is_new); @@ -330,8 +330,8 @@ namespace mbts.spark { void _deduce_ticks() { _tick_factors = TickUtils.deduce_ticks(leg_tuples.Select(l => l.leg.Security.ContractSpec)); - if (_tick_factors != null && !_available_tick_factors.Any(vm => vm.value.Equals(tick_factors))) - _available_tick_factors.Add(new TickFactorsVM(_tick_factors)); + if (_tick_factors != null && !_available_tick_factors.Contains(_tick_factors)) + _available_tick_factors.Add(_tick_factors); RaisePropertyChanged(nameof(tick_factors)); } diff --git a/src/client/spark/core/GlobalExtensions/TickExtensions.cs b/src/client/spark/core/GlobalExtensions/TickExtensions.cs index e04493d15..5174402b7 100644 --- a/src/client/spark/core/GlobalExtensions/TickExtensions.cs +++ b/src/client/spark/core/GlobalExtensions/TickExtensions.cs @@ -17,6 +17,8 @@ namespace mbts { public static double tick_unit_frac(this TickFactors tick) => tick.tick_unit / tick.tick_base; + public static double reduced_base(this TickFactors tick) => factor_out(tick.tick_base, 10); + public static string format(this TickFactors tick, double value) => format(tick, value, double.NaN, false, _nan_text); diff --git a/src/client/spark/core/Utility/CompareUtils.cs b/src/client/spark/core/Utility/CompareUtils.cs index 8e714db66..ee081f19f 100644 --- a/src/client/spark/core/Utility/CompareUtils.cs +++ b/src/client/spark/core/Utility/CompareUtils.cs @@ -1,4 +1,6 @@ using System; +using System.Collections; +using System.Collections.Generic; namespace mbts.utils { public static class CompareUtils { @@ -19,5 +21,19 @@ namespace mbts.utils { b.HasValue ? compare(a.Value, b.Value) : 1 : b.HasValue ? -1 : 0; #endregion + + #region Comparer + public static IComparer as_non_generic(this IComparer comparer) => + new NonGenericComparerWrapper(comparer); + + class NonGenericComparerWrapper : IComparer { + readonly IComparer _comparer; + + public NonGenericComparerWrapper(IComparer comparer) => _comparer = comparer; + + public int Compare(object x, object y) => + _comparer.Compare(ObjectHelper.try_convert(x), ObjectHelper.try_convert(y)); + } + #endregion } } \ No newline at end of file diff --git a/src/client/spark/core/user/settings/ticks/TickFactors.cs b/src/client/spark/core/user/settings/ticks/TickFactors.cs index 6514287d4..9d941acc9 100644 --- a/src/client/spark/core/user/settings/ticks/TickFactors.cs +++ b/src/client/spark/core/user/settings/ticks/TickFactors.cs @@ -1,5 +1,4 @@ -using mbts.spark.utilities; -using mbts.ui; +using mbts.ui; using ProtoBuf; using System; using System.ComponentModel; @@ -49,26 +48,4 @@ namespace mbts.user.settings { public static bool operator !=(TickFactors x, TickFactors y) => !(x == y); } - - class TickFactorsVM : IComparable, IEquatable { - public TickFactorsVM(TickFactors value) => - this.value = value; - - public TickFactors value { get; } - public double reduced_base => MathUtils.factor_out(value.tick_base, 10); - - public int CompareTo(TickFactorsVM other) { - int comp = reduced_base.CompareTo(other.reduced_base); - if (comp != 0) - return comp; - comp = value.tick_base.CompareTo(other.value.tick_base); - if (comp != 0) - return comp; - return value.tick_unit.CompareTo(other.value.tick_unit); - } - - public bool Equals(TickFactorsVM other) => value == other?.value; - public override bool Equals(object obj) => Equals(obj as TickFactorsVM); - public override int GetHashCode() => value.GetHashCode(); - } } \ No newline at end of file diff --git a/src/client/spark/view/Spark/Core/TickUtils.cs b/src/client/spark/view/Spark/Core/TickUtils.cs index f0f3b879f..709d1e3af 100644 --- a/src/client/spark/view/Spark/Core/TickUtils.cs +++ b/src/client/spark/view/Spark/Core/TickUtils.cs @@ -6,6 +6,7 @@ using mbts.utils; using System; using System.Collections.Concurrent; using System.Collections.Generic; +using System.Collections.ObjectModel; using System.Linq; namespace mbts.spark { @@ -71,13 +72,13 @@ namespace mbts.spark { return raw_mid - (raw_mid % tick_size); } - public static IReadOnlyList all_present_ticks() => - TickStore.all_present_ticks(); + public static IReadOnlyCollection synthetic_presets => + TickStore.synthetic_presets; public static TickFactors deduce_ticks(IEnumerable contract_specs) { var gcd = MathUtils.GCD(contract_specs.Select(s => s.LowTick)); if (gcd == 0) return null; - return _try_get_tick_factors(gcd); + return TickStore.get_tick_factors(gcd); } public static double tickup(this SecurityImmutable security, double value) => @@ -115,31 +116,106 @@ namespace mbts.spark { public static RegionalTickFactors get_regional_ticks(SecurityImmutable security) => TickStore.get(security); - static TickFactors _try_get_tick_factors(double tick) => - TickStore.get(tick); + public static class CompareUtils { + public static IComparer base_unit_comparer => + Comparer.Create(utils.CompareUtils.safe_comparison(compare_base_unit)); + + public static int compare_base_unit(TickFactors a, TickFactors b) { + int comp = a.reduced_base().CompareTo(b.reduced_base()); + if (comp != 0) + return comp; + comp = a.tick_base.CompareTo(b.tick_base); + if (comp != 0) + return comp; + return a.tick_unit.CompareTo(b.tick_unit); + } + } static class TickStore { static readonly RegionalTickFactors _default_rtf = new RegionalTickFactors(new TickFactors(1000, 1), new TickFactors(1000, 1), double.MaxValue); - static readonly ConcurrentDictionary _known_ticks = new ConcurrentDictionary(); - static readonly ConcurrentDictionary _unit_map = new ConcurrentDictionary(); + static readonly ConcurrentDictionary _exchange_ticks = new ConcurrentDictionary(); - public static RegionalTickFactors get(SecurityImmutable security) => - security.HasGlbx && security.HasContractSpec ? - _known_ticks.GetOrAdd(new SpecKey(security.ContractSpec, security.Glbx), _create_rtf) : _default_rtf; + static readonly ReadOnlyDictionary _synthetic_presets_cache = new[] { + // 100 based + new { tick_unit = 0.01, tick_factors = new TickFactors(100, 1) }, // 1/100 + new { tick_unit = 0.05, tick_factors = new TickFactors(100, 5) }, // 1/20 + new { tick_unit = 0.10, tick_factors = new TickFactors(100, 10) }, // 1/10 + new { tick_unit = 0.25, tick_factors = new TickFactors(100, 25) }, // 1/4 + new { tick_unit = 0.50, tick_factors = new TickFactors(100, 50) }, // 1/2 + // 1,000 based + new { tick_unit = 0.001, tick_factors = new TickFactors(1000, 1) }, // 1/1,000 + new { tick_unit = 0.005, tick_factors = new TickFactors(1000, 5) }, // 1/200 + new { tick_unit = 0.025, tick_factors = new TickFactors(1000, 25) }, // 1/40 + // 10,000 based + new { tick_unit = 0.0001, tick_factors = new TickFactors(10000, 1) }, // 1/10,000 + new { tick_unit = 0.0005, tick_factors = new TickFactors(10000, 5) }, // 1/2,000 + new { tick_unit = 0.0025, tick_factors = new TickFactors(10000, 25) }, // 1/400 + // 64 based + new { tick_unit = 0.015625, tick_factors = new TickFactors(64, 1) }, // 1/64 + new { tick_unit = 0.03125, tick_factors = new TickFactors(64, 2) }, // 1/32 + new { tick_unit = 0.0625, tick_factors = new TickFactors(64, 4) }, // 1/16 + new { tick_unit = 0.125, tick_factors = new TickFactors(64, 8) }, // 1/8 + // 640 based + new { tick_unit = 0.0015625, tick_factors = new TickFactors(640, 1) }, // 1/640 + new { tick_unit = 0.003125, tick_factors = new TickFactors(640, 2) }, // 1/320 + new { tick_unit = 0.00625, tick_factors = new TickFactors(640, 4) }, // 1/160 + new { tick_unit = 0.0078125, tick_factors = new TickFactors(640, 5) }, // 1/128 + new { tick_unit = 0.0125, tick_factors = new TickFactors(640, 8) }, // 1/80 + new { tick_unit = 0.0390625, tick_factors = new TickFactors(640, 25) }, // 5/128 + new { tick_unit = 0.078125, tick_factors = new TickFactors(640, 50) }, // 5/64 + // 6,400 based + new { tick_unit = 0.00015625, tick_factors = new TickFactors(6400, 1) }, // 1/6,400 + new { tick_unit = 0.0003125, tick_factors = new TickFactors(6400, 2) }, // 1/3,200 + new { tick_unit = 0.000625, tick_factors = new TickFactors(6400, 4) }, // 1/1,600 + new { tick_unit = 0.00078125, tick_factors = new TickFactors(6400, 5) }, // 1/1,280 + new { tick_unit = 0.00125, tick_factors = new TickFactors(6400, 8) }, // 1/800 + new { tick_unit = 0.00390625, tick_factors = new TickFactors(6400, 25) }, // 1/256 + // 64,000 based + new { tick_unit = 0.000015625, tick_factors = new TickFactors(64000, 1) }, // 1/6,400 + new { tick_unit = 0.00003125, tick_factors = new TickFactors(64000, 2) }, // 1/3,200 + new { tick_unit = 0.0000625, tick_factors = new TickFactors(64000, 4) }, // 1/1,600 + new { tick_unit = 0.000078125, tick_factors = new TickFactors(64000, 5) }, // 1/12,800 + new { tick_unit = 0.000125, tick_factors = new TickFactors(64000, 8) }, // 1/8,000 + new { tick_unit = 0.000390625, tick_factors = new TickFactors(64000, 25) }, // 1/2,560 + new { tick_unit = 0.001953125, tick_factors = new TickFactors(64000, 125) },// 1/512 + }.ToReadOnlyDictionary(obj => obj.tick_unit, obj => obj.tick_factors, EqualityComparer.Create(MathUtils.epsilon_equals)); + static readonly double[] _descending_synthetic_tick_sizes; + + static TickStore() => + _descending_synthetic_tick_sizes = _synthetic_presets_cache.Select(kv => kv.Key).Ordered(new ReverseComparer(Comparer.Default)).ToArray(); + + public static IReadOnlyCollection synthetic_presets => _synthetic_presets_cache.Values; + + public static RegionalTickFactors get(SecurityImmutable security) { + if (security.HasContractSpec) { + if (security.ContractCase == Security.ContractOneofCase.Synthetic) { + return get(security.ContractSpec.LowTick); + } else if (security.HasGlbx) { + return _exchange_ticks.GetOrAdd(new SpecKey(security.ContractSpec, security.Glbx), _create_rtf); + } + } + return _default_rtf; + } public static RegionalTickFactors get(SecurityImmutable? security) => security.HasValue ? get(security.Value) : _default_rtf; - public static TickFactors get(double unit) => - _unit_map.GetOrAdd(unit, _create_tf); + public static RegionalTickFactors get(double tick_size) { + var tf = get_tick_factors(tick_size); + return new RegionalTickFactors(tf, tf, double.MaxValue); + } - public static IReadOnlyList all_present_ticks() { - var set = new HashSet(); - foreach (var kv in _known_ticks) { - set.Add(kv.Value.low_tick); - set.Add(kv.Value.high_tick); + public static TickFactors get_tick_factors(double tick_size) { + if (_synthetic_presets_cache.TryGetValue(tick_size, out TickFactors result)) + return result; + // try to return the largest known tick that is divisible by this tick + foreach (var tfu in _descending_synthetic_tick_sizes) { + double mod = tick_size % tfu; + if (MathUtils.epsilon_equals(mod, 0)) { + return _synthetic_presets_cache[tfu]; + } } - return set.ToList(); + return new TickFactors(1 / tick_size, tick_size); } static RegionalTickFactors _create_rtf(SpecKey key) { @@ -217,7 +293,7 @@ namespace mbts.spark { return _default_rtf.low_tick; double matched_unit = double.MinValue; TickFactors matched_tf = null; - foreach (var kv in _known_ticks) { + foreach (var kv in _exchange_ticks) { if (kv.Key.high_tick == tick_size) { return kv.Value.high_tick; } else if (kv.Key.low_tick == tick_size) {