From 9055a6facb491affddf69a305730c418656263d2 Mon Sep 17 00:00:00 2001 From: Taha Afzal Date: Tue, 30 Nov 2021 22:39:57 -0500 Subject: [PATCH] More classes moved --- server_sln/spark_server.sln | 41 +++++ ...lSurfaceClientPrecomputedTheosPublisher.cs | 131 +++++++++++++++ ...ingleVolSurfaceClientTheosPublishHelper.cs | 51 ++++++ ...ingleVolSurfaceCommittedOutputRetriever.cs | 0 .../SingleVolSurfaceDataSource.cs | 0 .../SingleVolSurfaceGateway.cs | 0 .../spark/AW2/Bus/SingleVolSurfaceManager.cs | 51 ++++++ .../SingleVolSurfaceMarketImpliedVolSource.cs | 100 +++++------- .../SingleVolSurfaceNonVolDataSource.cs | 0 .../SingleVolSurfaceOptionDriverSource.cs | 0 .../Bus/SingleVolSurfaceRequestCalculator.cs | 131 +++++++++++++++ .../SingleVolSurfaceTheoSource.cs | 59 +++---- .../SingleVolSurfaceTimeSource.cs | 0 .../VolSurfacePrecomputedTheosProducer.cs | 151 ++++++++++++++++++ 14 files changed, 620 insertions(+), 95 deletions(-) create mode 100644 server_sln/spark_server.sln create mode 100644 src/client/spark/AW2/Bus/SingleVolSurfaceClientPrecomputedTheosPublisher.cs create mode 100644 src/client/spark/AW2/Bus/SingleVolSurfaceClientTheosPublishHelper.cs rename src/client/spark/AW2/Bus/{RequestResponse => }/SingleVolSurfaceCommittedOutputRetriever.cs (100%) rename src/client/spark/AW2/Bus/{RequestResponse => }/SingleVolSurfaceDataSource.cs (100%) rename src/client/spark/AW2/Bus/{RequestResponse => }/SingleVolSurfaceGateway.cs (100%) create mode 100644 src/client/spark/AW2/Bus/SingleVolSurfaceManager.cs rename src/client/spark/AW2/Bus/{RequestResponse => }/SingleVolSurfaceMarketImpliedVolSource.cs (76%) rename src/client/spark/AW2/Bus/{RequestResponse => }/SingleVolSurfaceNonVolDataSource.cs (100%) rename src/client/spark/AW2/Bus/{RequestResponse => }/SingleVolSurfaceOptionDriverSource.cs (100%) create mode 100644 src/client/spark/AW2/Bus/SingleVolSurfaceRequestCalculator.cs rename src/client/spark/AW2/Bus/{RequestResponse => }/SingleVolSurfaceTheoSource.cs (87%) rename src/client/spark/AW2/Bus/{RequestResponse => }/SingleVolSurfaceTimeSource.cs (100%) create mode 100644 src/client/spark/Analytics/Pricing/VolSurfacePrecomputedTheosProducer.cs diff --git a/server_sln/spark_server.sln b/server_sln/spark_server.sln new file mode 100644 index 000000000..6f8adbd5b --- /dev/null +++ b/server_sln/spark_server.sln @@ -0,0 +1,41 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.26730.10 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "sparkd", "src\server\sparkd\sparkd.vcxproj", "{BBBAFD38-312D-4A8D-9AF0-F2BDEE72CE6F}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libspark", "build\src\lib\libspark.vcxproj", "{502FD050-679A-3B50-B438-098500700919}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|x64 = Debug|x64 + MinSizeRel|x64 = MinSizeRel|x64 + Release|x64 = Release|x64 + RelWithDebInfo|x64 = RelWithDebInfo|x64 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {BBBAFD38-312D-4A8D-9AF0-F2BDEE72CE6F}.Debug|x64.ActiveCfg = Debug|x64 + {BBBAFD38-312D-4A8D-9AF0-F2BDEE72CE6F}.Debug|x64.Build.0 = Debug|x64 + {BBBAFD38-312D-4A8D-9AF0-F2BDEE72CE6F}.MinSizeRel|x64.ActiveCfg = Release|x64 + {BBBAFD38-312D-4A8D-9AF0-F2BDEE72CE6F}.MinSizeRel|x64.Build.0 = Release|x64 + {BBBAFD38-312D-4A8D-9AF0-F2BDEE72CE6F}.Release|x64.ActiveCfg = Release|x64 + {BBBAFD38-312D-4A8D-9AF0-F2BDEE72CE6F}.Release|x64.Build.0 = Release|x64 + {BBBAFD38-312D-4A8D-9AF0-F2BDEE72CE6F}.RelWithDebInfo|x64.ActiveCfg = Release|x64 + {BBBAFD38-312D-4A8D-9AF0-F2BDEE72CE6F}.RelWithDebInfo|x64.Build.0 = Release|x64 + {502FD050-679A-3B50-B438-098500700919}.Debug|x64.ActiveCfg = Debug|x64 + {502FD050-679A-3B50-B438-098500700919}.Debug|x64.Build.0 = Debug|x64 + {502FD050-679A-3B50-B438-098500700919}.MinSizeRel|x64.ActiveCfg = MinSizeRel|x64 + {502FD050-679A-3B50-B438-098500700919}.MinSizeRel|x64.Build.0 = MinSizeRel|x64 + {502FD050-679A-3B50-B438-098500700919}.Release|x64.ActiveCfg = Release|x64 + {502FD050-679A-3B50-B438-098500700919}.Release|x64.Build.0 = Release|x64 + {502FD050-679A-3B50-B438-098500700919}.RelWithDebInfo|x64.ActiveCfg = RelWithDebInfo|x64 + {502FD050-679A-3B50-B438-098500700919}.RelWithDebInfo|x64.Build.0 = RelWithDebInfo|x64 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {6A7249D7-B40C-4656-9347-60072D0B8FDB} + EndGlobalSection +EndGlobal diff --git a/src/client/spark/AW2/Bus/SingleVolSurfaceClientPrecomputedTheosPublisher.cs b/src/client/spark/AW2/Bus/SingleVolSurfaceClientPrecomputedTheosPublisher.cs new file mode 100644 index 000000000..432462adb --- /dev/null +++ b/src/client/spark/AW2/Bus/SingleVolSurfaceClientPrecomputedTheosPublisher.cs @@ -0,0 +1,131 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using mbts.analytics; +using System.Collections.Concurrent; +using System.IO; +using System.IO.Compression; +using bts; + +namespace mbts.spark { + /// + /// This is the client version of SingleVolSurfaceServerPrecomputedTheosProvider. + /// For a vs (and immutable list of option symbols) + /// It listens to + /// a. vol surface inputs + /// b. exp params (roll, rates etc) + /// c. securities (exp, strikes) for options in the vs + /// d. driver prices for options in vs + /// and passes the data above to VolSurfacePrecomputedTheosProducer where + /// the real calculations take place + /// + /// It also monitors "publish_from_client". If a vs has + /// that set to false, it no-ops the VolSurfacePrecomputedTheosProducer + /// by passing a null. Otherwise it brings the VolSurfacePrecomputedTheosProducer + /// to life, by passing a vs_input + /// + public class SingleVolSurfaceClientPrecomputedTheosPublisher : IDisposable { + private readonly int _vs_id; + private readonly IEnumerable _sym_map; + private readonly ThreadedBlackboard _threaded_bb; + private readonly object _in_vs_input_tag, _in_vs_nonvol_input_tag, _in_vs_contracts_tag, _in_vs_driver_price_map_tag, _in_vs_standard_time_tag, _in_ui_up_tag;//, _in_active_sheet_exps_tag, _in_bb_settings_tag; + private VolSurfacePrecomputedTheosProducer _theo_producer = new VolSurfacePrecomputedTheosProducer(); + private readonly SingleVolSurfaceClientTheosPublishHelper _local_publish_helper; + private readonly string _user; + + private VolSurfaceInput _vs_input = null; + + public SingleVolSurfaceClientPrecomputedTheosPublisher(int vs_id, ThreadedBlackboard threaded_bb, IEnumerable symbols) { + _vs_id = vs_id; + _sym_map = symbols; + _threaded_bb = threaded_bb; + // TODO + //_user = BlackboardSetup.current_user; + _user = String.Empty; + _theo_producer.on_theos += _theo_producer_on_theos; + _theo_producer.on_vols += _theo_producer_on_vols; + _in_vs_input_tag = SparkTags.VolSurfaceCommittedInputTag(vs_id); + _in_vs_nonvol_input_tag = SparkTags.VolSurfaceNonVolInputTag; + _in_vs_contracts_tag = SparkTags.VolSurfaceContractsTag(vs_id); + _in_vs_driver_price_map_tag = SparkTags.VolSurfaceOptionDriverTag(vs_id); + _in_vs_standard_time_tag = SparkTags.VolSurfaceStandardTimeTag(vs_id); + _in_ui_up_tag = SparkTags.VolSurfaceActiveUITag(_vs_id); + //_in_active_sheet_exps_tag = new NMSheetTags.NMSheetActiveExpirationsTag(); + _local_publish_helper = new SingleVolSurfaceClientTheosPublishHelper(vs_id, threaded_bb); + //_in_bb_settings_tag = new ClickTradeSettingsTag(); + _threaded_bb.add_to_subscription_list(_in_vs_input_tag, _in_vs_nonvol_input_tag, _in_vs_contracts_tag, _in_vs_driver_price_map_tag, _in_vs_standard_time_tag, _in_ui_up_tag/*, _in_active_sheet_exps_tag, _in_bb_settings_tag*/); + _threaded_bb.data_callback += _on_bb_data; + } + + #region Blackboard Callbacks + private void _on_bb_data(object tag, object data) { + if (_in_vs_input_tag.Equals(tag)) { + _vs_input = _threaded_bb.sec_thread_retrieve_from_cache(tag) as VolSurfaceInput; + _theo_producer.set_vol_data(_vs_input); + } else if (_in_vs_nonvol_input_tag.Equals(tag)) + _theo_producer.set_nonvol_parameters((_threaded_bb.sec_thread_retrieve_from_cache(tag) as VolSurfaceNonVolInput).exp_input_map); + else if (_in_vs_contracts_tag.Equals(tag)) // || _in_active_sheet_exps_tag.Equals(tag)) + _set_contracts(); + else if (_in_vs_driver_price_map_tag.Equals(tag)) + _theo_producer.set_driver_price(_threaded_bb.sec_thread_retrieve_from_cache(tag) as IDictionary); + else if (_in_vs_standard_time_tag.Equals(tag)) + _theo_producer.set_system_vol_time(_threaded_bb.sec_thread_retrieve_from_cache(tag) as VolSurfaceStandardTime); + } + + private void _set_contracts() { + // this was filtering contracts for TC2 + // var all_contracts = _threaded_bb.sec_thread_retrieve_from_cache(_in_vs_contracts_tag) as IDictionary>; + // if (all_contracts != null) { + // HashSet active_sheet_exp_map = _threaded_bb.sec_thread_retrieve_from_cache(_in_active_sheet_exps_tag) as HashSet; + // var filter_contracts = active_sheet_exp_map == null ? null : active_sheet_exp_map.Select(e => new VolSurfaceExpiration(e.nmsheet_symbol.option_name, e.option_expiration)).Where(e => all_contracts.ContainsKey(e)).ToDictionary(e => e, e => all_contracts[e]); + // _theo_producer.set_contracts(all_contracts, _compute_theos_for_active_sheet_expirations_only ? filter_contracts : null); + // } + } + + private bool _compute_theos_for_active_sheet_expirations_only { + // this was an optimization to calculate theos for visible expirations only + get { + return false; + // SymbolBasedSettingsManager click_trade_manager = _threaded_bb.sec_thread_retrieve_from_cache(_in_bb_settings_tag) as SymbolBasedSettingsManager; + // if (click_trade_manager != null) { + // GeneralClickTradeSettings gen_settings = click_trade_manager.fetch_associated_general_settings(); + // if (gen_settings != null) + // return gen_settings.compute_theos_for_active_sheet_expirations_only; + // } + // return false; + } + } + + #endregion + + private int _n_updates = 0; + private void _theo_producer_on_theos(IDictionary> exp_theo_map, double vol_compute_time, double theo_compute_time) { + int n_active_exps = exp_theo_map == null ? 0 : exp_theo_map.Where(kv => kv.Value != null && kv.Value.Count() > 0).Count(); + Log.Gen.info(String.Format("AW2 local compute # {0}, Exps = {1} Vol time = {2}, Theo time = {3}", ++_n_updates, n_active_exps, vol_compute_time, theo_compute_time)); + _local_publish_helper.publish(exp_theo_map); + } + + private void _theo_producer_on_vols(IDictionary> exp_vol_map, double vol_compute_time, double theo_compute_time) { + // Doesnt look like this is being used + // bts.api.data.VolSurfaceLocalVols[] vols = new bts.api.data.VolSurfaceLocalVols[exp_vol_map.Count]; + // int idx = 0; + // foreach (var entry in exp_vol_map) { + // vols[idx++] = new bts.api.data.VolSurfaceLocalVols { + // vs_id = _vs_id, + // expiration = entry.Key.expiration, + // symbol = entry.Key.symbol, + // vols = entry.Value.Select(x => (bts.api.analytics.VolMatrix)x).ToArray() + // }; + // } + // _threaded_bb.sec_thread_write(new bts.api.data.VolSurfaceLocalVolsTag(_vs_id), vols); + } + + #region IDisposable + public void Dispose() { + _threaded_bb.data_callback -= _on_bb_data; + } + #endregion + } +} \ No newline at end of file diff --git a/src/client/spark/AW2/Bus/SingleVolSurfaceClientTheosPublishHelper.cs b/src/client/spark/AW2/Bus/SingleVolSurfaceClientTheosPublishHelper.cs new file mode 100644 index 000000000..372f80a3e --- /dev/null +++ b/src/client/spark/AW2/Bus/SingleVolSurfaceClientTheosPublishHelper.cs @@ -0,0 +1,51 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +using mbts.analytics; + +namespace mbts.spark { + /// This class is held by the SingleVolSurfaceClientPrecomputedTheosPublisher + /// and acts as a buffer for publishing values. If wait_for_theo_confirmation + /// setting is true, it publshes an alert tag, otherwise publishes the theos + /// directly + public class SingleVolSurfaceClientTheosPublishHelper { + private readonly int _vs_id; + private readonly ThreadedBlackboard _bb; + private int _n_updates = 0; + + public SingleVolSurfaceClientTheosPublishHelper(int vs_id, ThreadedBlackboard bb) { + _vs_id = vs_id; + _bb = bb; + } + + public void publish(IDictionary> exp_theo_map) { + if (_n_updates == 0) + /// If its the first theos send it rightaway + _bb.sec_thread_write(SparkTags.VolSurfaceLocalTheosTag(_vs_id), exp_theo_map); + else { + if (_is_theo_acceptance_confirmation_on) + _bb.sec_thread_write(SparkTags.VolSurfaceTheoAlertTag, new VolSurfaceTheoAlertData(Guid.NewGuid().ToString(), _vs_id, exp_theo_map)); + else + _bb.sec_thread_write(SparkTags.VolSurfaceLocalTheosTag(_vs_id), exp_theo_map); + } + _n_updates++; + } + + private bool _is_theo_acceptance_confirmation_on { + get { + return true; + // this was a setting when theos could be accepted or buffered + // SymbolBasedSettingsManager click_trade_manager = _bb.sec_thread_retrieve_from_cache(new ClickTradeSettingsTag()) as SymbolBasedSettingsManager; + // if (click_trade_manager != null) { + // GeneralClickTradeSettings gen_settings = click_trade_manager.fetch_associated_general_settings(); + // if (gen_settings != null) + // return gen_settings.theo_acceptance_confirmation; + // } + // return false; + } + } + } +} diff --git a/src/client/spark/AW2/Bus/RequestResponse/SingleVolSurfaceCommittedOutputRetriever.cs b/src/client/spark/AW2/Bus/SingleVolSurfaceCommittedOutputRetriever.cs similarity index 100% rename from src/client/spark/AW2/Bus/RequestResponse/SingleVolSurfaceCommittedOutputRetriever.cs rename to src/client/spark/AW2/Bus/SingleVolSurfaceCommittedOutputRetriever.cs diff --git a/src/client/spark/AW2/Bus/RequestResponse/SingleVolSurfaceDataSource.cs b/src/client/spark/AW2/Bus/SingleVolSurfaceDataSource.cs similarity index 100% rename from src/client/spark/AW2/Bus/RequestResponse/SingleVolSurfaceDataSource.cs rename to src/client/spark/AW2/Bus/SingleVolSurfaceDataSource.cs diff --git a/src/client/spark/AW2/Bus/RequestResponse/SingleVolSurfaceGateway.cs b/src/client/spark/AW2/Bus/SingleVolSurfaceGateway.cs similarity index 100% rename from src/client/spark/AW2/Bus/RequestResponse/SingleVolSurfaceGateway.cs rename to src/client/spark/AW2/Bus/SingleVolSurfaceGateway.cs diff --git a/src/client/spark/AW2/Bus/SingleVolSurfaceManager.cs b/src/client/spark/AW2/Bus/SingleVolSurfaceManager.cs new file mode 100644 index 000000000..58f3ee844 --- /dev/null +++ b/src/client/spark/AW2/Bus/SingleVolSurfaceManager.cs @@ -0,0 +1,51 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +using bts.api.analytics; + +using mbts.analytics; + +namespace mbts.spark { + public class SingleVolSurfaceManager : IDisposable { + private IEnumerable _resources; + private readonly object _in_bb_delete_tag = SparkTags.VolSurfaceDeleteTag; + private readonly ThreadedBlackboard _threaded_bb; + + public SingleVolSurfaceManager(int vs_id, ThreadedBlackboard t_bb, bts.api.IBus global_bus) { + _threaded_bb = t_bb; + _threaded_bb.add_to_subscription_list(_in_bb_delete_tag); + _threaded_bb.data_callback += _on_data; + _resources = new IDisposable[] + { + new SingleVolSurfaceGateway (vs_id, t_bb), + new SingleVolSurfaceDataSource (SingleVolSurfaceDataSource.SymbolListType.Combined, vs_id, t_bb, syms => new SingleVolSurfaceNonVolDataSource (vs_id, syms, t_bb)), + new SingleVolSurfaceDataSource (SingleVolSurfaceDataSource.SymbolListType.Combined, vs_id, t_bb, syms => new SingleVolSurfaceOptionDriverSource (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), + // new SingleVolSurfaceHeatmapManager (vs_id, t_bb), + new SingleVolSurfaceTimeSource (vs_id, t_bb), + /// server work that can optionally be done on the client + // TODO + // new SingleVolSurfaceDataSource (SingleVolSurfaceDataSource.SymbolListType.Committed, vs_id, t_bb, a_syms => new SingleVolSurfaceClientPrecomputedTheosPublisher (vs_id, t_bb, a_syms)), + }; + } + + private void _on_data(object tag, object data) { + if (_in_bb_delete_tag.Equals(tag)) + Dispose(); + } + + #region IDisposable + private bool _is_disposed = false; + public void Dispose() { + if (!_is_disposed) + _resources.ToList().ForEach(d => d.Dispose()); + } + #endregion + } +} \ No newline at end of file diff --git a/src/client/spark/AW2/Bus/RequestResponse/SingleVolSurfaceMarketImpliedVolSource.cs b/src/client/spark/AW2/Bus/SingleVolSurfaceMarketImpliedVolSource.cs similarity index 76% rename from src/client/spark/AW2/Bus/RequestResponse/SingleVolSurfaceMarketImpliedVolSource.cs rename to src/client/spark/AW2/Bus/SingleVolSurfaceMarketImpliedVolSource.cs index d3bab3f30..6c43c9eb0 100644 --- a/src/client/spark/AW2/Bus/RequestResponse/SingleVolSurfaceMarketImpliedVolSource.cs +++ b/src/client/spark/AW2/Bus/SingleVolSurfaceMarketImpliedVolSource.cs @@ -7,15 +7,13 @@ using mbts.analytics; // using bts.o2.msgs; using mbts; -namespace mbts.spark -{ +namespace mbts.spark { /// This class publishes the market implied vols for the /// selected expiration. - public class SingleVolSurfaceMarketImpliedVolSource : IDisposable - { + public class SingleVolSurfaceMarketImpliedVolSource : IDisposable { // TODO - class ShellBBODispenser{ - internal class OptionBBOTag{ + class ShellBBODispenser { + internal class OptionBBOTag { } } @@ -28,13 +26,12 @@ namespace mbts.spark private bool _is_dirty = true; // private mbts.user.UserConfigHelper _config_helper = new mbts.user.UserConfigHelper(); - public SingleVolSurfaceMarketImpliedVolSource(int volsurface_id, ThreadedBlackboard bb) - { + public SingleVolSurfaceMarketImpliedVolSource(int volsurface_id, ThreadedBlackboard bb) { _vs_id = volsurface_id; _bb = bb; _in_bb_committed_output_tag = SparkTags.VolSurfaceCommittedOutputTag(volsurface_id); _in_bb_calc_resp_tag = SparkTags.VolSurfaceCalculationResponseTag(volsurface_id); - _in_bb_inp_dirty_tag = SparkTags.VolSurfaceDirtyStateTag(volsurface_id); + _in_bb_inp_dirty_tag = SparkTags.VolSurfaceDirtyStateTag(volsurface_id); _in_bb_selected_exp_tag = SparkTags.VolSurfaceGridSelectionTag(_vs_id); _in_bb_market_impliedvol_side_tag = SparkTags.VolSurfaceMarketImpliedVolSide(_vs_id); _in_bb_ignore_market_implied_vol_source_settings_tag = SparkTags.VolSurfaceIgnoreImpliedVolSettingsTag(volsurface_id); @@ -44,27 +41,23 @@ namespace mbts.spark _bb.timer_callback += _on_bb_timer; } - private void _on_bb_data(object tag, object data) - { + private void _on_bb_data(object tag, object data) { if (tag != null) - if (_in_bb_committed_output_tag.Equals(tag) || _in_bb_calc_resp_tag.Equals(tag) || _in_bb_inp_dirty_tag.Equals(tag) || _in_bb_selected_exp_tag.Equals(tag) || tag.Equals (_in_bb_market_impliedvol_side_tag) || tag is ShellBBODispenser.OptionBBOTag || _in_bb_ignore_market_implied_vol_source_settings_tag.Equals (tag)) + if (_in_bb_committed_output_tag.Equals(tag) || _in_bb_calc_resp_tag.Equals(tag) || _in_bb_inp_dirty_tag.Equals(tag) || _in_bb_selected_exp_tag.Equals(tag) || tag.Equals(_in_bb_market_impliedvol_side_tag) || tag is ShellBBODispenser.OptionBBOTag || _in_bb_ignore_market_implied_vol_source_settings_tag.Equals(tag)) _is_dirty = true; } private DateTime _last_publish_time = DateTime.MinValue; - private void _on_bb_timer() - { + private void _on_bb_timer() { if (_is_dirty) _recompute_and_publish(); } - private void _recompute_and_publish() - { + private void _recompute_and_publish() { Tuple sel_exp = _bb.sec_thread_retrieve_from_cache(_in_bb_selected_exp_tag) as Tuple; VolSurfaceOutput vs_output = _resolve_curr_cand(); if (vs_output != null && vs_output.volsurface_input != null && vs_output.aux_data_map != null && sel_exp != null && sel_exp.Item1 != null && - DateTime.Now.Subtract(_last_publish_time) > TimeSpan.FromMilliseconds(vs_output.volsurface_input.surface_settings.core_settings.market_fit_settings.graph_update_period_ms)) - { + DateTime.Now.Subtract(_last_publish_time) > TimeSpan.FromMilliseconds(vs_output.volsurface_input.surface_settings.core_settings.market_fit_settings.graph_update_period_ms)) { VolSurfaceEnums.MarketSide impliedvol_side = _get_market_impliedvol_side(_bb, _vs_id); _last_publish_time = DateTime.Now; _is_dirty = false; @@ -75,20 +68,17 @@ namespace mbts.spark _timer.stop(); _logger.log("SingleVolSurfaceMarketImpliedVolSource", "SingleVolSurfaceMarketImpliedVolSource", _timer.lastIntervalTime); _bb.sec_thread_write(SparkTags.VolSurfaceMarketImpliedVolTag(_vs_id), - new Dictionary>() { { orig_exp, Tuple.Create(md_exp, exp_impl_vol_map) } }); + new Dictionary>() { { orig_exp, Tuple.Create(md_exp, exp_impl_vol_map) } }); } } - private VolSurfaceOutput _resolve_curr_cand() - { + private VolSurfaceOutput _resolve_curr_cand() { object obj_is_dirty = _bb.sec_thread_retrieve_from_cache(_in_bb_inp_dirty_tag); bool is_dirty = obj_is_dirty != null && (bool)obj_is_dirty; - if (is_dirty) - { + if (is_dirty) { VolSurfaceCalculationResponse vs_resp = _bb.sec_thread_retrieve_from_cache(_in_bb_calc_resp_tag) as VolSurfaceCalculationResponse; return vs_resp != null ? vs_resp.volsurface_calculation_output : null; - } - else + } else return _bb.sec_thread_retrieve_from_cache(_in_bb_committed_output_tag) as VolSurfaceOutput; } @@ -106,52 +96,48 @@ namespace mbts.spark // } // TODO, get option BBO from the bus the and convert it into the return type - private IDictionary> _get_bbo(VolSurfaceExpiration vs_exp) - { + private IDictionary> _get_bbo(VolSurfaceExpiration vs_exp) { return null; } - // #region Static helpers - // internal static IDictionary> _get_bbo(ThreadedBlackboard bb, VolSurfaceExpiration vs_exp) - // { - // IEnumerable exchanges = SymbolExchangeAssociationSource.get_exchanges(vs_exp.symbol, bts.o2.msgs.SecurityType.type.OPTION); - // if (exchanges != null && exchanges.Count() > 0) - // { - // object bbo_tag = new ShellBBODispenser.OptionBBOTag(new SecurityTuple(SecurityType.type.OPTION, vs_exp.symbol, exchanges.ElementAt(0))); - // OptionContractKeyedData sym_bbo = bb.sec_thread_retrieve_from_cache(bbo_tag) as OptionContractKeyedData; - // if (sym_bbo != null) - // { - // IReadOnlyDictionary> exp_map = sym_bbo.get_exp_data(vs_exp.expiration); - // if (exp_map != null) - // return exp_map.ToDictionary(kv => kv.Key, kv => - // { - // CallPutValue cp_bbo = kv.Value; - // BBOPacket c = cp_bbo.call_value ?? BBOPacket.get_null_packet(), p = cp_bbo.put_value ?? BBOPacket.get_null_packet(); - // return Tuple.Create(new VolSurfaceBBOUnit(BBOPacket.get_bid_price(c), BBOPacket.get_bid_size(c), BBOPacket.get_ask_price(c), BBOPacket.get_ask_size(c)), - // new VolSurfaceBBOUnit(BBOPacket.get_bid_price(p), BBOPacket.get_bid_size(p), BBOPacket.get_ask_price(p), BBOPacket.get_ask_size(p))); - // }); - // } - // } - // return new Dictionary>(); - // } + #region Static helpers + internal static IDictionary> _get_bbo(ThreadedBlackboard bb, VolSurfaceExpiration vs_exp) { + return null; + // IEnumerable exchanges = SymbolExchangeAssociationSource.get_exchanges(vs_exp.symbol, bts.o2.msgs.SecurityType.type.OPTION); + // if (exchanges != null && exchanges.Count() > 0) + // { + // object bbo_tag = new ShellBBODispenser.OptionBBOTag(new SecurityTuple(SecurityType.type.OPTION, vs_exp.symbol, exchanges.ElementAt(0))); + // OptionContractKeyedData sym_bbo = bb.sec_thread_retrieve_from_cache(bbo_tag) as OptionContractKeyedData; + // if (sym_bbo != null) + // { + // IReadOnlyDictionary> exp_map = sym_bbo.get_exp_data(vs_exp.expiration); + // if (exp_map != null) + // return exp_map.ToDictionary(kv => kv.Key, kv => + // { + // CallPutValue cp_bbo = kv.Value; + // BBOPacket c = cp_bbo.call_value ?? BBOPacket.get_null_packet(), p = cp_bbo.put_value ?? BBOPacket.get_null_packet(); + // return Tuple.Create(new VolSurfaceBBOUnit(BBOPacket.get_bid_price(c), BBOPacket.get_bid_size(c), BBOPacket.get_ask_price(c), BBOPacket.get_ask_size(c)), + // new VolSurfaceBBOUnit(BBOPacket.get_bid_price(p), BBOPacket.get_bid_size(p), BBOPacket.get_ask_price(p), BBOPacket.get_ask_size(p))); + // }); + // } + // } + // return new Dictionary>(); + } - internal static bool _ignore_market_implied_vol_source_settings(ThreadedBlackboard bb, int vs_id) - { + internal static bool _ignore_market_implied_vol_source_settings(ThreadedBlackboard bb, int vs_id) { object rv = bb.sec_thread_retrieve_from_cache(SparkTags.VolSurfaceIgnoreImpliedVolSettingsTag(vs_id)); return rv == null ? false : (bool)rv; } - internal static VolSurfaceEnums.MarketSide _get_market_impliedvol_side(ThreadedBlackboard bb, int vs_id) - { + internal static VolSurfaceEnums.MarketSide _get_market_impliedvol_side(ThreadedBlackboard bb, int vs_id) { object impliedvol_side_obj = bb.sec_thread_retrieve_from_cache(SparkTags.VolSurfaceMarketImpliedVolSide(vs_id)); return (impliedvol_side_obj != null && impliedvol_side_obj is VolSurfaceEnums.MarketSide) ? (VolSurfaceEnums.MarketSide)impliedvol_side_obj : VolSurfaceEnums.MarketSide.Mid; } -// #endregion + #endregion #region IDisposable - public void Dispose() - { + public void Dispose() { _bb.data_callback -= _on_bb_data; _bb.timer_callback -= _on_bb_timer; } diff --git a/src/client/spark/AW2/Bus/RequestResponse/SingleVolSurfaceNonVolDataSource.cs b/src/client/spark/AW2/Bus/SingleVolSurfaceNonVolDataSource.cs similarity index 100% rename from src/client/spark/AW2/Bus/RequestResponse/SingleVolSurfaceNonVolDataSource.cs rename to src/client/spark/AW2/Bus/SingleVolSurfaceNonVolDataSource.cs diff --git a/src/client/spark/AW2/Bus/RequestResponse/SingleVolSurfaceOptionDriverSource.cs b/src/client/spark/AW2/Bus/SingleVolSurfaceOptionDriverSource.cs similarity index 100% rename from src/client/spark/AW2/Bus/RequestResponse/SingleVolSurfaceOptionDriverSource.cs rename to src/client/spark/AW2/Bus/SingleVolSurfaceOptionDriverSource.cs diff --git a/src/client/spark/AW2/Bus/SingleVolSurfaceRequestCalculator.cs b/src/client/spark/AW2/Bus/SingleVolSurfaceRequestCalculator.cs new file mode 100644 index 000000000..5b97c8a46 --- /dev/null +++ b/src/client/spark/AW2/Bus/SingleVolSurfaceRequestCalculator.cs @@ -0,0 +1,131 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +using mbts.analytics; + +namespace mbts.spark { + /// + /// All local changes to the VolSurface that trigger calculations + /// are handled here. + /// Subs : + /// 1. VS Calc Req + /// 2. VS Nonvol Data + /// 3. Dirty + /// Pubs : + /// 1. Calc Resp + /// + public class SingleVolSurfaceRequestCalculator : IDisposable { + private readonly int _vs_id; + private readonly HashSet _symbols; + private readonly ThreadedBlackboard _threaded_bb; + private readonly object _in_bb_request_tag, _in_bb_dirty_tag, _in_bb_nonvol_data_tag, _in_bb_vs_standard_time_tag, _in_bb_market_impliedvol_side_tag; + private HighPerformanceTimer _timer = new HighPerformanceTimer(); + /// data + private VolSurfaceOutput _last_output; + + public SingleVolSurfaceRequestCalculator(int vs_id, IEnumerable symbols, ThreadedBlackboard threaded_bb) { + _vs_id = vs_id; + _symbols = new HashSet(symbols); + _threaded_bb = threaded_bb; + _in_bb_request_tag = SparkTags.VolSurfaceCalculationRequestTag(vs_id); + _in_bb_nonvol_data_tag = SparkTags.VolSurfaceNonVolDataTag(vs_id); + _in_bb_vs_standard_time_tag = SparkTags.VolSurfaceStandardTimeTag(vs_id); + _in_bb_market_impliedvol_side_tag = SparkTags.VolSurfaceMarketImpliedVolSide(vs_id); + _in_bb_dirty_tag = SparkTags.VolSurfaceDirtyStateTag(vs_id); + _threaded_bb.add_to_subscription_list(_in_bb_request_tag, _in_bb_nonvol_data_tag, _in_bb_vs_standard_time_tag, _in_bb_vs_standard_time_tag, _in_bb_dirty_tag); + _threaded_bb.data_callback += _on_bb_data; + _recompute_and_publish(true); + } + + private void _on_bb_data(object tag, object data) { + if (_in_bb_request_tag.Equals(tag) || _in_bb_dirty_tag.Equals(tag)) + _recompute_and_publish(true); + else if (_in_bb_nonvol_data_tag.Equals(tag) || _in_bb_vs_standard_time_tag.Equals(tag)) + _recompute_and_publish(false); + + } + + private void _recompute_and_publish(bool is_new_request) { + object is_dirty_obj = _threaded_bb.sec_thread_retrieve_from_cache(_in_bb_dirty_tag); + bool is_dirty = is_dirty_obj is bool && (bool)is_dirty_obj; + VolSurfaceNonVolData nonvol_data = _threaded_bb.sec_thread_retrieve_from_cache(_in_bb_nonvol_data_tag) as VolSurfaceNonVolData; + VolSurfaceStandardTime vs_standard_time = _threaded_bb.sec_thread_retrieve_from_cache(_in_bb_vs_standard_time_tag) as VolSurfaceStandardTime; + if (is_dirty && nonvol_data != null) { + _timer.start(); + VolSurfaceCalculationRequest curr_req = _threaded_bb.sec_thread_retrieve_from_cache(_in_bb_request_tag) as VolSurfaceCalculationRequest, + effective_req = null; + if (is_new_request) + effective_req = curr_req; + else { + if (_last_output != null) + 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); + _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); + _timer.stop(); + bts.Log.Gen.info(String.Format("SingleVolSurfaceRequestCalculator. Time to compute vol for {0} exps {1} msecs", nonvol_data.contracts.Count, _timer.lastIntervalTime)); + _threaded_bb.sec_thread_write(SparkTags.VolSurfaceCalculationResponseTag(_vs_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, IDictionary aux_data_map) { + IDictionary rv = req.action_map; + /// TODO : VolCurveAction needs to be structured better. The UI enforces that + /// all exps have the same action, but the structure doesnt. So here the UI + /// constraint is flowing in + if (rv != null && rv.Count > 0) { + 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); + 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))); + } + } + return rv; + } + + 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(); + VolCurveAction rep_action = action_map.ElementAt(0).Value; + 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); + 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(_threaded_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(_threaded_bb, arg_vs_exp), impliedvol_side, SingleVolSurfaceMarketImpliedVolSource._ignore_market_implied_vol_source_settings(_threaded_bb, _vs_id), out md_exp); + rv[vs_exp] = exp_impl_data; + } + return rv; + } + + #region IDisposable + private bool _disposed = false; + public void Dispose() { + if (!_disposed) { + _disposed = true; + _threaded_bb.data_callback -= _on_bb_data; + } + } + #endregion + } +} \ No newline at end of file diff --git a/src/client/spark/AW2/Bus/RequestResponse/SingleVolSurfaceTheoSource.cs b/src/client/spark/AW2/Bus/SingleVolSurfaceTheoSource.cs similarity index 87% rename from src/client/spark/AW2/Bus/RequestResponse/SingleVolSurfaceTheoSource.cs rename to src/client/spark/AW2/Bus/SingleVolSurfaceTheoSource.cs index 903c27d81..ed9ea6355 100644 --- a/src/client/spark/AW2/Bus/RequestResponse/SingleVolSurfaceTheoSource.cs +++ b/src/client/spark/AW2/Bus/SingleVolSurfaceTheoSource.cs @@ -6,8 +6,7 @@ using System.Threading.Tasks; using mbts.analytics; using bts; -namespace mbts.spark -{ +namespace mbts.spark { /// Publishes the committed and candidate greeks in the /// form of VolSurfaceTheoData /// Subs : @@ -17,16 +16,14 @@ namespace mbts.spark /// 4. Detailed Window State /// Pubs : /// 1. VolSurfaceTheoData (cand and comm theos) - public class SingleVolSurfaceTheoSource : IDisposable - { + public class SingleVolSurfaceTheoSource : IDisposable { private readonly int _volsurface_id; private readonly ThreadedBlackboard _threaded_bb; - private readonly object _in_committed_vol_output_tag, _in_candidate_vol_output_tag, _in_input_dirty_tag, _in_window_state_tag; + private readonly object _in_committed_vol_output_tag, _in_candidate_vol_output_tag, _in_input_dirty_tag, _in_window_state_tag; private readonly HighPerformanceTimer _timer = new HighPerformanceTimer(); - private bool _is_dirty = true; - - public SingleVolSurfaceTheoSource(int volsurface_id, ThreadedBlackboard threaded_bb) - { + private bool _is_dirty = true; + + public SingleVolSurfaceTheoSource(int volsurface_id, ThreadedBlackboard threaded_bb) { _volsurface_id = volsurface_id; _threaded_bb = threaded_bb; _in_committed_vol_output_tag = SparkTags.VolSurfaceCommittedOutputTag(_volsurface_id); @@ -39,16 +36,13 @@ namespace mbts.spark } #region Blackboard - private void _on_data(object tag, object data) - { - if (_in_candidate_vol_output_tag.Equals(tag) || _in_committed_vol_output_tag.Equals(tag) || _in_input_dirty_tag.Equals (tag) || _in_window_state_tag.Equals (tag)) + private void _on_data(object tag, object data) { + if (_in_candidate_vol_output_tag.Equals(tag) || _in_committed_vol_output_tag.Equals(tag) || _in_input_dirty_tag.Equals(tag) || _in_window_state_tag.Equals(tag)) _is_dirty = true; } - private void _on_timer() - { - if (_is_dirty) - { + private void _on_timer() { + if (_is_dirty) { /// publishes new values when there is an /// 1. theos window up /// 2. waiting candidate change @@ -60,21 +54,17 @@ namespace mbts.spark private static readonly IDictionary> _empty_theos = new Dictionary>(); private VolSurfaceTheoData _last_data = new VolSurfaceTheoData(new Dictionary>(), _empty_theos, _empty_theos, false); - private void _compute_and_publish(bool is_active_candidate, bool is_active_theos_window) - { + private void _compute_and_publish(bool is_active_candidate, bool is_active_theos_window) { VolSurfaceCalculationResponse calc_resp = _threaded_bb.sec_thread_retrieve_from_cache(_in_candidate_vol_output_tag) as VolSurfaceCalculationResponse; VolSurfaceOutput candidate_output = calc_resp != null ? calc_resp.volsurface_calculation_output : null, committed_output = _threaded_bb.sec_thread_retrieve_from_cache(_in_committed_vol_output_tag) as VolSurfaceOutput; IDictionary> secs = _get_securities(committed_output, candidate_output); IDictionary> comm_theo_map = _empty_theos, cand_theo_map = _empty_theos; - if (is_active_theos_window) - { + if (is_active_theos_window) { comm_theo_map = _compute_theos(committed_output, secs); if (is_active_candidate) cand_theo_map = _compute_theos(candidate_output, secs); - } - else - { + } else { if (is_active_candidate) cand_theo_map = _compute_theos(candidate_output, secs); } @@ -83,18 +73,15 @@ namespace mbts.spark _threaded_bb.sec_thread_write(SparkTags.VolSurfaceTheoOutputTag(_volsurface_id), new_data); } - private bool _is_valid_update(VolSurfaceTheoData new_data) - { + private bool _is_valid_update(VolSurfaceTheoData new_data) { bool is_spurious = _last_data.committed_theo_map.Count == 0 && _last_data.candidate_theo_map.Count == 0 && new_data.committed_theo_map.Count == 0 && new_data.candidate_theo_map.Count == 0; _last_data = new_data; return !is_spurious; } - private IDictionary> _compute_theos(VolSurfaceOutput vs_output, IDictionary> exp_strikes) - { - if (vs_output != null) - { + private IDictionary> _compute_theos(VolSurfaceOutput vs_output, IDictionary> exp_strikes) { + if (vs_output != null) { _timer.start(); IDictionary> exp_volmat_map = VolSurfaceVolMatrixCalculator.generate_volmatrix(vs_output.volsurface_input, exp_strikes.ToDictionary(kv => kv.Key, kv => kv.Value as IEnumerable), vs_output.aux_data_map, @@ -110,8 +97,7 @@ namespace mbts.spark return new Dictionary>(); } - private IDictionary> _get_securities(VolSurfaceOutput commited_output, VolSurfaceOutput candidate_output) - { + private IDictionary> _get_securities(VolSurfaceOutput commited_output, VolSurfaceOutput candidate_output) { if (candidate_output != null) /// candidate output wins if its active return VolSurfaceUtilityFunctions.get_contracts(candidate_output); @@ -122,21 +108,18 @@ namespace mbts.spark } /// If the details window is not active, the calculations are suspended - private bool _is_active_theos_window() - { + private bool _is_active_theos_window() { object rv_obj = _threaded_bb.sec_thread_retrieve_from_cache(_in_window_state_tag); return rv_obj != null && (bool)rv_obj; } - private bool _is_active_candidate() - { + private bool _is_active_candidate() { object rv_obj = _threaded_bb.sec_thread_retrieve_from_cache(_in_input_dirty_tag); return rv_obj != null && (bool)rv_obj; } - + #region IDisposable - public void Dispose() - { + public void Dispose() { _threaded_bb.data_callback -= _on_data; _threaded_bb.timer_callback -= _on_timer; } diff --git a/src/client/spark/AW2/Bus/RequestResponse/SingleVolSurfaceTimeSource.cs b/src/client/spark/AW2/Bus/SingleVolSurfaceTimeSource.cs similarity index 100% rename from src/client/spark/AW2/Bus/RequestResponse/SingleVolSurfaceTimeSource.cs rename to src/client/spark/AW2/Bus/SingleVolSurfaceTimeSource.cs diff --git a/src/client/spark/Analytics/Pricing/VolSurfacePrecomputedTheosProducer.cs b/src/client/spark/Analytics/Pricing/VolSurfacePrecomputedTheosProducer.cs new file mode 100644 index 000000000..e0a47114c --- /dev/null +++ b/src/client/spark/Analytics/Pricing/VolSurfacePrecomputedTheosProducer.cs @@ -0,0 +1,151 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Collections.Concurrent; +using bts; +using bts.api; + +namespace mbts.analytics { + /// + /// This class computes the theos/greeks for a number of driver + /// prices (specified in the vs settings). + /// It has public setters that get + /// 1. vs input + /// 2. exp params + /// 3. contracts + /// 4. driver prices + /// The first 3 always trigger a calculation. + /// + public partial class VolSurfacePrecomputedTheosProducer { + private enum InputType { + Contracts, + Vol, + ExpParams, + DriverPrice, + VolTime, + }; + + // private readonly bts.config.StaticConfiguration _sym_input = mbts.config.Configuration.get(); + private IDictionary> _exp_strikes_map; + private IDictionary> _filter_map; + private VolSurfaceInput _vs_input; + private IDictionary _exp_params_map; + private IDictionary _driver_price_map; + private VolSurfaceStandardTime _vs_standard_time = null; + + /// last computed min/max driver for each exp + private IDictionary> _computed_driver_range_map = new Dictionary>(); + private readonly IEnumerable _default_abs_moves = new double[] { -25, -20, -15, -10, -5, 0, 5, 10, 15, 20, 25 }; + private readonly double _cushion_percentage = 25.0; + + public event Action>, double, double> on_theos = (o, vt, tt) => { }; + public event Action>, double, double> on_vols = (o, vt, tt) => { }; + + public VolSurfacePrecomputedTheosProducer() { } + + #region Public setters + + public void set_contracts(IDictionary> exp_strikes_map, + IDictionary> filter_map = null) { + _exp_strikes_map = exp_strikes_map.ToDictionary(kv => kv.Key, kv => kv.Value.ToList() as IEnumerable); + _filter_map = filter_map == null ? null : filter_map.ToDictionary(kv => kv.Key, kv => new HashSet(kv.Value)); + _compute_and_fire(InputType.Contracts); + } + + public void set_vol_data(VolSurfaceInput vs_input) { + _vs_input = vs_input != null ? VolSurfaceUtilityFunctions.clone_proto(vs_input) : null; + _compute_and_fire(InputType.Vol); + } + + public void set_nonvol_parameters(IDictionary exp_params) { + _exp_params_map = new Dictionary(exp_params); + _compute_and_fire(InputType.ExpParams); + } + + public void set_driver_price(IDictionary driver_price_map) { + _driver_price_map = new Dictionary(driver_price_map); + _compute_and_fire(InputType.DriverPrice); + } + + public void set_system_vol_time(VolSurfaceStandardTime vs_standard_time) { + Log.Gen.info("VolSurfacePrecomputedTheosProducer.set_system_vol_time"); + _vs_standard_time = vs_standard_time; + _compute_and_fire(InputType.VolTime); + } + + #endregion + + private void _compute_and_fire(InputType input_type) { + if (_vs_input != null && _exp_strikes_map != null && _exp_params_map != null && _driver_price_map != null && _vs_standard_time != null) { + VolSurfaceTimer timer = new VolSurfaceTimer(); + IEnumerable abs_moves = _get_abs_moves(); + VolSurfaceInput synced_vs_input = VolSurfaceDataFunctions.sync_input_expirations_to_master_list(_vs_input, _exp_strikes_map.Keys); + IDictionary synced_driver_price_map = _driver_price_map.sync(_exp_strikes_map.Keys, true, exp => Double.NaN); + IDictionary synced_exp_params_map = _sync_exp_params(); + IDictionary synced_aux_data_map = VolSurfaceUtilityFunctions.compute_aux_data(_vs_input, new VolSurfaceNonVolInput(synced_exp_params_map), _driver_price_map, _vs_standard_time); + + if (input_type == InputType.Vol || input_type == InputType.Contracts || input_type == InputType.ExpParams || + (input_type == InputType.VolTime && VolSurfaceDataFunctions.get_time_mode(_vs_input) == VolSurfaceEnums.VolSurfaceTimeMode.AutoDecay) || + (input_type == InputType.DriverPrice && _recenter(synced_aux_data_map, _computed_driver_range_map, _cushion_percentage))) { + _computed_driver_range_map = _get_driver_range_map(synced_aux_data_map, abs_moves); + double vol_compute_time, theo_compute_time; + timer.start(); IDictionary> exp_vm_map = VolSurfaceVolMatrixCalculator.generate_volmatrix(synced_vs_input, _exp_strikes_map, synced_aux_data_map, abs_moves, false, true, false, false, false, _filter_map); timer.stop(); + vol_compute_time = timer.last_interval_time_ms; + Log.Gen.info(String.Format("VolSurfacePrecomputedTheosProducer._compute_and_fire volmat time {0}", timer.last_interval_time_ms)); + timer.start(); IDictionary> exp_theo_map = VolSurfaceTheoCalculator.compute_standard_greeks(synced_vs_input.surface_settings, exp_vm_map, false); timer.stop(); + theo_compute_time = timer.last_interval_time_ms; + Log.Gen.info(String.Format("VolSurfacePrecomputedTheosProducer._compute_and_fire theo time {0}", timer.last_interval_time_ms)); + on_theos(exp_theo_map, vol_compute_time, theo_compute_time); + on_vols(exp_vm_map, vol_compute_time, theo_compute_time); + } + } + } + + private IDictionary _sync_exp_params() { + var master_exp_keys = _exp_strikes_map.Keys.Select(k => new SecurityExpiration(Venue.Unset, SecurityType.Option, k.symbol, k.expiration)); + var exp_params_no_exch = _exp_params_map.ToDictionary(kv => kv.Key.unset_exchange(), kv => kv.Value); + return exp_params_no_exch.sync(master_exp_keys, true, exp => AnalyticsExpirationParameters.empty); + } + + private static bool _recenter(IDictionary new_aux_data_map, + IDictionary> computed_range_map, + double cushion_percentage) { + computed_range_map = computed_range_map ?? new Dictionary>(); + foreach (KeyValuePair t in new_aux_data_map) { + Tuple range = null; + if (computed_range_map.TryGetValue(t.Key, out range)) { + if (_invalidates_range(t.Value.driver_price, range.Item1, range.Item2, cushion_percentage)) + return true; + } else + return true; + } + return false; + } + + private static bool _invalidates_range(double new_driver, double beg, double end, double cushion_percentage) { + double distance = end - beg; + bool range_nan = Double.IsNaN(beg) || Double.IsNaN(end), driver_nan = Double.IsNaN(new_driver); + return (driver_nan && !range_nan) || + (!driver_nan && range_nan) || + new_driver < beg || + new_driver > end || + (100.0 * (end - new_driver) / distance) <= cushion_percentage || + (100.0 * (new_driver - beg) / distance) <= cushion_percentage; + } + + private IEnumerable _get_abs_moves() { + if (_vs_input != null && _vs_input.surface_settings.advanced_settings != null && _vs_input.surface_settings.advanced_settings.precomputed_theo_handles != null && _vs_input.surface_settings.advanced_settings.precomputed_theo_handles.Count > 0) + return _vs_input.surface_settings.advanced_settings.precomputed_theo_handles; + else + return _default_abs_moves; + } + + private static IDictionary> _get_driver_range_map(IDictionary live_aux_map, + IEnumerable abs_moves) { + double min_move = abs_moves.Min(), max_move = abs_moves.Max(); + return live_aux_map.ToDictionary(kv => kv.Key, kv => Tuple.Create(kv.Value.driver_price + min_move, kv.Value.driver_price + max_move)); + } + } +} \ No newline at end of file