diff --git a/externals b/externals index f937c3334..94871c522 160000 --- a/externals +++ b/externals @@ -1 +1 @@ -Subproject commit f937c33349e5d7eeb9fe0445732e62550b8732ef +Subproject commit 94871c522792d906ba2c8343093c3ccb3f41421e diff --git a/src/client/spark/AW2/AnalyticsParameters/AnalyticsExpirationParametersVM.cs b/src/client/spark/AW2/AnalyticsParameters/AnalyticsExpirationParametersVM.cs new file mode 100644 index 000000000..7cc124e47 --- /dev/null +++ b/src/client/spark/AW2/AnalyticsParameters/AnalyticsExpirationParametersVM.cs @@ -0,0 +1,365 @@ +namespace mbts.spark { + using bts.api; + + using mbts; + using mbts.analytics; + using mbts.ui; + using mbts.ui.controls; + using mbts.ui.shell; + using mbts.ui.utility; + using mbts.utils; + + using ProtoBuf; + + using System; + using System.Collections.Generic; + using System.Collections.ObjectModel; + using System.Collections.Specialized; + using System.Linq; + using System.Reactive.Linq; + using System.Runtime.CompilerServices; + using System.Threading.Tasks; + using System.Windows.Input; + + class AnalyticsExpirationParametersVM : DisposableViewModelBase { + readonly IBus _bus; + readonly AnalyticsParametersUIModel _model; + readonly ObservableCollection _parameters = new(); + + bool _auto_copy_rolls_is_checked; + bool _auto_copy_rates_is_checked; + // IRaiseCanExecuteChangedCommand _copy_roll_schedule_to_selection; + // IRaiseCanExecuteChangedCommand _copy_roll_target_to_selection; + // IRaiseCanExecuteChangedCommand _copy_settlement_price_to_selection; + // IRaiseCanExecuteChangedCommand _copy_delta_beta_to_selection; + // IRaiseCanExecuteChangedCommand _copy_vega_beta_to_selection; + // IRaiseCanExecuteChangedCommand _smart_copy_roll_target; + // IRaiseCanExecuteChangedCommand _smart_copy_riskless_rate; + + public AnalyticsExpirationParametersVM(IBus bus, AnalyticsParametersUIModel model, StartupData startup_data) { + _bus = bus ?? throw new ArgumentNullException(nameof(bus)); + _model = model ?? throw new ArgumentNullException(nameof(model)); + non_options_with_empty = new ObservableAggregateCollection( + new() { SecurityExpiration.empty }, non_options); + + if (startup_data != null) { + if (!startup_data.selected_symbols.is_null_or_empty()) { + checked_symbols.AddRange(startup_data.selected_symbols); + } + auto_copy_rolls_is_checked = startup_data.auto_copy_rolls_is_checked; + auto_copy_rates_is_checked = startup_data.auto_copy_rates_is_checked; + } + + + dialog_skirt_items.Add(new DialogSkirtItem("Commit", + new AsyncCommand(async _ => { + var param_map = await _bus.subscribe(SparkTags.ExpirationParametersInputTag) + .StopAfter(TimeSpan.FromSeconds(30)) + .FirstOrDefaultAsync(); + if (param_map != null) { + _model.commit(rows.Select(_from_row)); + } + }))); + + dialog_skirt_items.Add(new DialogSkirtItem("Revert", new DelegateCommand(_ => { + foreach (var r in rows) { + r.revert(); + } + }))); + + checked_symbols.CollectionChanged += _on_checked_symbols_changed; + _model.on_expiration_parameters += sync_params; + + _dispose = Disposable.Create( + ObservableAutoWrapper.connect(_parameters, rows, _to_row, r => r.Dispose()), + Disposable.Create(() => { + checked_symbols.CollectionChanged -= _on_checked_symbols_changed; + _model.on_expiration_parameters -= sync_params; + _parameters.Clear(); + rows.DisposeAll(); + })); + init_async().ignore(); + + async Task init_async() { + var initial_param_map = await _bus.subscribe(SparkTags.ExpirationParametersInputTag).FirstOrDefaultAsync(); + if (initial_param_map != null) { + sync_params(initial_param_map); + } + } + + void sync_params(AnalyticsExpirationParametersMap param_map) { + _parameters.sync_with(param_map.get_sorted_exps().Select(exp => param_map.get_parameter(exp))); + non_options.sync_with(param_map.get_sorted_exps().Where(exp => exp.security_type != SecurityType.Option)); + //this of course assumes rows are sorted by Exp! + rows.GroupBy(r => r.security.expiration.Month).ForEach(exp_group => { + exp_group.ForEach(r => r.is_last_row_of_month_group = false); + exp_group.ElementAt(exp_group.Count() - 1).is_last_row_of_month_group = true; + }); + + List uniq = rows.Select(x => x.security.symbol).Distinct().ToList(); + uniq.Sort(); + // the data source for the MSDD (contiains unique symbol names + // and set the initial selection to all + distinct_symbols.sync_with(uniq); + if (checked_symbols.Count == 0) { + // check all the symbols in the first load + checked_symbols.sync_with(uniq); + // the data source for the DataGrid, filtered according to the selected rows in the MSDD + filtered_for_visible_rows.sync_with(rows); + } else { + // the form has just been commited, but rather than sync_with the original row collection, + // which will reset the grid to all symbols, we need to sync_with the checked symbols again to reset + // the red outline of the cell + filtered_for_visible_rows.sync_with(rows.Where(x => checked_symbols.Contains(x.security.symbol))); + } + } + } + + public ObservableCollection non_options { get; } = new(); + public ObservableCollection non_options_with_empty { get; } = new(); + public ObservableCollection filtered_for_visible_rows { get; } = new(); + public ObservableCollection checked_symbols { get; } = new(); + public ObservableCollection distinct_symbols { get; } = new(); + public ObservableCollection rows { get; } = new(); + public ObservableCollection selected_rows { get; } = new(); + public ObservableCollection dialog_skirt_items { get; } = new(); + + public bool auto_copy_rolls_is_checked { + get => _auto_copy_rolls_is_checked; + set => Set(ref _auto_copy_rolls_is_checked, value); + } + + public bool auto_copy_rates_is_checked { + get => _auto_copy_rates_is_checked; + set => Set(ref _auto_copy_rates_is_checked, value); + } + + ExpParamsRow _to_row(AnalyticsExpirationParameters exp_params) => + new(exp_params, this); + + AnalyticsExpirationParameters _from_row(ExpParamsRow row) => + new(row.security, row.driver, row.deliverable.is_empty() ? null : row.deliverable, row.roll_schedule.is_empty() ? null : row.roll_schedule, row.roll_target, row.riskless_rate, row.settlement_price, row.delta_beta, row.vega_beta); + + public StartupData get_state() => + new() { + selected_symbols = checked_symbols.Cast().ToArray(), + auto_copy_rates_is_checked = auto_copy_rates_is_checked, + auto_copy_rolls_is_checked = auto_copy_rolls_is_checked + }; + + void _on_checked_symbols_changed(object sender, NotifyCollectionChangedEventArgs e) => + filtered_for_visible_rows.sync_with(rows.Where(x => checked_symbols.Contains(x.security.symbol))); + + public class ExpParamsRow : DisposableViewModelBase, AnalyticsExpirationParametersView.IExpParamsRow { + readonly AnalyticsExpirationParameters _original_params; + readonly AnalyticsExpirationParametersVM _owner; + readonly Property _roll_schedule; + readonly Property _roll_schedule_dirty; + + double _roll_target; + double _riskless_rate; + double _settlement_price; + double _delta_beta; + double _vega_beta; + SecurityExpiration _driver; + SecurityExpiration _deliverable; + bool _is_last_row_of_month_group; + + IRaiseCanExecuteChangedCommand _copy_driver_to_selection; + IRaiseCanExecuteChangedCommand _copy_deliverable_to_selection; + readonly ObservantCommand _smart_copy_roll_target_cmd; + readonly ObservantCommand _smart_copy_riskless_rate_cmd; + + public ExpParamsRow(AnalyticsExpirationParameters param, AnalyticsExpirationParametersVM owner) { + _original_params = param; + _owner = owner; + security = param.security; + _driver = param.driver_security; + _deliverable = param.deliverable_security; + _roll_schedule = backing(nameof(roll_schedule), param.roll_schedule_expiration); + _roll_schedule_dirty = backing( + nameof(roll_schedule_dirty), + _roll_schedule.observe_current(true) + .Select(rs => !rs.Equals(_original_params.roll_schedule_expiration))); + _roll_target = param.roll_target; + _riskless_rate = param.riskless_rate; + _settlement_price = param.settlement_price; + _delta_beta = param.delta_beta; + _vega_beta = param.vega_beta; + _delta_beta = param.delta_beta; + _vega_beta = param.vega_beta; + + _smart_copy_roll_target_cmd = new ObservantCommand(_smart_copy_roll_target); + _smart_copy_riskless_rate_cmd = new ObservantCommand(_smart_copy_riskless_rate); + + _dispose = Disposable.Create( + _roll_schedule.observe_current(true) + .CombineLatest(_roll_schedule_dirty.observe_current(true), (rs, rs_dirty) => (rs, rs_dirty)) + .Select(tup => !tup.rs.is_empty() && !tup.rs_dirty) + .Subscribe(new CompositeObserver(_smart_copy_roll_target_cmd, _smart_copy_riskless_rate_cmd))); + } + + public SecurityExpiration security { get; } + public SecurityExpiration driver { get => _driver; set => Set(ref _driver, value); } + public SecurityExpiration deliverable { get => _deliverable; set => Set(ref _deliverable, value); } + public SecurityExpiration roll_schedule { get => _roll_schedule.Value; set => _roll_schedule.Value = value; } + + public bool is_last_row_of_month_group { + get => _is_last_row_of_month_group; + set => Set(ref _is_last_row_of_month_group, value); + } + + public double roll_target { + get => _roll_target; + set => _handle_input(_original_params.roll_target, ref _roll_target, value); + } + + public double riskless_rate { + get => _riskless_rate; + set => _handle_input(_original_params.riskless_rate, ref _riskless_rate, value); + } + + public double settlement_price { + get => _settlement_price; + set => _handle_input(_original_params.settlement_price, ref _settlement_price, value); + } + + public double delta_beta { + get => _delta_beta; + set => _handle_input(_original_params.delta_beta, ref _delta_beta, value); + } + + public double vega_beta { + get => _vega_beta; + set => _handle_input(_original_params.vega_beta, ref _vega_beta, value); + } + + public bool driver_dirty => !_driver.Equals(_original_params.driver_security); + public bool deliverable_dirty => !_deliverable.Equals(_original_params.deliverable_security); + public bool roll_schedule_dirty => !_roll_schedule.Equals(_original_params.roll_schedule_expiration); + public bool roll_target_dirty => !_roll_target.Equals(_original_params.roll_target); + public bool riskless_rate_dirty => !_riskless_rate.Equals(_original_params.riskless_rate); + public bool settlement_price_dirty => !_settlement_price.Equals(_original_params.settlement_price); + public bool delta_beta_dirty => !_delta_beta.Equals(_original_params.delta_beta); + public bool vega_beta_dirty => !_vega_beta.Equals(_original_params.vega_beta); + + public ICommand copy_driver_to_selection_cmd => _copy_driver_to_selection ??= new DelegateCommand(_ => { + foreach (var r in _get_selected_rows()) { + r.driver = driver; + r.RaisePropertyChanged(nameof(r.driver)); + } + }); + + public ICommand copy_deliverable_to_selection_cmd => _copy_deliverable_to_selection ??= new DelegateCommand(_ => { + foreach (var r in _get_selected_rows()) { + r.deliverable = deliverable; + r.RaisePropertyChanged(nameof(r.deliverable)); + } + }); + + public ICommand copy_roll_schedule_to_selection_cmd => new DelegateCommand(_ => { + foreach (var r in _get_selected_rows()) { + r.roll_schedule = roll_schedule; + r.RaisePropertyChanged(nameof(r.roll_schedule)); + } + }); + + public ICommand copy_roll_target_to_selection_cmd => new DelegateCommand(() => { + foreach (var r in _get_selected_rows()) { + r.roll_target = roll_target; + } + }); + + public ICommand copy_riskless_rate_to_selection_cmd => new DelegateCommand(() => { + foreach (var r in _get_selected_rows()) { + r.riskless_rate = riskless_rate; + } + }); + + public ICommand copy_settlement_price_to_selection_cmd => new DelegateCommand(() => { + foreach (var r in _get_selected_rows()) { + r.settlement_price = settlement_price; + } + }); + + public ICommand copy_delta_beta_to_selection_cmd => new DelegateCommand(() => { + foreach (var r in _get_selected_rows()) { + r.delta_beta = delta_beta; + } + }); + + public ICommand copy_vega_beta_to_selection_cmd => new DelegateCommand(() => { + foreach (var r in _get_selected_rows()) { + r.vega_beta = vega_beta; + } + }); + + public ICommand smart_copy_roll_target_cmd => _smart_copy_roll_target_cmd; + public ICommand smart_copy_riskless_rate_cmd => _smart_copy_riskless_rate_cmd; + + public void revert() { + driver = _original_params.driver_security; + deliverable = _original_params.deliverable_security; + roll_schedule = _original_params.roll_schedule_expiration; + roll_target = _original_params.roll_target; + riskless_rate = _original_params.riskless_rate; + settlement_price = _original_params.settlement_price; + delta_beta = _original_params.delta_beta; + vega_beta = _original_params.vega_beta; + } + + void _handle_input(double orig, ref double current, double next, [CallerMemberName] string prop = "") { + if (current.Equals(next)) { + return; + } + bool raise_dirty = current.Equals(orig) != next.Equals(orig); + current = next; + RaisePropertyChanged(prop); + if (raise_dirty) { + RaisePropertyChanged(prop + "_dirty"); + } + if (prop == nameof(roll_target) && _smart_copy_roll_target_cmd.CanExecute(null) && _owner.auto_copy_rolls_is_checked) { + _smart_copy_roll_target(); + } + if (prop == nameof(riskless_rate) && _smart_copy_riskless_rate_cmd.CanExecute(null) && _owner.auto_copy_rates_is_checked) { + _smart_copy_riskless_rate(); + } + } + + IEnumerable _get_selected_rows() => + _owner.selected_rows.OfType().ToList(); + + IEnumerable _get_smart_copy_roll_target_rows() { + var target_exps = _owner._model.get_smart_copy_roll_exps(_original_params); + var target_rows = _owner.rows.Where(r => target_exps.Contains(r.security)); + return target_rows; + } + + void _smart_copy_roll_target() { + foreach (var r in _get_smart_copy_roll_target_rows()) { + r.roll_target = roll_target; + } + } + + void _smart_copy_riskless_rate() { + foreach (var r in _get_smart_copy_roll_target_rows()) { + r.riskless_rate = riskless_rate; + } + } + } + + [ProtoContract] + public class StartupData { + public const int VERSION = 1; + + [ProtoMember(10)] + public string[] selected_symbols; + + [ProtoMember(20)] + public bool auto_copy_rates_is_checked; + + [ProtoMember(30)] + public bool auto_copy_rolls_is_checked; + } + } +} diff --git a/src/client/spark/AW2/AnalyticsParameters/AnalyticsExpirationParametersView.xaml b/src/client/spark/AW2/AnalyticsParameters/AnalyticsExpirationParametersView.xaml new file mode 100644 index 000000000..ceee7bce0 --- /dev/null +++ b/src/client/spark/AW2/AnalyticsParameters/AnalyticsExpirationParametersView.xaml @@ -0,0 +1,544 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/client/spark/AW2/AnalyticsParameters/AnalyticsExpirationParametersView.xaml.cs b/src/client/spark/AW2/AnalyticsParameters/AnalyticsExpirationParametersView.xaml.cs new file mode 100644 index 000000000..ed8e31abe --- /dev/null +++ b/src/client/spark/AW2/AnalyticsParameters/AnalyticsExpirationParametersView.xaml.cs @@ -0,0 +1,68 @@ +namespace mbts.ui.shell { + using bts.api; + + using System; + using System.Windows; + using System.Windows.Controls; + using System.Windows.Data; + using System.Windows.Input; + + /// + /// Interaction logic for AnalyticsExpirationParametersView.xaml + /// + partial class AnalyticsExpirationParametersView : UserControl { + public AnalyticsExpirationParametersView() => + InitializeComponent(); + + public interface IExpParamsRow { + ICommand copy_driver_to_selection_cmd { get; } + ICommand copy_deliverable_to_selection_cmd { get; } + ICommand copy_roll_schedule_to_selection_cmd { get; } + ICommand copy_roll_target_to_selection_cmd { get; } + ICommand copy_riskless_rate_to_selection_cmd { get; } + ICommand copy_settlement_price_to_selection_cmd { get; } + ICommand copy_delta_beta_to_selection_cmd { get; } + ICommand copy_vega_beta_to_selection_cmd { get; } + ICommand smart_copy_roll_target_cmd { get; } + } + + void grid_PreviewMouseRightButtonUp(object sender, MouseButtonEventArgs e) { + if (e.OriginalSource is not FrameworkElement el) { + return; + } + var cell = el.find_ancestor_of_type(); + if (cell?.ContextMenu is not ContextMenu cm || cell.DataContext is not IExpParamsRow row) { + return; + } + cm.DataContext = row; + cm.IsOpen = true; + e.Handled = true; + } + } + + class ExpTextConverter : IValueConverter { + public ExpTextConverter() { + NullOrEmptyText = "None"; + } + + public bool ShowType { get; set; } + public bool ShowSymbol { get; set; } + public bool MapExp { get; set; } + public string NullOrEmptyText { get; set; } + + public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { + var exp = value as SecurityExpiration; + if (exp == null || exp.is_empty()) { + return NullOrEmptyText; + } + return ShowSymbol ? + SecurityFormatter.format_future(exp.symbol, exp.expiration) : + DateFormatter.Format(exp.expiration, DateFormat.MonthCodeLastDigitYear); + } + + public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { + throw new NotImplementedException(); + } + } + +} diff --git a/src/client/spark/AW2/AnalyticsParameters/AnalyticsExpirationParametersWindow.cs b/src/client/spark/AW2/AnalyticsParameters/AnalyticsExpirationParametersWindow.cs new file mode 100644 index 000000000..5aced279e --- /dev/null +++ b/src/client/spark/AW2/AnalyticsParameters/AnalyticsExpirationParametersWindow.cs @@ -0,0 +1,42 @@ +namespace mbts.spark { + using bts.api; + using bts.spark; + + using mbts.ui.shell; + + using System; + using System.Windows; + + class AnalyticsExpirationParametersWindow : SparkWindow { + const string _window_type = nameof(AnalyticsExpirationParametersWindow); + + readonly Lazy _model; + readonly Lazy _vm; + + public AnalyticsExpirationParametersWindow( + IBus bus, AnalyticsExpirationParametersWindowFactory factory, AnalyticsExpirationParametersVM.StartupData startup_data) + : base("Analytics Exp Params", bus, factory) { + _model = new Lazy(() => new AnalyticsParametersUIModel(_bus)); + _vm = new Lazy( + () => new AnalyticsExpirationParametersVM(bus, _model.Value, startup_data)); + _dispose = Disposable.Create(() => { + if (_vm.IsValueCreated) { + _vm.Value.Dispose(); + } + if (_model.IsValueCreated) { + _model.Value.Dispose(); + } + }); + } + + public override string window_type => _window_type; + + public override AnalyticsExpirationParametersVM.StartupData SaveState => + _vm.IsValueCreated ? _vm.Value.get_state() : null; + + public override UIElement Content => + new AnalyticsExpirationParametersView { + DataContext = _vm.Value + }; + } +} diff --git a/src/client/spark/AW2/AnalyticsParameters/AnalyticsExpirationParametersWindowFactory.cs b/src/client/spark/AW2/AnalyticsParameters/AnalyticsExpirationParametersWindowFactory.cs new file mode 100644 index 000000000..714d57151 --- /dev/null +++ b/src/client/spark/AW2/AnalyticsParameters/AnalyticsExpirationParametersWindowFactory.cs @@ -0,0 +1,35 @@ +namespace mbts.spark { + using bts.api; + using bts.shell; + + using mbts.ui; + + using System; + using System.Linq; + using System.Reactive.Linq; + using System.Threading.Tasks; + + class AnalyticsExpirationParametersWindowFactory : ShellWindowFactory { + readonly IBus _bus; + + public AnalyticsExpirationParametersWindowFactory(IShellModule module, IBus bus) + : base(module, "Analytics Exp Params") { + _bus = bus; + _dispose = bus.subscribe(SparkTags.show_analytics_exp_params).OnDispatcher().Subscribe(_show); + } + + public override Task load(AnalyticsExpirationParametersVM.StartupData state) => + Task.FromResult(_create(state)); + + void _show(SparkTags.Nothing _) => + _bus.post(SparkTags.ShowWindow, _create(new AnalyticsExpirationParametersVM.StartupData())); + + void _show(SecurityCriteria security_criteria) => + _bus.post(SparkTags.ShowWindow, _create(new AnalyticsExpirationParametersVM.StartupData { + selected_symbols = (security_criteria?.clauses?.FirstOrDefault())?.symbols ?? Array.Empty() + })); + + IShellWindow _create(AnalyticsExpirationParametersVM.StartupData startup_data) => + new AnalyticsExpirationParametersWindow(_bus, this, startup_data); + } +} diff --git a/src/client/spark/AW2/AnalyticsParameters/AnalyticsParametersUIModel.cs b/src/client/spark/AW2/AnalyticsParameters/AnalyticsParametersUIModel.cs new file mode 100644 index 000000000..e330ff160 --- /dev/null +++ b/src/client/spark/AW2/AnalyticsParameters/AnalyticsParametersUIModel.cs @@ -0,0 +1,40 @@ +namespace mbts.spark { + using bts.api; + + using mbts; + using mbts.analytics; + + using System; + using System.Collections.Generic; + using System.Linq; + using System.Text; + using System.Threading.Tasks; + + class AnalyticsParametersUIModel : IDisposable { + AnalyticsExpirationParametersMap _curr_val = null; + readonly IBus _bus; + readonly IDisposable _sub; + + public event Action on_expiration_parameters; + + public AnalyticsParametersUIModel(IBus bus) { + _bus = bus; + _sub = _bus.subscribe(SparkTags.ExpirationParametersInputTag) + .Subscribe(d => on_expiration_parameters?.Invoke(d)); + } + + public void commit(IEnumerable data) => + _bus.post(SparkTags.ExpirationParametersCommitTag, data); + + public IEnumerable get_smart_copy_roll_exps(AnalyticsExpirationParameters source) { + if (_curr_val != null) { + foreach (var kv in _curr_val.exp_map) + if (kv.Value.roll_schedule_expiration.Equals(source.roll_schedule_expiration)) + yield return kv.Key; + } + } + + public void Dispose() => + _sub.Dispose(); + } +} diff --git a/src/client/spark/AW2/Bus/SingleOptionDriverPricePublisher.cs b/src/client/spark/AW2/Bus/SingleOptionDriverPricePublisher.cs index 71ed343f5..3894f405c 100644 --- a/src/client/spark/AW2/Bus/SingleOptionDriverPricePublisher.cs +++ b/src/client/spark/AW2/Bus/SingleOptionDriverPricePublisher.cs @@ -1,18 +1,14 @@ using System; using System.Collections.Generic; using System.Linq; -using System.Text; -using System.Threading.Tasks; using mbts.analytics; -using mbts; using bts.api; -using System.Security.Principal; -using mbts.co2; namespace mbts.spark { using DriverMD = Tuple; - // publishes the driver prices for driver securities that drive - // expirations of an option + // Publishes the driver prices for expirations of a single option (this is not AW2 specific) + // f(AnalyticsExpirationParametersMap, SystemContractData) -> OptionDriverPriceMap + // This is constructed by the ResourceAllocator public class SingleOptionDriverPricePublisher { private readonly SecurityTuple _sec_tup; private ThreadedBlackboard _bb; @@ -21,18 +17,20 @@ namespace mbts.spark { SparkTags.ExpirationParametersInputTag; private ITag _in_bb_contracts_tag = SparkTags.SystemContractsTag; - private IDictionary _last_published_map - = new Dictionary(); + private OptionDriverPriceMap _last_published; public SingleOptionDriverPricePublisher(SecurityTuple sec_tup, ThreadedBlackboard bb) { - bts.Log.Gen.info($"SingleOptionDriverPricePublisher initialized st:'{sec_tup}'"); + bts.Log.Gen.info($"SingleOptionDriverPricePublisher initialized st:{sec_tup}"); _sec_tup = sec_tup; _bb = bb; + _last_published = new OptionDriverPriceMap(sec_tup.security_name, + new Dictionary()); _bb.subscribe(_in_bb_exp_params_tag); _bb.subscribe(_in_bb_contracts_tag); _bb.data_callback += _on_bb_data; _bb.timer_callback += _on_bb_timer; + _compute_and_fire(); } private void _on_bb_data(object tag, object data) { @@ -63,8 +61,10 @@ namespace mbts.spark { res.Add(option_exp, bbo_tup); } if (_is_different(res)) { - _last_published_map = res; - bts.Log.Gen.info($"SingleOptionDriverPricePublisher._compute_and_fire sz:'{res.Count()}'"); + _last_published = new OptionDriverPriceMap(_sec_tup.security_name, res); + var to_fire = new OptionDriverPriceMap(_sec_tup.security_name, res); + bts.Log.Gen.info("SingleOptionDriverPricePublisher._compute_and_fire \n" + + $"map:{to_fire.log_string()}"); _bb.post(SparkTags.OptionDriverBBOTag(_sec_tup.security_name), new OptionDriverPriceMap(_sec_tup.security_name, res)); } @@ -76,7 +76,7 @@ namespace mbts.spark { return !d1.Item1.Equals(d2.Item1) || !d1.Item2.Equals(d2.Item2); }; - new_dic.Difference(_last_published_map, out var ex_left, out var ex_right, out var overlap); + new_dic.Difference(_last_published.exp_price_map, out var ex_left, out var ex_right, out var overlap); return ex_left.Count() != 0 || ex_right.Count() != 0 || overlap.Where(v => is_dmd_diff(v.Value.left, v.Value.right)).Count() > 0; } diff --git a/src/client/spark/AW2/Bus/SingleVolSurfaceCommittedOutputRetriever.cs b/src/client/spark/AW2/Bus/SingleVolSurfaceCommittedOutputRetriever.cs index 392328fc3..0760c34b3 100644 --- a/src/client/spark/AW2/Bus/SingleVolSurfaceCommittedOutputRetriever.cs +++ b/src/client/spark/AW2/Bus/SingleVolSurfaceCommittedOutputRetriever.cs @@ -12,8 +12,8 @@ namespace mbts.spark { // - f (vs_input, aux_data, securities) -> vs_output // and publishes it // Subs : - // 1. Comm VS Input - // 3. VS nonvol Data + // 1. Committed VS Input + // 3. VS Nonvol Data // Pubs : // 1. VS Out public class SingleVolSurfaceCommittedOutputRetriever : IDisposable { @@ -29,7 +29,7 @@ namespace mbts.spark { public SingleVolSurfaceCommittedOutputRetriever(int vs_id, ThreadedBlackboard threaded_bb, IEnumerable symbols) { - bts.Log.Gen.info($"SingleVolSurfaceCommittedOutputRetriever cons vs_id:{vs_id}"); + bts.Log.Gen.info($"SingleVolSurfaceCommittedOutputRetriever cons vs_id:{vs_id} tid:{_tid()}"); _vs_id = vs_id; _bb = threaded_bb; _in_bb_vs_input_tag = SparkTags.VolSurfaceCommittedInputTag(vs_id); @@ -43,13 +43,14 @@ namespace mbts.spark { _bb.data_callback += _on_bb_data; _recompute_and_publish(); } - + private static int _tid() { return VolSurfaceTroubleshootingFunctions.tid(); } private void _on_bb_data(object tag, object data) { - if (_in_bb_vs_input_tag.Equals(tag) || _in_bb_nonvol_data_tag.Equals(tag) || _in_vs_standard_time_tag.Equals(tag)) - _recompute_and_publish(); + if (_in_bb_vs_input_tag.Equals(tag) || _in_bb_nonvol_data_tag.Equals(tag) || + _in_vs_standard_time_tag.Equals(tag)) + _recompute_and_publish(tag); } - private void _recompute_and_publish() { + private void _recompute_and_publish(object tag = null) { VolSurfaceInput vs_input = _bb.read_state(_in_bb_vs_input_tag); VolSurfaceNonVolData vs_nonvol_data = _bb.read_state(_in_bb_nonvol_data_tag); VolSurfaceStandardTime vs_standard_time = _bb.read_state(_in_vs_standard_time_tag); @@ -60,7 +61,10 @@ namespace mbts.spark { vs_nonvol_data.input, vs_nonvol_data.driver_price_map, vs_standard_time); VolSurfaceOutput vs_output = GeneralVolSurfaceCalculator.compute(vs_input, vs_nonvol_data.contracts, aux_data_map); _timer.stop(); - bts.Log.Gen.info($"SingleVolSurfaceCommittedOutputRetriever._recompute_and_publish vs_id:{_vs_id} time:{_timer.lastIntervalTime} msecs"); + var tag_str = tag == null ? "Null" : tag.ToString(); + bts.Log.Gen.info($"SingleVolSurfaceCommittedOutputRetriever._recompute_and_publish " + + $"vs_id:{_vs_id} time:{_timer.lastIntervalTime} ms tag:{tag_str} tid:{_tid()}" + + $"output: {vs_output.log_string()}"); _logger.log(_log_id, _log_id, _timer.lastIntervalTime); _bb.post(_out_bb_computed_vol_tag, vs_output); } diff --git a/src/client/spark/AW2/Bus/SingleVolSurfaceGateway.cs b/src/client/spark/AW2/Bus/SingleVolSurfaceGateway.cs index 0cd23d73c..beebc0d94 100644 --- a/src/client/spark/AW2/Bus/SingleVolSurfaceGateway.cs +++ b/src/client/spark/AW2/Bus/SingleVolSurfaceGateway.cs @@ -20,10 +20,10 @@ namespace mbts.spark { private readonly int _volsurface_id; private readonly ThreadedBlackboard _bb; private readonly ITag _in_bb_committ_tag; - private AnalyticsService _analytics_service; + private readonly AnalyticsService _analytics_service; private readonly HighPerformanceTimer _timer = new HighPerformanceTimer(); private readonly string _user; - private List _disposables = new List(); + private readonly List _disposables = new List(); private IDictionary _snp_shot_map = new Dictionary(); @@ -45,12 +45,8 @@ namespace mbts.spark { } private void _log_basic_vs_info(VolSurfaceInput vs_inp) { - string exp_str = "expirations: "; - foreach (var kv in vs_inp.surface_parameters.curve_parameters_map) { - exp_str += " " + kv.Item1.to_security_expiration().ToString(); - } - bts.Log.Gen.info(String.Format("SingleVolSurfaceGateway vs_id:{0} {1}", - vs_inp.surface_settings.core_settings.vol_surface_id, exp_str)); + bts.Log.Gen.info(String.Format("SingleVolSurfaceGateway vs_id:{0} vs:{1}", + vs_inp.surface_settings.core_settings.vol_surface_id, vs_inp.log_string())); } private void _on_vss(bts.api.core.Update update) { diff --git a/src/client/spark/AW2/Bus/SingleVolSurfaceManager.cs b/src/client/spark/AW2/Bus/SingleVolSurfaceManager.cs index c7d70917b..355d62159 100644 --- a/src/client/spark/AW2/Bus/SingleVolSurfaceManager.cs +++ b/src/client/spark/AW2/Bus/SingleVolSurfaceManager.cs @@ -1,57 +1,75 @@ using System; using System.Collections.Generic; using System.Linq; -using System.Text; -using System.Threading.Tasks; - using bts.api.analytics; using bts.api; -using mbts.analytics; - namespace mbts.spark { public class SingleVolSurfaceManager : IDisposable { + private readonly int _vs_id; private IEnumerable _resources; - private readonly ITag _in_bb_delete_tag = SparkTags.VolSurfaceDeleteTag; - private readonly ThreadedBlackboard _threaded_bb; + private readonly ThreadedBlackboard _bb; + private readonly AnalyticsService _analytics_service; + private ITag _vs_activation_tag; + private bool _activated = false; public SingleVolSurfaceManager(int vs_id, ThreadedBlackboard t_bb, AnalyticsService analytics_service) { - _threaded_bb = t_bb; - _threaded_bb.subscribe(_in_bb_delete_tag); - _threaded_bb.data_callback += _on_data; + var tid = System.Threading.Thread.CurrentThread.ManagedThreadId; + bts.Log.Ui.info($"SingleVolSurfaceManager.cons vs_id:{vs_id} tid:{tid}"); + _vs_id = vs_id; + _bb = t_bb; + _analytics_service = analytics_service; + _vs_activation_tag = SparkTags.VolSurfaceActiveUITag(vs_id); + _bb.subscribe(_vs_activation_tag); + _bb.data_callback += _on_data; + } + + private void _spin_resources() { + bts.Log.Ui.info($"SingleVolSurfaceManager._spin_resources vs_id:{_vs_id}"); _resources = new IDisposable[] - { - new SingleVolSurfaceGateway(vs_id, t_bb, analytics_service), - new SingleVolSurfaceTimeSource(vs_id,t_bb), - new SingleVolSurfaceDataSource(SingleVolSurfaceDataSource.SymbolListType.Combined, vs_id, t_bb, - syms => new SingleVolSurfaceOptionDriverSource(vs_id, syms, t_bb)), + { + new SingleVolSurfaceGateway(_vs_id, _bb, _analytics_service), + new SingleVolSurfaceTimeSource(_vs_id,_bb), + new SingleVolSurfaceDataSource(SingleVolSurfaceDataSource.SymbolListType.Combined, _vs_id, _bb, + syms => new SingleVolSurfaceOptionDriverSource(_vs_id, syms, _bb)), new SingleVolSurfaceDataSource(SingleVolSurfaceDataSource.SymbolListType.Combined, - vs_id, t_bb, syms => new SingleVolSurfaceNonVolDataSource(vs_id, syms, t_bb)), - new SingleVolSurfaceDataSource(SingleVolSurfaceDataSource.SymbolListType.Committed, vs_id, t_bb, - a_syms => new SingleVolSurfaceCommittedOutputRetriever(vs_id, t_bb, a_syms)), - new SingleVolSurfaceDataSource(SingleVolSurfaceDataSource.SymbolListType.Candidate, vs_id, t_bb, - a_syms => new SingleVolSurfaceRequestCalculator(vs_id, a_syms, t_bb)), - new SingleVolSurfaceMarketImpliedVolSource(vs_id, t_bb), - new SingleVolSurfaceTheoSource(vs_id, t_bb), + _vs_id, _bb, syms => new SingleVolSurfaceNonVolDataSource(_vs_id, syms, _bb)), + new SingleVolSurfaceDataSource(SingleVolSurfaceDataSource.SymbolListType.Committed, _vs_id, _bb, + a_syms => new SingleVolSurfaceCommittedOutputRetriever(_vs_id, _bb, a_syms)), + new SingleVolSurfaceDataSource(SingleVolSurfaceDataSource.SymbolListType.Combined, _vs_id, _bb, + a_syms => new SingleVolSurfaceRequestCalculator(_vs_id, a_syms, _bb)), + new SingleVolSurfaceMarketImpliedVolSource(_vs_id, _bb), + new SingleVolSurfaceTheoSource(_vs_id, _bb), // TODO: suspending heatmaps for now (12/24/21) // new SingleVolSurfaceHeatmapManager (vs_id, t_bb), // server work that can optionally be done on the client - new SingleVolSurfaceDataSource (SingleVolSurfaceDataSource.SymbolListType.Committed, vs_id, t_bb, - a_syms => new SingleVolSurfaceClientPrecomputedTheosPublisher (vs_id, t_bb, a_syms)), - }; + new SingleVolSurfaceDataSource (SingleVolSurfaceDataSource.SymbolListType.Committed, _vs_id, _bb, + a_syms => new SingleVolSurfaceClientPrecomputedTheosPublisher (_vs_id, _bb, a_syms)), + }; } private void _on_data(object tag, object data) { - if (_in_bb_delete_tag.Equals(tag)) - Dispose(); + if (_vs_activation_tag.Equals(tag)) { + if (_activated) { + // TODO: not cleaning up recources + return; + } + bool is_activation_signal = data is Boolean && (Boolean)data; + if (is_activation_signal) { + _activated = true; + _spin_resources(); + } + } } #region IDisposable private bool _is_disposed = false; public void Dispose() { - if (!_is_disposed) + if (!_is_disposed) { + _is_disposed = true; _resources.ToList().ForEach(d => d.Dispose()); + } } #endregion } diff --git a/src/client/spark/AW2/Bus/SingleVolSurfaceNonVolDataSource.cs b/src/client/spark/AW2/Bus/SingleVolSurfaceNonVolDataSource.cs index 466cf213b..550f5730b 100644 --- a/src/client/spark/AW2/Bus/SingleVolSurfaceNonVolDataSource.cs +++ b/src/client/spark/AW2/Bus/SingleVolSurfaceNonVolDataSource.cs @@ -1,8 +1,5 @@ using System; using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; using mbts.analytics; using bts.api; @@ -17,6 +14,7 @@ namespace mbts.spark { // 3. Driver prices (VolSurfaceOptionDriverTag) // Publishes : // 1. VolSurfaceNonVolData which is simply a union of the 3 inputs + // 2. VolSurfaceStrikeMap public class SingleVolSurfaceNonVolDataSource : IDisposable { private readonly int _vs_id; private readonly IEnumerable _option_symbols; @@ -26,12 +24,9 @@ namespace mbts.spark { private readonly ITag> _in_bb_driver_price_tag; private readonly ITag _out_bb_vs_nonvol_data_tag; private readonly ITag _out_bb_vs_contracts_tag; - /// This is the only cached data to avoid computing it - /// when more frequently changing data move around - private IDictionary> _sec_map = - new Dictionary>(); - public SingleVolSurfaceNonVolDataSource(int vs_id, IEnumerable option_symbols, ThreadedBlackboard bb) { + public SingleVolSurfaceNonVolDataSource(int vs_id, IEnumerable option_symbols, + ThreadedBlackboard bb) { bts.Log.Gen.info($"SingleVolSurfaceNonVolDataSource vs_id:{vs_id}"); _vs_id = vs_id; _option_symbols = option_symbols; @@ -45,30 +40,41 @@ namespace mbts.spark { _bb.subscribe(_in_bb_vs_nonvol_input_tag); _bb.subscribe(_in_bb_driver_price_tag); _bb.data_callback += _on_bb_data; + _init(); + } + + private void _init() { + _publish_vs_strike_map(); + _recompute_and_fire(); + } + + private void _publish_vs_strike_map() { + SystemContractData sc_data = _bb.read_state(_in_bb_contract_data_tag); + if (sc_data != null) { + var k_map = new VolSurfaceStrikeMap(_option_symbols, sc_data); + bts.Log.Gen.info($"SingleVolSurfaceNonVolDataSource vs_id:{_vs_id} " + + "publishing strike_map sz:{k_map.strike_map.Count()}"); + _bb.post(_out_bb_vs_contracts_tag, new VolSurfaceStrikeMap(_option_symbols, sc_data)); + } } private void _on_bb_data(object tag, object data) { if (_in_bb_contract_data_tag.Equals(tag)) { - SystemContractData contract_data = _bb.read_state(_in_bb_contract_data_tag); - _sec_map.Clear(); - if (contract_data != null) - foreach (string s in _option_symbols) - foreach (var kv in contract_data.get_option_strikes(s)) - _sec_map[new VolSurfaceExpiration() { symbol = s, expiration = kv.Key }] = kv.Value; - bts.Log.Gen.info($"SingleVolSurfaceNonVolDataSource vs_id:{_vs_id} publishing strike_map sz:{_sec_map.Count()}"); - _bb.post(_out_bb_vs_contracts_tag, new VolSurfaceStrikeMap(_sec_map)); + _publish_vs_strike_map(); _recompute_and_fire(); } else if (_in_bb_vs_nonvol_input_tag.Equals(tag) || _in_bb_driver_price_tag.Equals(tag)) _recompute_and_fire(); } private void _recompute_and_fire() { + SystemContractData sc_data = _bb.read_state(_in_bb_contract_data_tag); VolSurfaceNonVolInput vs_nonvol_input = _bb.read_state(_in_bb_vs_nonvol_input_tag); var price_map = _bb.read_state(_in_bb_driver_price_tag); - if (_sec_map != null && vs_nonvol_input != null && price_map != null) { + if (sc_data != null && vs_nonvol_input != null && price_map != null) { bts.Log.Gen.info($"SingleVolSurfaceNonVolDataSource vs_id:{_vs_id} publishing VolSurfaceNonVolData"); _bb.post(_out_bb_vs_nonvol_data_tag, - new VolSurfaceNonVolData(vs_nonvol_input, price_map, _sec_map)); + new VolSurfaceNonVolData(vs_nonvol_input, price_map, + new VolSurfaceStrikeMap(_option_symbols, sc_data).strike_map)); } } diff --git a/src/client/spark/AW2/Bus/SingleVolSurfaceOptionDriverSource.cs b/src/client/spark/AW2/Bus/SingleVolSurfaceOptionDriverSource.cs index 4ca8f430d..4b135e497 100644 --- a/src/client/spark/AW2/Bus/SingleVolSurfaceOptionDriverSource.cs +++ b/src/client/spark/AW2/Bus/SingleVolSurfaceOptionDriverSource.cs @@ -1,8 +1,6 @@ using System; using System.Collections.Generic; using System.Linq; -using System.Text; -using System.Threading.Tasks; using mbts.analytics; using bts.api; @@ -11,29 +9,24 @@ namespace mbts.spark { // Subs : // 1. Driver Price tag for each option // Publishes : - // 1. Map of VS Exp vs Driver Price for each Option Exp - // in the VS + // 1. Map of VS Exp vs Driver Price for each Option Exp in the VS // TODO: VolSurfaceDriverSymbolPriceTag is not being published out (its needed for Slide) public class SingleVolSurfaceOptionDriverSource : IDisposable { private readonly int _vs_id; private readonly ThreadedBlackboard _threaded_bb; - private readonly ITag> _out_bb_driver_price_tag; - private readonly ITag> _out_bb_driver_symbol_price_tag; - private IDictionary _option_driver_price_map = - new Dictionary(); - private bool _option_driver_dirty = false; + private readonly ITag> + _out_bb_driver_price_tag; + private bool _option_driver_dirty = true; private HashSet> _option_driver_price_tags = new HashSet>(); - public SingleVolSurfaceOptionDriverSource(int vs_id, IEnumerable option_symbols, ThreadedBlackboard threaded_bb) { _vs_id = vs_id; - bts.Log.Gen.info($"SingleVolSurfaceOptionDriverSource cons vs_id:'{vs_id}' syms:'{option_symbols.Count()}'"); + bts.Log.Gen.info($"SingleVolSurfaceOptionDriverSource cons vs_id:{vs_id} syms:{option_symbols.Count()}"); _threaded_bb = threaded_bb; _out_bb_driver_price_tag = SparkTags.VolSurfaceOptionDriverTag(vs_id); - _out_bb_driver_symbol_price_tag = SparkTags.VolSurfaceDriverSymbolPriceTag(vs_id); foreach (string o in option_symbols) { var tag = SparkTags.OptionDriverBBOTag(o); _option_driver_price_tags.Add(tag); @@ -41,31 +34,40 @@ namespace mbts.spark { } _threaded_bb.data_callback += _on_bb_data; _threaded_bb.timer_callback += _on_timer; + _publish_driver_prices(); + } + + private IDictionary _get_driver_prices() { + var rv = new Dictionary(); + foreach (var tag in _option_driver_price_tags) { + OptionDriverPriceMap price_map = _threaded_bb.read_state(tag); + if (price_map == null) { + continue; + } + foreach (var kv in price_map.exp_price_map) { + Tuple driver_bbo = kv.Value; + rv[new VolSurfaceExpiration(kv.Key)] = driver_bbo.Item2.get_mid_price(); + } + } + return rv; + } + + private void _publish_driver_prices() { + var map = _get_driver_prices(); + _log_output(_vs_id, map); + _threaded_bb.post(_out_bb_driver_price_tag, map); } private void _on_bb_data(object tag, object data) { - if (tag != null) { - if (_option_driver_price_tags.Contains(tag)) { - OptionDriverPriceMap price_map = data as OptionDriverPriceMap; - foreach (var kv in price_map.exp_price_map) { - SecurityExpiration option_exp = kv.Key; - Tuple driver_bbo = kv.Value; - _option_driver_price_map[new VolSurfaceExpiration() { - symbol = price_map.option_symbol, - expiration = option_exp.expiration - }] = - driver_bbo.Item2.get_mid_price(); - } - _option_driver_dirty = true; - } + if (_option_driver_price_tags.Contains(tag)) { + _option_driver_dirty = true; } } - void _log_output() { - string log_txt = String.Format("SingleVolSurfaceOptionDriverSource vs_id:{0} data:", - _vs_id); - foreach (var kv in _option_driver_price_map) { - log_txt += " " + kv.Key + ":" + kv.Value; + static void _log_output(int vs_id, IDictionary d_map) { + string log_txt = $"SingleVolSurfaceOptionDriverSource vs_id:{0} data: "; + foreach (var kv in d_map) { + log_txt += kv.Key + ":" + kv.Value + ","; } bts.Log.Gen.info(log_txt); } @@ -73,10 +75,7 @@ namespace mbts.spark { private void _on_timer() { if (_option_driver_dirty) { _option_driver_dirty = false; - //bts.Log.Gen.info($"SingleVolSurfaceOptionDriverSource vs_id:{_vs_id} publishing sz:{_option_driver_price_map.Count()}"); - _log_output(); - _threaded_bb.post(_out_bb_driver_price_tag, - new Dictionary(_option_driver_price_map)); + _publish_driver_prices(); } } diff --git a/src/client/spark/AW2/Bus/SingleVolSurfaceRequestCalculator.cs b/src/client/spark/AW2/Bus/SingleVolSurfaceRequestCalculator.cs index 65a66a146..69add7513 100644 --- a/src/client/spark/AW2/Bus/SingleVolSurfaceRequestCalculator.cs +++ b/src/client/spark/AW2/Bus/SingleVolSurfaceRequestCalculator.cs @@ -30,7 +30,8 @@ namespace mbts.spark { /// data private VolSurfaceOutput _last_output; - public SingleVolSurfaceRequestCalculator(int vs_id, IEnumerable symbols, ThreadedBlackboard threaded_bb) { + public SingleVolSurfaceRequestCalculator(int vs_id, IEnumerable symbols, + ThreadedBlackboard threaded_bb) { bts.Log.Gen.info($"SingleVolSurfaceRequestCalculator cons vs_id:{vs_id}"); _vs_id = vs_id; _symbols = new HashSet(symbols); @@ -70,30 +71,36 @@ namespace mbts.spark { effective_req = curr_req; else { if (_last_output != null) - effective_req = new VolSurfaceCalculationRequest(_last_output.volsurface_input, curr_req.request_id); + effective_req = + new VolSurfaceCalculationRequest(_last_output.volsurface_input, curr_req.request_id); } if (effective_req != null) { IDictionary aux_data_map = VolSurfaceUtilityFunctions.compute_aux_data(effective_req.volsurface_input, - nonvol_data.input, nonvol_data.driver_price_map, vs_standard_time, true); - IDictionary action_map = _post_process_action(effective_req, aux_data_map); + nonvol_data.input, + nonvol_data.driver_price_map, + vs_standard_time, true); + IDictionary action_map = + _post_process_action(effective_req, aux_data_map); _last_output = GeneralVolSurfaceCalculator.compute(effective_req.volsurface_input, nonvol_data.contracts, aux_data_map, action_map, null, - effective_req.cascade_up, effective_req.cascade_down); + effective_req.cascade_up, + effective_req.cascade_down); _timer.stop(); - bts.Log.Gen.info(String.Format("SingleVolSurfaceRequestCalculator. Time to compute vol for {0} exps {1} msecs", - nonvol_data.contracts.Count, _timer.lastIntervalTime)); + bts.Log.Gen.info($"SingleVolSurfaceRequestCalculator._recompute_and_publish time:" + + $"{_timer.lastIntervalTime} vs_output:{_last_output.log_string()}"); _bb.post(SparkTags.VolSurfaceCalculationResponseTag(_vs_id), - new VolSurfaceCalculationResponse(_last_output, effective_req.request_id)); + new VolSurfaceCalculationResponse(_last_output, effective_req.request_id)); } } } /// Computes the impl vol if the action is fit to market - private IDictionary _post_process_action(VolSurfaceCalculationRequest req, + private IDictionary _post_process_action( + VolSurfaceCalculationRequest req, IDictionary aux_data_map) { IDictionary rv = req.action_map; /// TODO : VolCurveAction needs to be structured better. The UI enforces that @@ -103,7 +110,8 @@ namespace mbts.spark { VolCurveAction rep_action = rv.ElementAt(0).Value; if (rep_action.action_type == VolCurveAction.ActionType.FitToMarket) { IDictionary impl_vol_map = - _fill_in_implied_vols(req.volsurface_input, req.action_map, aux_data_map, req.cascade_up, req.cascade_down); + _fill_in_implied_vols(req.volsurface_input, req.action_map, aux_data_map, + req.cascade_up, req.cascade_down); rv = impl_vol_map.ToDictionary(kv => kv.Key, kv => new VolCurveAction( new VolCurveMarketFitAction(rep_action.market_fit_action.fit_action, kv.Value, rep_action.market_fit_action.use_weighted_regression))); @@ -112,29 +120,36 @@ namespace mbts.spark { return rv; } - private IDictionary _fill_in_implied_vols(VolSurfaceInput vs_inp, + private IDictionary _fill_in_implied_vols( + VolSurfaceInput vs_inp, IDictionary action_map, IDictionary aux_data_map, bool cascade_up, bool cascade_down) { - IDictionary rv = new Dictionary(); + IDictionary rv = + new Dictionary(); VolCurveAction rep_action = action_map.ElementAt(0).Value; - HashSet master_exps = VolSurfaceUtilityFunctions.get_master_expirations(vs_inp, true); + HashSet master_exps = + VolSurfaceUtilityFunctions.get_master_expirations(vs_inp, true); IEnumerable applicable_exps; if (cascade_up || cascade_down) - applicable_exps = VolSurfaceUtilityFunctions.get_exp_list_from_cascade(vs_inp.surface_parameters.curve_parameters_map.Select(t => t.Item1), - action_map.Keys, cascade_up, cascade_down); + applicable_exps = + VolSurfaceUtilityFunctions.get_exp_list_from_cascade( + vs_inp.surface_parameters.curve_parameters_map.Select(t => t.Item1), + action_map.Keys, cascade_up, cascade_down); else applicable_exps = action_map.Keys; applicable_exps = applicable_exps.Where(vs_exp => master_exps.Contains(vs_exp)); - VolSurfaceEnums.MarketSide impliedvol_side = SingleVolSurfaceMarketImpliedVolSource._get_market_impliedvol_side(_bb, _vs_id); + VolSurfaceEnums.MarketSide impliedvol_side = + SingleVolSurfaceMarketImpliedVolSource._get_market_impliedvol_side(_bb, _vs_id); foreach (VolSurfaceExpiration vs_exp in applicable_exps) { VolSurfaceExpiration md_exp; VolCurveMarketImpliedVolData exp_impl_data = VolSurfaceCoreFunctions.compute_implied_vols(vs_inp, vs_exp, aux_data_map, arg_vs_exp => SingleVolSurfaceMarketImpliedVolSource._get_bbo(_bb, arg_vs_exp), impliedvol_side, - SingleVolSurfaceMarketImpliedVolSource._ignore_market_implied_vol_source_settings(_bb, _vs_id), + SingleVolSurfaceMarketImpliedVolSource._ignore_market_implied_vol_source_settings( + _bb, _vs_id), out md_exp); rv[vs_exp] = exp_impl_data; } diff --git a/src/client/spark/AW2/Bus/SingleVolSurfaceTimeSource.cs b/src/client/spark/AW2/Bus/SingleVolSurfaceTimeSource.cs index 3c0758be5..16f017f30 100644 --- a/src/client/spark/AW2/Bus/SingleVolSurfaceTimeSource.cs +++ b/src/client/spark/AW2/Bus/SingleVolSurfaceTimeSource.cs @@ -1,8 +1,4 @@ using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; using mbts.analytics; @@ -10,7 +6,7 @@ namespace mbts.spark { public class SingleVolSurfaceTimeSource : IDisposable { private readonly int _vs_id; private readonly ThreadedBlackboard _bb; - private TimeSpan _publish_period = TimeSpan.FromMinutes(VolSurfaceConstants.vol_time_sample_mins); + private readonly TimeSpan _publish_period = TimeSpan.FromMinutes(VolSurfaceConstants.vol_time_sample_mins); private DateTime _last_publish_time = DateTime.MinValue; public SingleVolSurfaceTimeSource(int vs_id, ThreadedBlackboard bb) { @@ -35,4 +31,4 @@ namespace mbts.spark { } #endregion } -} +} \ No newline at end of file diff --git a/src/client/spark/AW2/Bus/VolSurfaceBlackboardManager.cs b/src/client/spark/AW2/Bus/VolSurfaceBlackboardManager.cs index 90c7103cb..eb297951f 100644 --- a/src/client/spark/AW2/Bus/VolSurfaceBlackboardManager.cs +++ b/src/client/spark/AW2/Bus/VolSurfaceBlackboardManager.cs @@ -59,17 +59,21 @@ namespace mbts.spark { private readonly ITag> _in_sec_tag = SparkTags.SecuritiesTag; private readonly ITag _in_bb_create_tag = SparkTags.VolSurfaceCreateTag; private readonly ITag _in_bb_delete_tag = SparkTags.VolSurfaceDeleteTag; - private readonly ITag _in_bb_exp_params_tag = SparkTags.ExpirationParametersInputTag; + private readonly ITag _in_bb_exp_params_tag = + SparkTags.ExpirationParametersInputTag; // state private SystemContractData _contract_data = null; - private IDictionary _vs_manager_map = new Dictionary(); - private Queue _waiting_creations = new Queue(); + private IDictionary _vs_manager_map = + new Dictionary(); + private Queue _waiting_creations = + new Queue(); private bts.api.IBus _bus; private List _subs = new List(); private HighPerformanceTimer _timer = new HighPerformanceTimer(); public VolSurfaceBlackboardManager(bts.api.IBus bus, bts.api.analytics.AnalyticsService analytics_service) { + bts.Log.Ui.info("VSBusManager cons tid:{VolSurfaceTroubleshootingFunctions.tid()}"); _bus = bus; _bb = new ThreadedBlackboard(bus); _analytics_service = analytics_service; @@ -122,8 +126,8 @@ namespace mbts.spark { // (will take care of it later) foreach (var vs_id in vs_ids) { if (!_vs_manager_map.ContainsKey(vs_id)) { - _vs_manager_map[vs_id] = new SingleVolSurfaceManager( - vs_id, _bb, _analytics_service); + _vs_manager_map.Add(vs_id, new SingleVolSurfaceManager( + vs_id, _bb, _analytics_service)); } } } @@ -151,8 +155,9 @@ namespace mbts.spark { _analytics_service.delete_volsurface(vs_id_w); } catch (Exception ex) { Log.Gen.error(String.Format("Vol Surface deletion failed with exception:{0}", ex.Message)); - _bb.post(SparkTags.MessageDisplayTag, new MessageDisplayData("Vol Surface Deletion", - String.Format("Could not delete Vol Surface, Error : {0}", ex.Message))); + _bb.post(SparkTags.MessageDisplayTag, + new MessageDisplayData("Vol Surface Deletion", + String.Format("Could not delete Vol Surface, Error : {0}", ex.Message))); } } else if (_in_bb_exp_params_tag.Equals(tag)) { AnalyticsExpirationParametersMap exp_param_map = data as AnalyticsExpirationParametersMap; diff --git a/src/client/spark/AW2/Graph/AxisPosition.cs b/src/client/spark/AW2/Graph/AxisPosition.cs new file mode 100644 index 000000000..86a005fc6 --- /dev/null +++ b/src/client/spark/AW2/Graph/AxisPosition.cs @@ -0,0 +1,13 @@ +namespace mbts.spark { + enum AxisPosition { + None, + TopLeftToRight, + TopRightToLeft, + BottomLeftToRight, + BottomRightToLeft, + LeftTopToBottom, + LeftBottomToTop, + RightTopToBottom, + RightBottomToTop + } +} diff --git a/src/client/spark/AW2/Graph/DateTimeIntervalType.cs b/src/client/spark/AW2/Graph/DateTimeIntervalType.cs new file mode 100644 index 000000000..ee21d1c7c --- /dev/null +++ b/src/client/spark/AW2/Graph/DateTimeIntervalType.cs @@ -0,0 +1,12 @@ +namespace mbts.spark { + enum DateTimeIntervalType { + Auto, + Seconds, + Minutes, + Hours, + Days, + Weeks, + Months, + Years + } +} diff --git a/src/client/spark/AW2/Graph/GraphPoint.cs b/src/client/spark/AW2/Graph/GraphPoint.cs new file mode 100644 index 000000000..f63b48ad2 --- /dev/null +++ b/src/client/spark/AW2/Graph/GraphPoint.cs @@ -0,0 +1,22 @@ +namespace mbts.spark { + using mbts.ui.shell; + + /// ** BTSGraphPoint in edge ** + /// + /// Represents a point in a graph + /// + class GraphPointVM : ViewModelBase { + object _x; + object _y; + + public GraphPointVM() { } + + public GraphPointVM(object x, object y) { + this.x = x; + this.x = y; + } + + public object x { get => _x; set => Set(ref _x, value); } + public object y { get => _y; set => Set(ref _y, value); } + } +} diff --git a/src/client/spark/AW2/Graph/IVolTermsSeries.cs b/src/client/spark/AW2/Graph/IVolTermsSeries.cs new file mode 100644 index 000000000..b96af2d69 --- /dev/null +++ b/src/client/spark/AW2/Graph/IVolTermsSeries.cs @@ -0,0 +1,9 @@ +namespace mbts.spark { + using System; + using System.Collections.Generic; + + interface IVolTermsSeries { + bool is_committed { get; } + void update_points(IReadOnlyDictionary vol_map); + } +} diff --git a/src/client/spark/AW2/Graph/LineSeriesSettings.cs b/src/client/spark/AW2/Graph/LineSeriesSettings.cs new file mode 100644 index 000000000..798436597 --- /dev/null +++ b/src/client/spark/AW2/Graph/LineSeriesSettings.cs @@ -0,0 +1,36 @@ +namespace mbts.spark { + using mbts.ui; + + using ProtoBuf; + + using System; + + [ProtoContract] + class LineSeriesSettings : IEquatable, ICloneable { + [ProtoMember(1)] + public LineStyle line_style { get; set; } + [ProtoMember(2)] + public double stroke_thickness { get; set; } + [ProtoMember(3)] + public BTSColor color { get; set; } + + public object Clone() => + new LineSeriesSettings { + line_style = line_style, + stroke_thickness = stroke_thickness, + color = color.clone() + }; + + public bool Equals(LineSeriesSettings other) => + other != null && + line_style == other.line_style && + stroke_thickness.Equals(other.stroke_thickness) && + color == other.color; + + public override bool Equals(object obj) => + Equals(obj as LineSeriesSettings); + + public override int GetHashCode() => + GetType().GetHashCode(); + } +} diff --git a/src/client/spark/AW2/Graph/LineStyle.cs b/src/client/spark/AW2/Graph/LineStyle.cs new file mode 100644 index 000000000..236b45027 --- /dev/null +++ b/src/client/spark/AW2/Graph/LineStyle.cs @@ -0,0 +1,16 @@ +namespace mbts.spark { + enum LineStyle { + None, + Solid, + Dashed, + Dot, + DashDot, + DashDashDot, + DashDotDot, + DashDashDotDot, + LongDash, + LongDashDot, + LongDashDotDot, + Automatic + }; +} diff --git a/src/client/spark/AW2/Graph/MarkerShape.cs b/src/client/spark/AW2/Graph/MarkerShape.cs new file mode 100644 index 000000000..551282546 --- /dev/null +++ b/src/client/spark/AW2/Graph/MarkerShape.cs @@ -0,0 +1,11 @@ +namespace mbts.spark { + enum MarkerShape { + None, + Circle, + Cross, Diamond, + Plus, + Square, + Star, + Triangle + } +} diff --git a/src/client/spark/AW2/Graph/ScatterSeriesSettings.cs b/src/client/spark/AW2/Graph/ScatterSeriesSettings.cs new file mode 100644 index 000000000..fd7b53b33 --- /dev/null +++ b/src/client/spark/AW2/Graph/ScatterSeriesSettings.cs @@ -0,0 +1,44 @@ +namespace mbts.spark { + using mbts.ui; + + using ProtoBuf; + + using System; + + [ProtoContract] + class ScatterSeriesSettings : IEquatable, ICloneable { + public ScatterSeriesSettings() { } + + public ScatterSeriesSettings(MarkerShape shape, double size, BTSColor color) { + this.shape = shape; + this.size = size; + this.color = color; + } + + [ProtoMember(1)] + public MarkerShape shape { get; set; } + [ProtoMember(2)] + public double size { get; set; } + [ProtoMember(3)] + public BTSColor color { get; set; } + + public object Clone() => + new ScatterSeriesSettings { + shape = shape, + size = size, + color = color.clone() + }; + + public bool Equals(ScatterSeriesSettings other) => + other != null && + shape == other.shape && + size.Equals(other.size) && + color == other.color; + + public override bool Equals(object obj) => + Equals(obj as ScatterSeriesSettings); + + public override int GetHashCode() => + GetType().GetHashCode(); + } +} diff --git a/src/client/spark/AW2/Graph/VolTermsLineSeriesVM.cs b/src/client/spark/AW2/Graph/VolTermsLineSeriesVM.cs new file mode 100644 index 000000000..05e1e9f5d --- /dev/null +++ b/src/client/spark/AW2/Graph/VolTermsLineSeriesVM.cs @@ -0,0 +1,40 @@ +namespace mbts.spark { + using bts.collections; + + using mbts.ui; + + using System; + using System.Collections.Generic; + using System.Linq; + + /// ** VolTermsLineSeries in edge ** + /// + /// Represents a scatter series in a graph + /// + class VolTermsLineSeriesVM : LineSeriesVM, IVolTermsSeries { + bool _is_committed; + // public VolTermsLineSeriesVM(bool is_committed) { + // this.is_committed = is_committed; + // name = is_committed ? "Committed" : "Candidate"; + // is_visible = true; + // color = BTSColors.VolSurfaceGraph.main_curve; + // line_style = is_committed ? LineStyle.Solid : LineStyle.Dashed; + // stroke_thickness = 1.5; + // } + + public bool is_committed { + get => _is_committed; + set { + if (Set(ref _is_committed, value)) { + name = value ? "Committed" : "Candidate"; + } + } + } + + public void update_points(IReadOnlyDictionary vol_map) => + points.SetItems(vol_map + .Where(kv => !double.IsNaN(kv.Value)) + .OrderBy(kv => kv.Key) + .Select(kv => new GraphPointVM(OxyPlot.Axes.DateTimeAxis.ToDouble(kv.Key), kv.Value))); + } +} diff --git a/src/client/spark/AW2/Graph/VolTermsScatterSeriesVM.cs b/src/client/spark/AW2/Graph/VolTermsScatterSeriesVM.cs new file mode 100644 index 000000000..5f08d7f8f --- /dev/null +++ b/src/client/spark/AW2/Graph/VolTermsScatterSeriesVM.cs @@ -0,0 +1,37 @@ +namespace mbts.spark { + using bts.collections; + + using mbts.ui; + + using System; + using System.Collections.Generic; + using System.Linq; + + class VolTermsScatterSeriesVM : ScatterSeriesVM, IVolTermsSeries { + bool _is_committed; + + // public VolTermsScatterSeriesVM(bool is_committed) { + // this.is_committed = is_committed; + // name = is_committed ? "Committed" : "Candidate"; + // is_visible = true; + // marker_color = BTSColors.VolSurfaceGraph.main_curve_atm; + // marker_shape = MarkerShape.Circle; + // marker_size = 3.0; + // } + + public bool is_committed { + get => _is_committed; + set { + if (Set(ref _is_committed, value)) { + name = value ? "Committed" : "Candidate"; + } + } + } + + public void update_points(IReadOnlyDictionary vol_map) => + points.SetItems(vol_map + .Where(kv => !double.IsNaN(kv.Value)) + .OrderBy(kv => kv.Key) + .Select(kv => new GraphPointVM(OxyPlot.Axes.DateTimeAxis.ToDouble(kv.Key), kv.Value))); + } +} diff --git a/src/client/spark/AW2/Grid/Settings/BTSTabularGridColumnConfiguration.cs b/src/client/spark/AW2/Grid/Settings/BTSTabularGridColumnConfiguration.cs index 004e73eb0..a90d9a963 100644 --- a/src/client/spark/AW2/Grid/Settings/BTSTabularGridColumnConfiguration.cs +++ b/src/client/spark/AW2/Grid/Settings/BTSTabularGridColumnConfiguration.cs @@ -24,6 +24,11 @@ namespace mbts.ui.controls header_font_weight = System.Drawing.FontStyle.Bold; wpf_width = Double.NaN; } + + internal BTSTabularGridColumnConfiguration(mbts.ui.settings.GridColumnSettings settings) { + /// TODO (maybe): need to resolve diffs between this class and + } + [ProtoMember(1)] public string name { get; set; } [ProtoMember(2)] diff --git a/src/client/spark/AW2/Grid/VolSurfaceDisplayGrid.cs b/src/client/spark/AW2/Grid/VolSurfaceDisplayGrid.cs index 7faeb1034..9249ce37f 100644 --- a/src/client/spark/AW2/Grid/VolSurfaceDisplayGrid.cs +++ b/src/client/spark/AW2/Grid/VolSurfaceDisplayGrid.cs @@ -10,11 +10,9 @@ using mbts.ui.shell; using mbts.spark; using bts.utils; -namespace mbts.ui.controls -{ +namespace mbts.ui.controls { /// Encapsulates the vol data that would show up in the top grid - public class VolSurfaceDisplayGrid : ICloneable, IGridDisplayModel, ICellDataStore - { + public class VolSurfaceDisplayGrid : ICloneable, IGridDisplayModel, ICellDataStore { private readonly IEnumerable _ordered_expirations = null; private readonly IEnumerable _ordered_columns = null; private readonly IDictionary _column_map; @@ -30,35 +28,36 @@ namespace mbts.ui.controls }).ToArray()); } + public IDictionary> data_map { + get { + return _data_map; + } + } public VolSurfaceDisplayGrid(IEnumerable ordered_expirations, IEnumerable ordered_columns, - IDictionary> data) - { + IDictionary> data) { _ordered_expirations = ordered_expirations; _ordered_columns = ordered_columns; _data_map = data; _column_map = ordered_columns.ToDictionary(k => k.unique_col_name, k => k); } - public object get_grid_data(VolSurfaceDisplayGridExpiration exp, VolSurfaceDisplayGridColumn col, object default_value) - { + public object get_grid_data(VolSurfaceDisplayGridExpiration exp, VolSurfaceDisplayGridColumn col, object default_value) { object rv = default_value; return get_grid_data(exp, col, out rv) ? rv : default_value; } - public bool get_grid_data(VolSurfaceDisplayGridExpiration exp, VolSurfaceDisplayGridColumn col, out object data) - { + public bool get_grid_data(VolSurfaceDisplayGridExpiration exp, VolSurfaceDisplayGridColumn col, out object data) { data = null; IDictionary exp_data; if (_data_map.TryGetValue(exp, out exp_data)) if (exp_data.TryGetValue(col, out data)) return true; return false; - } + } public bool copy(VolSurfaceDisplayGridExpiration source_exp, VolSurfaceDisplayGridTextInputColumn source_col, - VolSurfaceDisplayGridExpiration target_exp, VolSurfaceDisplayGridTextInputColumn target_col) - { + VolSurfaceDisplayGridExpiration target_exp, VolSurfaceDisplayGridTextInputColumn target_col) { object data; if (get_grid_data(source_exp, source_col, out data)) return set_grid_data(target_exp, target_col, data); @@ -68,18 +67,16 @@ namespace mbts.ui.controls #region Comparison Helpers /// Returns the expiration differences public static void compare_exps(VolSurfaceDisplayGrid new_grid, VolSurfaceDisplayGrid old_grid, - out IEnumerable deleted, out IEnumerable added) - { + out IEnumerable deleted, out IEnumerable added) { HashSet new_grid_map = new HashSet(new_grid.get_ordered_expirations()), old_grid_map = new HashSet(old_grid.get_ordered_expirations()), del, add; - CollectionHelper.compare_hashsets(new_grid_map, old_grid_map, out del, out add); + CollectionHelper.compare_hashsets(new_grid_map, old_grid_map, out del, out add); deleted = del; added = add; } - public static bool cols_changed(VolSurfaceDisplayGrid d1, VolSurfaceDisplayGrid d2) - { + public static bool cols_changed(VolSurfaceDisplayGrid d1, VolSurfaceDisplayGrid d2) { IEnumerable d1_extra, d2_extra; compare_cols(d1, d2, out d1_extra, out d2_extra); return d1_extra.Count() > 0 || d2_extra.Count() > 0; @@ -88,8 +85,7 @@ namespace mbts.ui.controls /// Returns the col name differences (it will generally be very rare, but for instance when a point gets added /// to a polynomial or the spline model, d1 or d2 wont be empty) public static void compare_cols(VolSurfaceDisplayGrid d1, VolSurfaceDisplayGrid d2, - out IEnumerable d1_extra, out IEnumerable d2_extra) - { + out IEnumerable d1_extra, out IEnumerable d2_extra) { HashSet d1_exp_map = new HashSet(d1.get_ordered_columns()), d2_exp_map = new HashSet(d2.get_ordered_columns()), del, add; @@ -104,12 +100,10 @@ namespace mbts.ui.controls /// Returns the differernce between two VolSurfaceDisplay's. /// It only returns the elements that are present in both /// and are different. - public static IEnumerable> compare_data(VolSurfaceDisplayGrid d1, VolSurfaceDisplayGrid d2) - { - List> rv = new List> (); - foreach (VolSurfaceDisplayGridExpiration exp in CollectionHelper.append_arrays (d1.get_ordered_expirations(), d2.get_ordered_expirations())) - foreach (VolSurfaceDisplayGridColumn col in CollectionHelper.append_arrays(d1.get_ordered_columns(), d2.get_ordered_columns())) - { + public static IEnumerable> compare_data(VolSurfaceDisplayGrid d1, VolSurfaceDisplayGrid d2) { + List> rv = new List>(); + foreach (VolSurfaceDisplayGridExpiration exp in CollectionHelper.append_arrays(d1.get_ordered_expirations(), d2.get_ordered_expirations())) + foreach (VolSurfaceDisplayGridColumn col in CollectionHelper.append_arrays(d1.get_ordered_columns(), d2.get_ordered_columns())) { object d1_data, d2_data; if (d1.get_grid_data(exp, col, out d1_data) && d2.get_grid_data(exp, col, out d2_data) && d1 != d2) rv.Add(Tuple.Create(exp, col)); @@ -119,11 +113,10 @@ namespace mbts.ui.controls #endregion #region ICloneable - public object Clone() - { - Dictionary> data = new Dictionary> (); + public object Clone() { + Dictionary> data = new Dictionary>(); foreach (KeyValuePair> p in _data_map) - data.Add (p.Key, new Dictionary (p.Value)); + data.Add(p.Key, new Dictionary(p.Value)); return new VolSurfaceDisplayGrid(new List(_ordered_expirations), new List(_ordered_columns), data); @@ -137,12 +130,10 @@ namespace mbts.ui.controls #endregion #region ICellDataStore - public string read(VolSurfaceDisplayGridExpiration row, IDataGridDisplayModelColumn col) - { + public string read(VolSurfaceDisplayGridExpiration row, IDataGridDisplayModelColumn col) { VolSurfaceDisplayGridColumn grid_col = col as VolSurfaceDisplayGridColumn; grid_col = grid_col != null ? (_column_map.TryGetValue(grid_col.unique_col_name, out grid_col) ? grid_col : null) : null; - if (grid_col != null) - { + if (grid_col != null) { object value; if (get_grid_data(row, grid_col, out value)) return grid_col.format(value); @@ -150,29 +141,24 @@ namespace mbts.ui.controls return string.Empty; } - public bool write(VolSurfaceDisplayGridExpiration row, IDataGridDisplayModelColumn col, string value) - { + public bool write(VolSurfaceDisplayGridExpiration row, IDataGridDisplayModelColumn col, string value) { VolSurfaceDisplayGridTextInputColumn grid_col = col as VolSurfaceDisplayGridTextInputColumn; return grid_col != null ? set_grid_data(row, grid_col, grid_col.parse(value)) : false; } - public object get_display_info(VolSurfaceDisplayGridExpiration row, IDataGridDisplayModelColumn col) - { + public object get_display_info(VolSurfaceDisplayGridExpiration row, IDataGridDisplayModelColumn col) { return null; // ?? //return read(row, col); } - public void handle_tick(VolSurfaceDisplayGridExpiration row, IDataGridDisplayModelColumn col, TickDirection tick, out string new_value) - { + public void handle_tick(VolSurfaceDisplayGridExpiration row, IDataGridDisplayModelColumn col, TickDirection tick, out string new_value) { VolSurfaceDisplayGridColumn mapped_col = col as VolSurfaceDisplayGridColumn; mapped_col = mapped_col != null ? (_column_map.TryGetValue(mapped_col.unique_col_name, out mapped_col) ? mapped_col : null) : null; VolSurfaceDisplayGridTextInputColumn grid_col = mapped_col as VolSurfaceDisplayGridTextInputColumn; - new_value = String.Empty; - if (grid_col != null) - { + new_value = String.Empty; + if (grid_col != null) { object data; - if (get_grid_data(row, grid_col, out data)) - { + if (get_grid_data(row, grid_col, out data)) { data = grid_col.tick_move(data, tick == TickDirection.UP); new_value = grid_col.format(data); set_grid_data(row, grid_col, data); @@ -180,29 +166,49 @@ namespace mbts.ui.controls } } - public bool can_tick(VolSurfaceDisplayGridExpiration row, IDataGridDisplayModelColumn col, TickDirection tick) - { + public bool can_tick(VolSurfaceDisplayGridExpiration row, IDataGridDisplayModelColumn col, TickDirection tick) { return true; } #endregion - internal void set_grid_data_text(VolSurfaceDisplayGridExpiration exp, string col_name, string formatted_data) - { + internal void set_grid_data_text(VolSurfaceDisplayGridExpiration exp, string col_name, string formatted_data) { VolSurfaceDisplayGridColumn grid_col; if (_column_map.TryGetValue(col_name, out grid_col)) write(exp, grid_col, formatted_data); } - internal bool set_grid_data(VolSurfaceDisplayGridExpiration exp, VolSurfaceDisplayGridColumn col, object data) - { + internal bool set_grid_data(VolSurfaceDisplayGridExpiration exp, VolSurfaceDisplayGridColumn col, object data) { IDictionary exp_data; if (_data_map.TryGetValue(exp, out exp_data)) - if (exp_data.ContainsKey(col)) - { + if (exp_data.ContainsKey(col)) { exp_data[col] = data; return true; } return false; } + + // internal string log_string { + // get { + // Func trim_leading_comma = (s) => { + // if (!s.IsNullOrEmpty() && s.EndsWith(",")) { + // return s.Remove(s.Length - 1, 1); + // } + // return s; + // }; + // Func, string> log_exp = (map) => { + // string rv = String.Empty; + // foreach (var kv in map) { + // string val_string = kv.Value == null ? "Null" : kv.Value.ToString(); + // rv += $"{kv.Key.display_name}:{val_string},"; + // } + // return trim_leading_comma(rv); + // }; + // string rv = String.Empty; + // foreach (var kv in _data_map) { + // rv += $"Exp:{kv.Key.expiration.ToShortDateString()} Data:{log_exp(kv.Value)},"; + // } + // return trim_leading_comma(rv); + // } + // } } } \ No newline at end of file diff --git a/src/client/spark/AW2/Grid/VolSurfaceDisplayUtilities.cs b/src/client/spark/AW2/Grid/VolSurfaceDisplayUtilities.cs index 68d18bc23..d95f47dbf 100644 --- a/src/client/spark/AW2/Grid/VolSurfaceDisplayUtilities.cs +++ b/src/client/spark/AW2/Grid/VolSurfaceDisplayUtilities.cs @@ -4,28 +4,22 @@ using System.Linq; using System.Text; using System.Threading.Tasks; -namespace mbts.ui.controls -{ - public class VolSurfaceDisplayUtilities - { - public static double parse_double(object obj) - { +namespace mbts.ui.controls { + class VolSurfaceDisplayUtilities { + public static double parse_double(object obj) { obj = obj ?? Double.NaN; double rv = obj is Double ? (double)obj : (Double.TryParse(obj.ToString(), out rv) ? rv : Double.NaN); return rv; } - public static bool parse_boolean(object obj, bool def_value) - { + public static bool parse_boolean(object obj, bool def_value) { bool rv; rv = Boolean.TryParse(obj == null ? String.Empty : obj.ToString(), out rv) ? rv : def_value; return rv; } - public static Func get_parse_double(double multiplier) - { - return (text) => - { + public static Func get_parse_double(double multiplier) { + return (text) => { double rv = Double.NaN; rv = Double.TryParse(text, out rv) ? rv : Double.NaN; rv /= multiplier; @@ -33,45 +27,35 @@ namespace mbts.ui.controls }; } - public static Func get_double_tostring(double tick_base, double tick_interval, double multiplier) - { - return (data) => - { - if (data != null && data is double) - { + public static Func get_double_tostring(double tick_base, double tick_interval, double multiplier) { + return (data) => { + if (data != null && data is double) { double d_data = (double)data; d_data *= multiplier; return Double.IsNaN(d_data) ? String.Empty : _to_string(d_data, tick_base, tick_interval); - } - else + } else return String.Empty; }; } - public static Func get_double_tickmove(double tick_base, double tick_move, double multiplier) - { - return (data, is_up) => - { - if (data != null && data is double) - { + public static Func get_double_tickmove(double tick_base, double tick_move, double multiplier) { + return (data, is_up) => { + if (data != null && data is double) { double d_data = (double)data; d_data *= multiplier; d_data = is_up ? d_data + (tick_move / tick_base) : d_data - (tick_move / tick_base); d_data /= multiplier; return d_data; - } - else + } else return data; }; } public static VolSurfaceDisplayGridColumn get_double_output_col(string group, string name, string display_name, double tick_base, double tick_interval, double multiplier, - VolSurfaceMacroGridSettings grid_settings) - { + VolSurfaceMacroGridSettings grid_settings) { BTSTabularGridCellConfiguration col_config = _get_col_config(name, grid_settings); - if (col_config != null) - { + if (col_config != null) { _assign(col_config.tick_base, ref tick_base); _assign(col_config.tick_interval, ref tick_interval); _assign(col_config.multiplier, ref multiplier); @@ -79,15 +63,13 @@ namespace mbts.ui.controls return new VolSurfaceDisplayGridTextOutputColumn(group, name, display_name, null, get_double_tostring(tick_base, tick_interval, multiplier), get_parse_double(multiplier)); - } + } public static VolSurfaceDisplayGridColumn get_double_input_col(string group, string name, string display_name, double tick_base, double tick_interval, double tick_move, double multiplier, - VolSurfaceMacroGridSettings grid_settings) - { + VolSurfaceMacroGridSettings grid_settings) { BTSTabularGridCellConfiguration col_config = _get_col_config(name, grid_settings); - if (col_config != null) - { + if (col_config != null) { _assign(col_config.tick_base, ref tick_base); _assign(col_config.tick_interval, ref tick_interval); _assign(col_config.tick_move, ref tick_move); @@ -99,20 +81,17 @@ namespace mbts.ui.controls get_double_tickmove(tick_base, tick_move, multiplier)); } - private static BTSTabularGridCellConfiguration _get_col_config(string col_name, VolSurfaceMacroGridSettings grid_setting) - { - return grid_setting != null ? grid_setting.get_col_setting(col_name) : null; + private static BTSTabularGridCellConfiguration _get_col_config(string col_name, VolSurfaceMacroGridSettings grid_setting) { + return grid_setting != null ? grid_setting.get_cell_conf(col_name) : null; } - private static string _to_string (double d, double tick_base, double tick_interval) - { - return d.ToString(); + private static string _to_string(double d, double tick_base, double tick_interval) { + return d.ToString(); // TODO // return TickConverter2.to_tick(d, new TickConverter2.TickTypeInfo(tick_base == 100.0, (int)tick_base, tick_interval, false)); } - private static void _assign(double d, ref double v) - { + private static void _assign(double d, ref double v) { if (_is_valid(d)) v = d; } diff --git a/src/client/spark/AW2/Grid/VolSurfaceMacroGridSettings.cs b/src/client/spark/AW2/Grid/VolSurfaceMacroGridSettings.cs index abad18f24..f4466910f 100644 --- a/src/client/spark/AW2/Grid/VolSurfaceMacroGridSettings.cs +++ b/src/client/spark/AW2/Grid/VolSurfaceMacroGridSettings.cs @@ -1,34 +1,43 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using mbts; -using mbts.ui.controls; -using mbts.ui.shell; +namespace mbts.ui.controls { + using System; + using System.Collections.Generic; + using System.Linq; -namespace mbts.ui.controls -{ + using mbts.ui.settings; + using mbts.ui.shell; -[ProtoBuf.ProtoContract()] - public class VolSurfaceMacroGridSettings : ICloneable - { - [ProtoBuf.ProtoMember(1)] - public BTSTabularGridConfiguration configuration { get; set; } + using ProtoBuf; - public object Clone() { - return ProtoBufSerializationHelper.clone_protobuf(this); + [ProtoContract] + class VolSurfaceMacroGridSettings : ICloneable { + public static VolSurfaceMacroGridSettings Default => + new() { + configuration = new GridSettings() + }; + + [ProtoMember(1)] + public GridSettings configuration { get; set; } + + /// This should be the same size as ; + /// the cell configurations are associated with the + /// in the same corresponding index. + [ProtoMember(2)] + public List cell_settings { get; } = new List(); + + public GridColumnSettings get_col_setting(string col_name) => + GridSettingsHelper.try_find_column(configuration.columns, col_name, out var res) ? res : null; + + public BTSTabularGridCellConfiguration get_cell_conf(string col_name) { + if (cell_settings.Count != configuration.columns.Count) { + throw new InvalidOperationException( + $"{nameof(cell_settings)} doesn't have the same number of " + + $"elements as {nameof(configuration)}.${nameof(GridSettings.columns)}"); + } + return GridSettingsHelper.try_find_column(configuration.columns, col_name, out var _, out var idx) ? + cell_settings[idx] : null; } - private IDictionary _col_setting_map = null; - - public BTSTabularGridCellConfiguration get_col_setting(string col_name) - { - if (_col_setting_map == null) - _col_setting_map = configuration != null ? configuration.column_configurations.ToDictionary(c => c.name, c => c.cell_configuration) : new Dictionary(); - BTSTabularGridCellConfiguration rv = _col_setting_map.TryGetValue(col_name, out rv) ? rv : null; - return rv; - } + public object Clone() => + ProtoBufSerializationHelper.clone_protobuf(this); } - -} \ No newline at end of file +} diff --git a/src/client/spark/AW2/Misc/OptionDriverPriceMap.cs b/src/client/spark/AW2/Misc/OptionDriverPriceMap.cs index 08e20aec4..e3c2fc0b6 100644 --- a/src/client/spark/AW2/Misc/OptionDriverPriceMap.cs +++ b/src/client/spark/AW2/Misc/OptionDriverPriceMap.cs @@ -1,17 +1,17 @@ using System; using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; using mbts.analytics; using bts.api; namespace mbts.spark { + // All driver prices for an option symbol public class OptionDriverPriceMap { public readonly String option_symbol = null; - public readonly IDictionary> exp_price_map = null; + public readonly IDictionary> + exp_price_map = null; public OptionDriverPriceMap(string option_symbol_a, - IDictionary> exp_price_map_a) { + IDictionary> + exp_price_map_a) { option_symbol = option_symbol_a; exp_price_map = exp_price_map_a; } diff --git a/src/client/spark/AW2/Misc/SystemContractData.cs b/src/client/spark/AW2/Misc/SystemContractData.cs index 487210521..11ad921dd 100644 --- a/src/client/spark/AW2/Misc/SystemContractData.cs +++ b/src/client/spark/AW2/Misc/SystemContractData.cs @@ -167,6 +167,11 @@ namespace mbts.spark { .ToDictionary(kv => kv.Key.expiration, kv => kv.Value.Select(k => k.strike)); } + public IDictionary> get_option_strikes(HashSet option_names) { + return strike_map.Where(kv => option_names.Contains(kv.Key.symbol)) + .ToDictionary(kv => kv.Key, kv => kv.Value.Select(k => k.strike)); + } + public Nullable get_exp_sec_id(SecurityExpiration sec_exp) { UInt32 rv; if (exp_map.TryGetValue(sec_exp, out rv)) { diff --git a/src/client/spark/AW2/Misc/ThreadedBlackboard.cs b/src/client/spark/AW2/Misc/ThreadedBlackboard.cs index da3e86064..1c8ecdd5f 100644 --- a/src/client/spark/AW2/Misc/ThreadedBlackboard.cs +++ b/src/client/spark/AW2/Misc/ThreadedBlackboard.cs @@ -21,14 +21,16 @@ namespace mbts.spark { /// public class ThreadedBlackboard { private IBus _bus; - //public delegate void OnBBData(object tag, object data); + private List _subs = new List(); + private HashSet _tag_map = new HashSet(); public event Action data_callback = (t, v) => { }; public event Action timer_callback = () => { }; private IDictionary _cache = new Dictionary(); - + private static int _tid() {return VolSurfaceTroubleshootingFunctions.tid();} public ThreadedBlackboard(IBus bus) { + bts.Log.Ui.info($"ThreadedBlackBoard.cons tid:{ _tid()}"); _bus = bus; subscribe(SparkTags.SparkTimer); System.Threading.Thread timer_thread = new System.Threading.Thread(() => { @@ -46,20 +48,40 @@ namespace mbts.spark { #region Templatized sub/write public void subscribe(ITag tag) { + if (_tag_map.Contains(tag)) { + return; + } + _tag_map.Add(tag); + bts.Log.Ui.info($"ThreadedBlackBoard.subscribe tag:{tag} tid:{ _tid()}"); var observable = _bus.subscribe(tag).OnDispatcher().Subscribe( data => _on_bus_data(tag, data)); + _subs.Add(observable); } + private static string _data_string(T data) { + string rv = "Null"; + try { + rv = data.ToString(); + } catch (Exception ex) { + bts.Log.Ui.error($"ThreadedBlackBoard data:Null ex:{ex.Message}"); + } + return rv; + } public void post(ITag tag, T data, bool block_until_written = false) { + bts.Log.Ui.info($"ThreadedBlackBoard.post tag:{tag} data:{_data_string(data)} " + + $"tid:{_tid()}"); _cache[tag] = data; _bus.post(tag, data); } private void _on_bus_data(ITag tag, T data) { + _cache[tag] = data; if (tag == SparkTags.SparkTimer) { timer_callback(); return; } + bts.Log.Ui.info($"ThreadedBlackBoard._on_bus_data tag:{tag} data:{_data_string(data)} " + + $"tid:{_tid()}"); data_callback(tag, data); } #endregion diff --git a/src/client/spark/AW2/Misc/VolSurfaceTroubleshootingFunctions.cs b/src/client/spark/AW2/Misc/VolSurfaceTroubleshootingFunctions.cs new file mode 100644 index 000000000..de0cf60c3 --- /dev/null +++ b/src/client/spark/AW2/Misc/VolSurfaceTroubleshootingFunctions.cs @@ -0,0 +1,109 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using mbts; +using mbts.analytics; +using mbts.ui.controls; +using mbts.ui.shell; +using mbts.spark; +using bts.utils; +using bts.api; + +namespace mbts.spark { + /// This contains the list of global values for the vol + /// surface (whereas VolSurfaceDisplayGrid has exp keyed + /// values) + public static class VolSurfaceTroubleshootingFunctions { + public static string log_string(this VolSurfaceInput vs_inp) { + string rv = "Null"; + if (vs_inp.surface_parameters != null && vs_inp.surface_parameters.curve_parameters_map != null) { + rv = String.Empty; + foreach (var kv in vs_inp.surface_parameters.curve_parameters_map) { + var exp = kv.Item1; + var exp_data = kv.Item2; + double atm_vol = VolSurfaceDataFunctions.get_atm_vol(vs_inp.surface_settings, exp_data); + rv += $"exp:{exp.expiration.ToShortDateString()} atm_vol:{atm_vol} \n"; + } + } + return rv; + } + + public static string log_string(this VolSurfaceOutput vs_out) { + if (vs_out == null) { + return "Null"; + } + var vs_inp = vs_out.volsurface_input; + string rv = "vs_inp:" + vs_inp == null ? "Null" : vs_inp.log_string() + "\n"; + rv += "vs_output:" + "\n"; + if (vs_out.exp_output_map != null) { + foreach (var exp_kv in vs_out.exp_output_map) { + var exp = exp_kv.Key; + var exp_output = exp_kv.Value; + foreach (var vol in exp_output.strike_vol_map) { + rv += $"{exp},{vol.Key}:{vol.Value}" + ","; + } + rv += "\n"; + } + } + return rv; + } + + private static string _trim_leading_char(string s, char c) { + if (!s.IsNullOrEmpty() && s.EndsWith(c)) { + return s.Remove(s.Length - 1, 1); + } + return s; + } + + internal static string log_string(this VolSurfaceDisplayModel.DisplayModelData dm_data) { + string rv = String.Empty; + string global_grid_str = dm_data.global_grid == null ? "Null" : dm_data.global_grid.log_string(); + rv += $"global_grid: {global_grid_str} \n"; + string exp_grid_str = dm_data.exp_grid == null ? "Null" : dm_data.exp_grid.log_string(); + rv += $"exp_grid: {exp_grid_str} \n"; + return rv; + } + + public static string log_string(this VolSurfaceDisplayGlobalGrid ggrid) { + string rv = String.Empty; + foreach (var col in ggrid.get_ordered_columns()) { + object col_data = null; + ggrid.get_grid_data(col, out col_data); + string col_data_str = col_data == null ? "Null" : col_data.ToString(); + rv += $"{col.display_name}:{col_data_str} "; + } + return rv; + } + + internal static string log_string(this VolSurfaceDisplayGrid dgrid) { + Func, string> log_exp = (map) => { + string rv = String.Empty; + foreach (var kv in map) { + string val_string = kv.Value == null ? "Null" : kv.Value.ToString(); + rv += $"{kv.Key.display_name}:{val_string},"; + } + return _trim_leading_char(rv, ','); + }; + string rv = String.Empty; + foreach (var kv in dgrid.data_map) { + rv += $"Exp:{kv.Key.expiration.ToShortDateString()} Data:{log_exp(kv.Value)},"; + } + return _trim_leading_char(rv, ','); + } + + internal static string log_string(this OptionDriverPriceMap map) { + string rv = String.Empty; + foreach (var kv in map.exp_price_map) { + var t = kv.Value; + rv += $"{kv.Key.ToString()}:{t.Item1.Id},{t.Item2.get_mid_price()},"; + } + return _trim_leading_char(rv, ','); + } + + internal static int tid() { + return System.Threading.Thread.CurrentThread.ManagedThreadId; + } + } +} diff --git a/src/client/spark/AW2/UIAdapters/DiagnosticsUIAdapter.cs b/src/client/spark/AW2/UIAdapters/DiagnosticsUIAdapter.cs index a9fcbdf28..c82537d22 100644 --- a/src/client/spark/AW2/UIAdapters/DiagnosticsUIAdapter.cs +++ b/src/client/spark/AW2/UIAdapters/DiagnosticsUIAdapter.cs @@ -17,7 +17,7 @@ namespace mbts.ui.controls return rv; } } - public class DiagnosticsUIAdapter : IReadWriteGridAdapter + class DiagnosticsUIAdapter : IReadWriteGridAdapter { private const string _group = "Diagnostics"; private readonly VolSurfaceDisplayGridColumn _atm_straddle_col, _rr_col, _strangle_col, _put_bf_col, _call_bf_col, diff --git a/src/client/spark/AW2/UIAdapters/DriverUIAdapter.cs b/src/client/spark/AW2/UIAdapters/DriverUIAdapter.cs index 206335ed4..1bf1ba759 100644 --- a/src/client/spark/AW2/UIAdapters/DriverUIAdapter.cs +++ b/src/client/spark/AW2/UIAdapters/DriverUIAdapter.cs @@ -8,7 +8,7 @@ using mbts.spark; namespace mbts.ui.controls { - public class DriverUIAdapter : IReadWriteGridAdapter + class DriverUIAdapter : IReadWriteGridAdapter { private const string _group = "Driver"; private readonly VolSurfaceDisplayGridColumn _fwd_col, _ref_fwd_col, _live_driver_col, _driver_override_col; diff --git a/src/client/spark/AW2/UIAdapters/DualQuadraticModelUIAdapter.cs b/src/client/spark/AW2/UIAdapters/DualQuadraticModelUIAdapter.cs index 5495bf62f..494c97431 100644 --- a/src/client/spark/AW2/UIAdapters/DualQuadraticModelUIAdapter.cs +++ b/src/client/spark/AW2/UIAdapters/DualQuadraticModelUIAdapter.cs @@ -8,7 +8,7 @@ using mbts.spark; namespace mbts.ui.controls { - public class DualQuadraticModelUIAdapter : IReadWriteGridAdapter + class DualQuadraticModelUIAdapter : IReadWriteGridAdapter { private const string _group = "Main Curve"; private readonly VolSurfaceDisplayGridColumn _put_wing_strike_col, _put_slope_col, _put_curvature_col, @@ -99,4 +99,4 @@ namespace mbts.ui.controls }; } } -} \ No newline at end of file +} diff --git a/src/client/spark/AW2/UIAdapters/ExplicitSlopeWingUIAdapter.cs b/src/client/spark/AW2/UIAdapters/ExplicitSlopeWingUIAdapter.cs index ca902c8c5..5390018cf 100644 --- a/src/client/spark/AW2/UIAdapters/ExplicitSlopeWingUIAdapter.cs +++ b/src/client/spark/AW2/UIAdapters/ExplicitSlopeWingUIAdapter.cs @@ -8,7 +8,7 @@ using mbts.spark; namespace mbts.ui.controls { - public class ExplicitSlopeWingUIAdapter : IReadWriteGridAdapter + class ExplicitSlopeWingUIAdapter : IReadWriteGridAdapter { private const string _group = "Wings"; private VolSurfaceDisplayGridColumn _p_wing_slope, _c_wing_slope, _p_wing_decay, _c_wing_decay; diff --git a/src/client/spark/AW2/UIAdapters/ImplicitSlopeWingUIAdapter.cs b/src/client/spark/AW2/UIAdapters/ImplicitSlopeWingUIAdapter.cs index bb1ae5a11..c7f2be58f 100644 --- a/src/client/spark/AW2/UIAdapters/ImplicitSlopeWingUIAdapter.cs +++ b/src/client/spark/AW2/UIAdapters/ImplicitSlopeWingUIAdapter.cs @@ -8,7 +8,7 @@ using mbts.spark; namespace mbts.ui.controls { - public class ImplicitSlopeWingUIAdapter : IReadWriteGridAdapter + class ImplicitSlopeWingUIAdapter : IReadWriteGridAdapter { private const string _group = "Wings"; private VolSurfaceDisplayGridColumn _p_wing_max, _c_wing_max; diff --git a/src/client/spark/AW2/UIAdapters/MiscColsUIAdapter.cs b/src/client/spark/AW2/UIAdapters/MiscColsUIAdapter.cs index 2268122b7..969f55239 100644 --- a/src/client/spark/AW2/UIAdapters/MiscColsUIAdapter.cs +++ b/src/client/spark/AW2/UIAdapters/MiscColsUIAdapter.cs @@ -8,7 +8,7 @@ using mbts.spark; namespace mbts.ui.controls { - public class MiscColsUIAdapter : IReadWriteGridAdapter + class MiscColsUIAdapter : IReadWriteGridAdapter { private const string _group = "General"; private readonly VolSurfaceDisplayGridColumn _time_shift_col, _biz_time_output_col, _vol_time_years_output_col, _vol_time_days_per_year, diff --git a/src/client/spark/AW2/UIAdapters/ParabolicVolPathUIAdapter.cs b/src/client/spark/AW2/UIAdapters/ParabolicVolPathUIAdapter.cs index e1dcb1532..29893e269 100644 --- a/src/client/spark/AW2/UIAdapters/ParabolicVolPathUIAdapter.cs +++ b/src/client/spark/AW2/UIAdapters/ParabolicVolPathUIAdapter.cs @@ -8,7 +8,7 @@ using mbts.spark; namespace mbts.ui.controls { - public class ParabolicVolPathUIAdapter : IReadWriteGridAdapter + class ParabolicVolPathUIAdapter : IReadWriteGridAdapter { private const string _group = "Vol Path"; private readonly VolSurfaceDisplayGridColumn _down_market_move, _down_market_vol_move, _up_market_move, _up_market_vol_move, _max_vol_increase, _max_vol_decrease; diff --git a/src/client/spark/AW2/UIAdapters/PolynomialModelUIAdapter.cs b/src/client/spark/AW2/UIAdapters/PolynomialModelUIAdapter.cs index 1696b7d74..94ef4cceb 100644 --- a/src/client/spark/AW2/UIAdapters/PolynomialModelUIAdapter.cs +++ b/src/client/spark/AW2/UIAdapters/PolynomialModelUIAdapter.cs @@ -8,7 +8,7 @@ using mbts.spark; namespace mbts.ui.controls { - public class PolynomialModelUIAdapter : IReadWriteGridAdapter + class PolynomialModelUIAdapter : IReadWriteGridAdapter { private const string _group = "Main Curve"; private readonly List> _put_cols, _call_cols; @@ -130,4 +130,4 @@ namespace mbts.ui.controls return rv; } } -} \ No newline at end of file +} diff --git a/src/client/spark/AW2/UIAdapters/SplineModelUIAdapter.cs b/src/client/spark/AW2/UIAdapters/SplineModelUIAdapter.cs index d43f5b90e..45f85fb85 100644 --- a/src/client/spark/AW2/UIAdapters/SplineModelUIAdapter.cs +++ b/src/client/spark/AW2/UIAdapters/SplineModelUIAdapter.cs @@ -8,7 +8,7 @@ using mbts.spark; namespace mbts.ui.controls { - public class SplineModelUIAdapter : IReadWriteGridAdapter + class SplineModelUIAdapter : IReadWriteGridAdapter { private const string _group = "Main Curve"; private readonly List> _put_cols, _call_cols; @@ -123,4 +123,4 @@ namespace mbts.ui.controls return rv; } } -} \ No newline at end of file +} diff --git a/src/client/spark/AW2/UIAdapters/StrikeConversionUIAdapter.cs b/src/client/spark/AW2/UIAdapters/StrikeConversionUIAdapter.cs index 7f4c316ed..ed5d10d16 100644 --- a/src/client/spark/AW2/UIAdapters/StrikeConversionUIAdapter.cs +++ b/src/client/spark/AW2/UIAdapters/StrikeConversionUIAdapter.cs @@ -8,7 +8,7 @@ using mbts.spark; namespace mbts.ui.controls { - public class StrikeConversionUIAdapter : IReadWriteGridAdapter + class StrikeConversionUIAdapter : IReadWriteGridAdapter { private const string _group = "Strike Dynamics"; private readonly VolSurfaceDisplayGridColumn _conv_fwd_slider_col, _conv_vol_slider_col, _conv_fwd_col, _conv_vol_col; diff --git a/src/client/spark/AW2/UIAdapters/TwoWaySlopeVolPathUIAdapter.cs b/src/client/spark/AW2/UIAdapters/TwoWaySlopeVolPathUIAdapter.cs index a868f8ed9..3bb4c9e22 100644 --- a/src/client/spark/AW2/UIAdapters/TwoWaySlopeVolPathUIAdapter.cs +++ b/src/client/spark/AW2/UIAdapters/TwoWaySlopeVolPathUIAdapter.cs @@ -8,7 +8,7 @@ using mbts.spark; namespace mbts.ui.controls { - public class TwoWaySlopeVolPathUIAdapter : IReadWriteGridAdapter + class TwoWaySlopeVolPathUIAdapter : IReadWriteGridAdapter { private const string _group = "Vol Path"; private readonly VolSurfaceDisplayGridColumn _down_slope_col, _up_slope_col, _max_vol_inc_col, _max_vol_dec_col, _joint_speed_col; diff --git a/src/client/spark/AW2/UIAdapters/VolSurfaceUIAdapter.cs b/src/client/spark/AW2/UIAdapters/VolSurfaceUIAdapter.cs index ffe88f364..e01a66f7f 100644 --- a/src/client/spark/AW2/UIAdapters/VolSurfaceUIAdapter.cs +++ b/src/client/spark/AW2/UIAdapters/VolSurfaceUIAdapter.cs @@ -11,7 +11,7 @@ using bts; namespace mbts.ui.controls { - public class VolSurfaceUIAdapter + class VolSurfaceUIAdapter { private class MyComparerWrapper : IComparer { @@ -150,4 +150,4 @@ namespace mbts.ui.controls return rv; } } -} \ No newline at end of file +} diff --git a/src/client/spark/AW2/UISettings/VolSurfaceGraphSettings.cs b/src/client/spark/AW2/UISettings/VolSurfaceGraphSettings.cs new file mode 100644 index 000000000..31e7c75aa --- /dev/null +++ b/src/client/spark/AW2/UISettings/VolSurfaceGraphSettings.cs @@ -0,0 +1,153 @@ +using mbts.ui; +using mbts.ui.controls.graph; +using mbts.ui.shell; + +using ProtoBuf; + +using System; +using System.Collections.Generic; + +namespace mbts.spark { + [ProtoContract] + class VolSurfaceGraphSettings : IEquatable, ICloneable { + public static VolSurfaceGraphSettings get_default() { + return new VolSurfaceGraphSettings { + put_control_points = new ScatterSeriesSettings { + color = BTSColors.VolSurfaceGraph.put_special, + shape = MarkerShape.Circle, + size = 3.0 + }, + atm = new ScatterSeriesSettings { + shape = MarkerShape.Diamond, + size = 4.5, + color = BTSColors.VolSurfaceGraph.main_curve_atm + }, + call_control_points = new ScatterSeriesSettings { + color = BTSColors.VolSurfaceGraph.call_special, + shape = MarkerShape.Circle, + size = 3.0 + }, + put_wing = new LineSeriesSettings { + color = BTSColors.VolSurfaceGraph.wing, + stroke_thickness = 1.5 + }, + inner_curve = new LineSeriesSettings { + color = BTSColors.VolSurfaceGraph.main_curve, + stroke_thickness = 1.5 + }, + call_wing = new LineSeriesSettings { + color = BTSColors.VolSurfaceGraph.wing, + stroke_thickness = 1.5 + }, + implied_puts = new ScatterSeriesSettings { + shape = MarkerShape.Circle, + size = 1.5, + color = BTSColors.VolSurfaceGraph.implied_put + }, + implied_atm = new ScatterSeriesSettings { + shape = MarkerShape.Cross, + size = 4.5, + color = BTSColors.VolSurfaceGraph.implied_atm + }, + implied_calls = new ScatterSeriesSettings { + shape = MarkerShape.Circle, + size = 1.5, + color = BTSColors.VolSurfaceGraph.implied_call + }, + vol_path = get_default_vol_path_settings(), + exp_bounds = new ExpGraphBounds[0] + }; + } + + public static LineSeriesSettings get_default_vol_path_settings() { + return new LineSeriesSettings { + color = BTSColors.VolSurfaceGraph.vol_path, + stroke_thickness = 1.5 + }; + } + + [ProtoMember(1)] + public ScatterSeriesSettings call_control_points; + [ProtoMember(2)] + public ScatterSeriesSettings put_control_points; + + [ProtoMember(3)] + public LineSeriesSettings put_wing; + [ProtoMember(4)] + public LineSeriesSettings inner_curve; + [ProtoMember(5)] + public LineSeriesSettings call_wing; + + [ProtoMember(6)] + public ScatterSeriesSettings implied_puts; + [ProtoMember(7)] + public ScatterSeriesSettings implied_calls; + + [ProtoMember(8)] + public ScatterSeriesSettings atm; + [ProtoMember(9)] + public ScatterSeriesSettings implied_atm; + + [ProtoMember(10)] + public LineSeriesSettings vol_path; + + [ProtoMember(11)] + public ExpGraphBounds[] exp_bounds; + + //private LineSeriesSettings _vol_path; + //public LineSeriesSettings vol_path { + // get { + // return _vol_path ?? (_vol_path = new LineSeriesSettings { + // color = BTSColors.VolSurfaceGraph.vol_path, + // thickness = 1.5 + // }); + // } + //} + + public object Clone() => + ProtoBufSerializationHelper.clone_protobuf(this); + + public bool Equals(VolSurfaceGraphSettings other) => + other != null && + call_control_points.safe_equals(other.call_control_points) && + call_wing.safe_equals(other.call_wing) && + implied_calls.safe_equals(other.implied_calls) && + put_control_points.safe_equals(other.put_control_points) && + put_wing.safe_equals(other.put_wing) && + implied_puts.safe_equals(other.implied_puts) && + inner_curve.safe_equals(other.inner_curve) && + atm.safe_equals(other.atm) && + implied_atm.safe_equals(other.implied_atm) && + vol_path.safe_equals(other.vol_path) && + exp_bounds.safe_sequence_equals(other.exp_bounds); + + public override bool Equals(object obj) => + Equals(obj as VolSurfaceGraphSettings); + + public override int GetHashCode() => + GetType().GetHashCode(); + } + + [ProtoContract] + class ExpGraphBounds : IEquatable { + [ProtoMember(1)] + public SecurityExpirationProto exp { get; set; } + + [ProtoMember(2)] + public AxisBounds x_bounds { get; set; } + + [ProtoMember(3)] + public AxisBounds y_bounds { get; set; } + + public bool Equals(ExpGraphBounds other) => + other != null && + x_bounds.safe_equals(other.x_bounds) && + y_bounds.safe_equals(other.y_bounds); + + public override bool Equals(object obj) => + Equals(obj as ExpGraphBounds); + + public override int GetHashCode() => + GetType().GetHashCode(); + } +} diff --git a/src/client/spark/AW2/UISettings/VolSurfaceWindowSettings.cs b/src/client/spark/AW2/UISettings/VolSurfaceWindowSettings.cs new file mode 100644 index 000000000..f61c8eb79 --- /dev/null +++ b/src/client/spark/AW2/UISettings/VolSurfaceWindowSettings.cs @@ -0,0 +1,46 @@ +namespace mbts.spark { + using mbts.analytics; + + using ProtoBuf; + + using System.Collections.Generic; + + [ProtoContract] + class VolSurfaceWindowSettings { + public static int version => 1; + + [ProtoMember(1)] + public int id { get; set; } + + [ProtoMember(2)] + public ui.controls.graph.BTSGraphAxis vol_curve_x_axis { get; set; } + + [ProtoMember(3)] + public ui.controls.graph.BTSGraphAxis vol_curve_y_axis { get; set; } + + [ProtoMember(4)] + public List vol_curve_visible_series { get; set; } + + [ProtoMember(5)] + public List hidden_exps { get; set; } + + [ProtoMember(6)] + public bool show_mkt_implied_vol { get; set; } + + [ProtoMember(7)] + public VolSurfaceGraphSettings vol_curve_graph_settings { get; set; } + + [ProtoMember(8)] + public ui.controls.VolSurfaceMacroGridSettings macro_grid_settings { get; set; } + + public bool Equals(VolSurfaceWindowSettings other) => + other != null && + id == other.id && + vol_curve_x_axis.safe_equals(other.vol_curve_x_axis) && + vol_curve_y_axis.safe_equals(other.vol_curve_y_axis) && + vol_curve_visible_series.safe_sequence_equals(other.vol_curve_visible_series) && + hidden_exps.safe_sequence_equals(other.hidden_exps) && + show_mkt_implied_vol == other.show_mkt_implied_vol && + vol_curve_graph_settings.safe_equals(other.vol_curve_graph_settings); + } +} diff --git a/src/client/spark/AW2/View/VolSurfaceMacroControlView.xaml b/src/client/spark/AW2/View/VolSurfaceMacroControlView.xaml new file mode 100644 index 000000000..987c0ed89 --- /dev/null +++ b/src/client/spark/AW2/View/VolSurfaceMacroControlView.xaml @@ -0,0 +1,129 @@ + + + + + + + + + + + + + + Up + Down + + + + + + + + + diff --git a/src/client/spark/AW2/View/VolSurfaceMacroControlView.xaml.cs b/src/client/spark/AW2/View/VolSurfaceMacroControlView.xaml.cs new file mode 100644 index 000000000..b4aaf002d --- /dev/null +++ b/src/client/spark/AW2/View/VolSurfaceMacroControlView.xaml.cs @@ -0,0 +1,8 @@ +namespace mbts.ui.controls { + using System.Windows.Controls; + + partial class VolSurfaceMacroControlView : UserControl { + public VolSurfaceMacroControlView() => + InitializeComponent(); + } +} diff --git a/src/client/spark/AW2/View/VolSurfaceSettingsEditor.xaml b/src/client/spark/AW2/View/VolSurfaceSettingsEditor.xaml new file mode 100644 index 000000000..d4c224d09 --- /dev/null +++ b/src/client/spark/AW2/View/VolSurfaceSettingsEditor.xaml @@ -0,0 +1,1293 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Volatility Time Decays Automatically + + + + + If unchecked, volatility will be calculated according to the regular calendar year, like interest, + + and both will refer to the "Regular Calendar Days per Year" value below. + + + + + Use Business Calendar for Volatility + + + + + + Regular Calendar Days per Year + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Strike Axis + Wing Axis + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/client/spark/AW2/View/VolSurfaceSettingsEditor.xaml.cs b/src/client/spark/AW2/View/VolSurfaceSettingsEditor.xaml.cs new file mode 100644 index 000000000..a93a517ca --- /dev/null +++ b/src/client/spark/AW2/View/VolSurfaceSettingsEditor.xaml.cs @@ -0,0 +1,14 @@ +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Input; + +namespace mbts.ui.shell { + partial class VolSurfaceSettingsEditor : Window { + public VolSurfaceSettingsEditor() => + InitializeComponent(); + } +} diff --git a/src/client/spark/AW2/View/VolSurfaceShellModuleContent.xaml b/src/client/spark/AW2/View/VolSurfaceShellModuleContent.xaml new file mode 100644 index 000000000..be205f024 --- /dev/null +++ b/src/client/spark/AW2/View/VolSurfaceShellModuleContent.xaml @@ -0,0 +1,146 @@ + + + + + + + + + + + + + + + + + + diff --git a/src/client/spark/AW2/View/VolSurfaceShellModuleContent.xaml.cs b/src/client/spark/AW2/View/VolSurfaceShellModuleContent.xaml.cs new file mode 100644 index 000000000..293ccd9b6 --- /dev/null +++ b/src/client/spark/AW2/View/VolSurfaceShellModuleContent.xaml.cs @@ -0,0 +1,11 @@ +namespace mbts.ui.shell { + using System.Windows.Controls; + + /// + /// Interaction logic for VolSurfaceShellModuleContent.xaml + /// + partial class VolSurfaceShellModuleContent : UserControl { + public VolSurfaceShellModuleContent() => + InitializeComponent(); + } +} diff --git a/src/client/spark/AW2/View/VolSurfaceTimeDecayEditor.xaml b/src/client/spark/AW2/View/VolSurfaceTimeDecayEditor.xaml new file mode 100644 index 000000000..a36803d02 --- /dev/null +++ b/src/client/spark/AW2/View/VolSurfaceTimeDecayEditor.xaml @@ -0,0 +1,111 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/client/spark/AW2/View/VolSurfaceTimeDecayEditor.xaml.cs b/src/client/spark/AW2/View/VolSurfaceTimeDecayEditor.xaml.cs new file mode 100644 index 000000000..211c9a909 --- /dev/null +++ b/src/client/spark/AW2/View/VolSurfaceTimeDecayEditor.xaml.cs @@ -0,0 +1,33 @@ +using System; +using System.Windows.Controls; +using System.Windows.Input; +using System.Windows.Threading; + +namespace mbts.ui.shell { + /// + /// Interaction logic for VolSurfaceTimeDecayEditor.xaml + /// + partial class VolSurfaceTimeDecayEditor : UserControl { + public VolSurfaceTimeDecayEditor() => + InitializeComponent(); + + void decay_hours_Loaded(object sender, System.Windows.RoutedEventArgs e) { + var tb = (TextBox)sender; + tb.Focus(); + Keyboard.Focus(tb); + } + + void time_picker_KeyDown(object sender, KeyEventArgs e) { + if (e.Key == Key.Enter) { + e.Handled = true; + add_item_button.Focus(); + ICommand command = add_item_button.Command; + if (command != null) { + object parameter = add_item_button.CommandParameter; + if (add_item_button.Command.CanExecute(parameter)) + add_item_button.Command.Execute(parameter); + } + } + } + } +} diff --git a/src/client/spark/AW2/View/VolSurfaceView2.xaml b/src/client/spark/AW2/View/VolSurfaceView2.xaml new file mode 100644 index 000000000..b45fe6939 --- /dev/null +++ b/src/client/spark/AW2/View/VolSurfaceView2.xaml @@ -0,0 +1,649 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +