diff --git a/src/client/spark/AW2/Bus/VolSurfaceBlackboardManager.cs b/src/client/spark/AW2/Bus/VolSurfaceBlackboardManager.cs index 1d6eb07e1..1b439e685 100644 --- a/src/client/spark/AW2/Bus/VolSurfaceBlackboardManager.cs +++ b/src/client/spark/AW2/Bus/VolSurfaceBlackboardManager.cs @@ -128,6 +128,10 @@ namespace mbts.spark { _bb.post(SparkTags.VolSurfaceUsageTag, new VolSurfaceUsageListImmutable(ulist)); } + public ThreadedBlackboard bb() { + return _bb; + } + void _on_vs_usage_update(Update update) { // TODO return; diff --git a/src/client/spark/AW2/LiveTheoPublisher.cs b/src/client/spark/AW2/LiveTheoPublisher.cs index 9b0678e1c..a20f8a35c 100644 --- a/src/client/spark/AW2/LiveTheoPublisher.cs +++ b/src/client/spark/AW2/LiveTheoPublisher.cs @@ -3,6 +3,8 @@ using System.Collections.Generic; using mbts.analytics; using bts.api; using mbts.ui; +using MathNet.Numerics.Providers.FourierTransform; +using BCG; namespace mbts.spark { // Publishes theos for all options (on the side, also publishes the theos for TC2) @@ -15,12 +17,15 @@ namespace mbts.spark { private readonly HighPerformanceTimer _timer = new HighPerformanceTimer(); private readonly PerfStatsLogger _logger = new PerfStatsLogger(50, 100); private readonly string _log_id = "LiveTheoPublisher"; + private DateTime _last_future_theos_published = DateTime.MinValue; + private TimeSpan _futures_theos_publish_period = TimeSpan.FromMilliseconds(300); public LiveTheoPublisher(ThreadedBlackboard bb) { _bb = bb; _bb.subscribe(_greeks_tag); _bb.subscribe(_drivers_tag); _bb.data_callback += _on_data; + _bb.timer_callback += _on_timer; _interp_and_publish(); } @@ -31,6 +36,10 @@ namespace mbts.spark { } } + private void _on_timer() { + _publish_future_theos(); + } + private void _log_interpgreeks( IReadOnlyDictionary interp_greeks) { string log_msg = String.Empty; @@ -153,6 +162,27 @@ namespace mbts.spark { _publish_tc2_theos(k_theos); } + // recomputes and publishes them periodicially + void _publish_future_theos() { + if (DateTime.Now - _last_future_theos_published < _futures_theos_publish_period) + return; + _last_future_theos_published = DateTime.Now; + var rv = new Dictionary(); + SystemContractData sc_data = _bb.read_state(SparkTags.SystemContractsTag); + foreach (var kv in sc_data.exp_map) { + var id = kv.Value; + SecurityMD sec_md; + if (sc_data.sec_md_map.TryGetValue(id, out sec_md)) { + if (sec_md.security.HasFuture) { + SecurityExpiration exp = kv.Key; + double pr = sec_md.md.fixing_price; + rv.Add(exp, new FutureTheoStructure(exp.expiration, pr, pr, 1, 0)); + } + } + } + _bb.post(SparkTags.TC2Tags.LiveFutureTheosTag, rv); + } + public void Dispose() { _bb.data_callback -= _on_data; } diff --git a/src/client/spark/AW2/todo.txt b/src/client/spark/AW2/todo.txt index e30b87892..25930716c 100644 --- a/src/client/spark/AW2/todo.txt +++ b/src/client/spark/AW2/todo.txt @@ -24,13 +24,14 @@ Value: OptionDriverPriceMap which is a wrapper around IDictionary> ---------------------------------------------------------------- -SingleVolSurfaceInterpGreeksPublisher listens to all inputs and publishes -exp vs InterpGreeks +SingleVolSurfaceInterpGreeksPublisher (for one vs) listens to all inputs and publishes +IDictionary> -VolSurfaceInterpGreeksMultiplexer listens to all vol surfaces, resolves symbols and -publishes symbol vs InterpGreeks +VolSurfaceInterpGreeksMultiplexer (for multiple option symbols) listens to all vol +surfaces, resolves symbols and for each option_symbol publishes +OptionTheoInterpolationData* -SymbolAggregationPublisher is a thin class that combines individual symbol data and +SymbolAggregationPublisher is a thin generic class that combines individual symbol data and publishes symbol vs data map LiveTheoPublisher: diff --git a/src/client/spark/Daemons/AnalyticsDaemon.cs b/src/client/spark/Daemons/AnalyticsDaemon.cs index ade45370b..56d56cbef 100644 --- a/src/client/spark/Daemons/AnalyticsDaemon.cs +++ b/src/client/spark/Daemons/AnalyticsDaemon.cs @@ -15,6 +15,7 @@ using System.Reactive.Disposables; using System.Reactive.Linq; using System.Windows; using bts.api.analytics; +using BCG; using Disposable = mbts.Disposable; @@ -24,6 +25,9 @@ namespace bts { private readonly IBus _bus; private readonly AnalyticsService _analytics_service; private readonly VolSurfaceBusManager _vs_manager; + private readonly SpreadManager _spread_manager; + private readonly SpreadCalculationSynchronizer _spread_calc; + IDisposable _dispose; [ImportingConstructor] @@ -32,6 +36,8 @@ namespace bts { _bus = bus; _analytics_service = analytics_service; _vs_manager = new VolSurfaceBusManager(_bus, _analytics_service); + _spread_manager = new SpreadManager(_vs_manager.bb(), "xxx"); + _spread_calc = new SpreadCalculationSynchronizer(_vs_manager.bb()); } public void Dispose() => diff --git a/src/client/spark/NMSheets/Outside/tc2/ClickTrading/InitialTradingSideHint.cs b/src/client/spark/NMSheets/Outside/tc2/ClickTrading/InitialTradingSideHint.cs index 80cb777b8..a49f517bf 100644 --- a/src/client/spark/NMSheets/Outside/tc2/ClickTrading/InitialTradingSideHint.cs +++ b/src/client/spark/NMSheets/Outside/tc2/ClickTrading/InitialTradingSideHint.cs @@ -17,10 +17,10 @@ namespace BCG { } public class SpreadInititialState { - public InitialTradingSideHint preset_trading_side; - public SpreadWindowMode preset_mode; + public InitialTradingSideHint preset_trading_side = InitialTradingSideHint.Buy; + public SpreadWindowMode preset_mode = SpreadWindowMode.Greeks; //public Nullable preset_order_hint = null; public double preset_price = Double.NaN; - public UInt32 preset_size = 0; + public UInt32 preset_size = 1; } } diff --git a/src/client/spark/NMSheets/Outside/tc2/GUI/CentralTimer.cs b/src/client/spark/NMSheets/Outside/tc2/GUI/CentralTimer.cs new file mode 100644 index 000000000..3abaa01b2 --- /dev/null +++ b/src/client/spark/NMSheets/Outside/tc2/GUI/CentralTimer.cs @@ -0,0 +1,30 @@ +using System; +using System.Windows.Forms; + +using BCG; +using BCG.Utilities; + +namespace BCG +{ + public class CentralTimer + { + static CentralTimer() + { + CentralTimer.timer = new Timer(); + timer.Enabled = true; + timer.Interval = 20; + } + + // #HACK, there is a bug in PropertyGrid. When a fast (< 100ms) + // timer is active the property grid does not work properly. + // we work around by speeding up / slowing down the timer + // when a property grid is visible. + public static void slowDownTimer() + {timer.Interval = 2000;} + + public static void resumeTimer() + {timer.Interval = 10;} + + public static System.Windows.Forms.Timer timer; + } +} diff --git a/src/client/spark/NMSheets/Outside/tc2/GUI/SpreadPositionGUI.cs b/src/client/spark/NMSheets/Outside/tc2/GUI/SpreadPositionGUI.cs new file mode 100644 index 000000000..8cd08c43b --- /dev/null +++ b/src/client/spark/NMSheets/Outside/tc2/GUI/SpreadPositionGUI.cs @@ -0,0 +1,188 @@ +using System; +using System.Collections; +using System.ComponentModel; +using System.Drawing; +using System.Data; +using System.Windows.Forms; + +namespace BCG +{ + /// + /// This class encapsulates the size part of the spread + /// leg. This includes +/-, size, up arrow, down arrow + /// 3/7/12 : Fixed the bug where enterring the size through + /// the numpad would always result in a +ve size (in myEdit) + /// + public class SpreadPositionGUI : System.Windows.Forms.UserControl + { + private BCG.ValueEntryGUI myValueEntryGUI; + /// + /// Required designer variable. + /// + private System.ComponentModel.Container components = null; + + + public Control layoutContainer; + + public GUIChange onPositionChange; + public double position + { + get + { + if (myValueEntryGUI != null && !DesignMode) + return (double) myValueEntryGUI.currentValue; + else + return 0; + } + set + { + if (myValueEntryGUI != null && !DesignMode ) + { + myValueEntryGUI.currentValue = value; + myValueEntryGUI.flip = value < 0; + } + } + } + + public Size minSize + {get{return myValueEntryGUI.minSize;}} + + public ValueEntryGUIConfig config + { + set{myValueEntryGUI.config = value;} + get{return myValueEntryGUI.config;} + } + + private Guid myGuid = Guid.NewGuid(); + public SpreadPositionGUI() + { + // This call is required by the Windows.Forms Form Designer. + InitializeComponent(); + + myValueEntryGUI.currentValue = 0; + myValueEntryGUI.onValueDown += new GUIChange(myDown); + myValueEntryGUI.onValueUp += new GUIChange(myUp); + myValueEntryGUI.onValueEdit += new GUIChange(myEdit); + myValueEntryGUI.onValueFlip += new GUIChange(myFlip); + } + + + public override int GetHashCode() + { + return myGuid.GetHashCode(); + } + + public override bool Equals(object obj) + { + SpreadPositionGUI rhs = obj as SpreadPositionGUI; + if(rhs == null) + return false; + else + { + return this.myGuid.Equals(rhs.myGuid); + } + } + + /// + /// Clean up any resources being used. + /// + protected override void Dispose( bool disposing ) + { + if( disposing ) + { + if(components != null) + { + components.Dispose(); + } + } + base.Dispose( disposing ); + } + + void myUp(object sender, object value ) + {myMove(sender,value,1);} + + void myDown(object sender, object value ) + {myMove(sender,value,-1);} + + void myMove(object sender, object value, int move) + { + ValueEntryGUI g = (ValueEntryGUI) sender; + + double v = (double) g.currentValue; + + if (v < 0) + move *= -1; + + v += move; + + if (v != 0) + { + g.currentValue = v; + g.flip = v < 0; + if (onPositionChange != null) + onPositionChange(this,v); + } + } + + void myEdit(object sender, object value) + { + using (TCNumPad tcNumPad = new TCNumPad("Size")) + { + tcNumPad.Left = Cursor.Position.X; + tcNumPad.Top = Cursor.Position.Y; + + if (tcNumPad.ShowDialog() == DialogResult.OK) + { + ValueEntryGUI g = (ValueEntryGUI)sender; + /// TCNumPad does not have the +/- sign, this + /// ensures the sign from the spread is carried + /// over after qty manipulations via the num pad + g.currentValue = ((double)g.currentValue < 0 ? -1.0 : 1.0) * tcNumPad.asNumber; + g.flip = (double)g.currentValue < 0; + if (onPositionChange != null) + onPositionChange(this, (double)g.currentValue); + } + } + } + + void myFlip(object sender, object value ) + { + ValueEntryGUI g = (ValueEntryGUI) sender; + g.flip = !g.flip; + g.currentValue = - (double) g.currentValue; + if (onPositionChange != null) + onPositionChange(this,(double) g.currentValue); + } + + #region Component Designer generated code + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + this.myValueEntryGUI = new BCG.ValueEntryGUI(); + this.SuspendLayout(); + // + // myValueEntryGUI + // + this.myValueEntryGUI.config = null; + this.myValueEntryGUI.currentValue = "0"; + this.myValueEntryGUI.Dock = System.Windows.Forms.DockStyle.Fill; + this.myValueEntryGUI.flip = false; + this.myValueEntryGUI.Location = new System.Drawing.Point(0, 0); + this.myValueEntryGUI.Name = "myValueEntryGUI"; + this.myValueEntryGUI.Size = new System.Drawing.Size(56, 16); + this.myValueEntryGUI.TabIndex = 0; + // + // SpreadPositionGUI + // + this.Controls.Add(this.myValueEntryGUI); + this.Name = "SpreadPositionGUI"; + this.Size = new System.Drawing.Size(56, 16); + this.ResumeLayout(false); + + } + #endregion + } +} diff --git a/src/client/spark/NMSheets/Outside/tc2/GUI/SpreadPositionGUI.resx b/src/client/spark/NMSheets/Outside/tc2/GUI/SpreadPositionGUI.resx new file mode 100644 index 000000000..e00f98156 --- /dev/null +++ b/src/client/spark/NMSheets/Outside/tc2/GUI/SpreadPositionGUI.resx @@ -0,0 +1,139 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 1.3 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + False + + + Private + + + Private + + + False + + + False + + + True + + + True + + + 80 + + + (Default) + + + False + + + Private + + + SpreadPositionGUI + + + 8, 8 + + \ No newline at end of file diff --git a/src/client/spark/NMSheets/UIComponents/MainSheet/NMSheetControl.cs b/src/client/spark/NMSheets/UIComponents/MainSheet/NMSheetControl.cs index 2bc1db2ab..246e66763 100644 --- a/src/client/spark/NMSheets/UIComponents/MainSheet/NMSheetControl.cs +++ b/src/client/spark/NMSheets/UIComponents/MainSheet/NMSheetControl.cs @@ -514,20 +514,26 @@ namespace BCG { bool originated_externally, int initial_size, SpreadInititialState initial_state) { - // if (_sheet_data != null && _sheet_data.security_exist(nmsheet_expiration, option_strike)) { - // IDictionary driver_map = _sheet_data.get_driver_data(); - // NMSheetDriverData driver_data = null; - // driver_map.TryGetValue(nmsheet_expiration, out driver_data); - // if (driver_data != null) { - // OptionContract contract = new OptionContract(nmsheet_expiration.option_exchange, nmsheet_expiration.option_name, nmsheet_expiration.option_expiration, option_strike, is_call); - // if (initial_state.preset_mode == SpreadWindowMode.Click) { - // string elec_equiv_symbol = ContractUtilities.get_electronic_equivelant(bts.o2.msgs.SecurityType.OPTION, contract.product); - // contract = new OptionContract(contract.exchange, elec_equiv_symbol, contract.expiration, contract.strike, contract.isCall); - // } - // PriceSpec price_spec = new PriceSpec(contract.product, driver_data.driver_symbol, driver_data.driver_expiration, 0, (driver_data.is_frozen && initial_state.preset_mode == SpreadWindowMode.Greeks) ? driver_data.driver_price_at_computed_theo : -1, -1); - // _threaded_bb.sec_thread_write(new AddSpreadLegTag(), new AddSpreadLegMessage(this, contract, price_spec, originated_externally, initial_size, initial_state)); - // } - // } + if (_sheet_data != null && _sheet_data.security_exist(nmsheet_expiration, option_strike)) { + IDictionary driver_map = _sheet_data.get_driver_data(); + NMSheetDriverData driver_data = null; + driver_map.TryGetValue(nmsheet_expiration, out driver_data); + if (driver_data != null) { + OptionContract contract = new OptionContract(nmsheet_expiration.option_exchange, nmsheet_expiration.option_name, nmsheet_expiration.option_expiration, option_strike, is_call); + // if (initial_state.preset_mode == SpreadWindowMode.Click) { + // string elec_equiv_symbol = ContractUtilities.get_electronic_equivelant(bts.o2.msgs.SecurityType.OPTION, contract.product); + // contract = new OptionContract(contract.exchange, elec_equiv_symbol, contract.expiration, contract.strike, contract.isCall); + // } + PriceSpec price_spec = new PriceSpec(contract.product, driver_data.driver_symbol, + driver_data.driver_expiration, 0, (driver_data.is_frozen && initial_state.preset_mode == SpreadWindowMode.Greeks) ? + driver_data.driver_price_at_computed_theo : -1, -1); + bts.Log.Ui.info(String.Format("NMSheetControls._add_spread_leg publishing AddSpreadLegMessage for contract: {0}", + contract.expiration.ToShortDateString() + contract.strike)); + _threaded_bb.post(SparkTags.SpreadBoxTags.AddSpreadLegTag, + new AddSpreadLegMessage(this, contract, price_spec, + originated_externally, initial_size, initial_state)); + } + } } private void _launch_order_ticket(NMSheetTheoGrid.GridCell cell) { @@ -544,26 +550,21 @@ namespace BCG { } private void _handle_spread_initialization(NMSheetTheoGrid.GridCell cell, int leg_size) { - _launch_order_ticket(cell); - // if (cell.expiration != null && !String.IsNullOrEmpty(cell.expiration.option_name)) { - // SpreadInititialState state = null; - // if (cell.col == NMSheetColumnName.call_bid_price || cell.col == NMSheetColumnName.call_bid_size || cell.col == NMSheetColumnName.put_bid_price || cell.col == NMSheetColumnName.put_bid_size) - // state = new SpreadInititialState() { preset_mode = SpreadWindowMode.Click, preset_trading_side = InitialTradingSideHint.Sell }; - // if (cell.col == NMSheetColumnName.call_ask_price || cell.col == NMSheetColumnName.call_ask_size || cell.col == NMSheetColumnName.put_ask_price || cell.col == NMSheetColumnName.put_ask_size) - // state = new SpreadInititialState() { preset_mode = SpreadWindowMode.Click, preset_trading_side = InitialTradingSideHint.Buy }; - // else if (cell.col == NMSheetColumnName.call_theo || cell.col == NMSheetColumnName.put_theo || - // cell.col == NMSheetColumnName.call_quoteset_mid_price || cell.col == NMSheetColumnName.put_quoteset_mid_price || - // cell.col == NMSheetColumnName.straddle || cell.col == NMSheetColumnName.quoteset_mid_price_straddle || - // cell.col == NMSheetColumnName.strike) - // state = new SpreadInititialState() { preset_mode = SpreadWindowMode.Greeks }; - // if (state != null) { - // if (cell.call_selected) - // _add_spread_leg(cell.expiration, cell.strike, true, false, leg_size, state); - // if (cell.put_selected) - // _add_spread_leg(cell.expiration, cell.strike, false, false, leg_size, state); - // } - // _handle_task_mouse_event(cell); - // } + if (cell.expiration != null && !String.IsNullOrEmpty(cell.expiration.option_name)) { + SpreadInititialState state = new SpreadInititialState(); + if (cell.col == NMSheetColumnName.call_bid_price || cell.col == NMSheetColumnName.call_bid_size || + cell.col == NMSheetColumnName.put_bid_price || cell.col == NMSheetColumnName.put_bid_size || + cell.col == NMSheetColumnName.call_ask_price || cell.col == NMSheetColumnName.call_ask_size || + cell.col == NMSheetColumnName.put_ask_price || cell.col == NMSheetColumnName.put_ask_size) { + _launch_order_ticket(cell); + } else if (cell.col == NMSheetColumnName.call_theo || cell.col == NMSheetColumnName.put_theo || + cell.col == NMSheetColumnName.straddle || cell.col == NMSheetColumnName.strike) { + if (cell.call_selected) + _add_spread_leg(cell.expiration, cell.strike, true, false, leg_size, state); + if (cell.put_selected) + _add_spread_leg(cell.expiration, cell.strike, false, false, leg_size, state); + } + } } private bool _single_click_spread = true; @@ -609,6 +610,11 @@ namespace BCG { #region Rightclick/Context menu private void _handle_right_click(NMSheetTheoGrid.GridCell cell) { _last_rightclick_cell = cell; + if (cell.col == NMSheetColumnName.call_theo || cell.col == NMSheetColumnName.put_theo || + cell.col == NMSheetColumnName.straddle || cell.col == NMSheetColumnName.strike) { + _handle_spread_initialization(cell, -1); + return; + } foreach (ToolStripItem i in _contextmenustrip_main.Items) { if (i.Tag != null && i.Tag is NMSheetExpiration) { NMSheetExpiration this_menu_exp = i.Tag as NMSheetExpiration; diff --git a/src/client/spark/SpreadBox/Bus/AddSpreadLegMessage.cs b/src/client/spark/SpreadBox/Bus/AddSpreadLegMessage.cs new file mode 100644 index 000000000..eacb25dc7 --- /dev/null +++ b/src/client/spark/SpreadBox/Bus/AddSpreadLegMessage.cs @@ -0,0 +1,41 @@ +using System; +using BCG; +using BCG.Utilities; +using System.Windows.Forms; + +namespace BCG +{ + /// + /// Value written to the blackboard when a new contract is selected for + /// inclusion on a (possibly new) spread. Contains both the new contract + /// specification and the form on which the request was originally made. + /// The form parameter is used so that a new spread form can be show in + /// a position close to the form where the request originated. The spec + /// parameter is used to determine the default price specification in + /// the case of a previously empty SpreadSpec. + /// + public class AddSpreadLegMessage + { + private AddSpreadLegMessage(Control f, OptionContract c, PriceSpec spec) + { + originForm = f; + contract = c; + this.spec = spec; + } + + public AddSpreadLegMessage(Control f, OptionContract c, PriceSpec spec, bool theOriginatedExternally, int theLegSize, SpreadInititialState the_initial_state) + : this (f, c, spec) + { + originatedExternally = theOriginatedExternally; + legSize = theLegSize; + initial_state = the_initial_state; + } + + public Control originForm; + public OptionContract contract; + public PriceSpec spec; + public int legSize; + public bool originatedExternally = false; + public SpreadInititialState initial_state; + } +} diff --git a/src/client/spark/SpreadBox/Bus/SpreadAdvisor.cs b/src/client/spark/SpreadBox/Bus/SpreadAdvisor.cs new file mode 100644 index 000000000..c067b3e52 --- /dev/null +++ b/src/client/spark/SpreadBox/Bus/SpreadAdvisor.cs @@ -0,0 +1,160 @@ +using System; +using BCG; +using BCG.Utilities; + +using mbts.spark; +using bts.api; +using mbts.ui; + +namespace BCG { + /// + /// Listens to a specific SpreadSpecs, and: + /// If the SpreadSpec position was never directly edited + /// by the user then suggests positions according to the + /// contracts in the SpreadSpec. Also short and long spread + /// names are suggested. + /// Once the positions are edited by the user then only + /// name suggestion takes place the contract + /// proportions are used to search for compatible spreads. + /// + public class SpreadAdvisor : IDisposable { + //private readonly Blackboard myBB; + private ThreadedBlackboard _bb; + private readonly ITag _spread_spec_tag; + private readonly ITag _spread_value_tag; + private readonly ITag _kill_tag = SparkTags.SpreadBoxTags.KillSpreadTag; + private readonly string _spread_id; + private readonly ITheoInsensitiveSpread[] _theo_insensitive_spreads; + private readonly ITheoSensitiveSpread[] _theo_sensitive_spreads; + private readonly bool _disabled_initially = false; + + public SpreadAdvisor(ThreadedBlackboard bb, string spread_id, bool disabled_initially) { + _bb = bb; + _disabled_initially = disabled_initially; + _spread_spec_tag = SparkTags.SpreadBoxTags.SpreadSpecTag(spread_id); + _spread_value_tag = SparkTags.SpreadBoxTags.SpreadValueTag(spread_id); + _spread_id = spread_id; + _theo_insensitive_spreads = new ITheoInsensitiveSpread[] + { + new CallSpread(), + new PutSpread(), + new SingleOptionSpread(), + new ChristmasTreeSpread(), + new CondorSpread(), + new StraddleSpread(), + new IronButterflySpread(), + new CallPutSwapSpread(), + new RollSpread(), + new CrossMonthButterfly(), + new StraddleSwapSpread(), + new BoxSpread(), + new ButterflySpread() + }; + + _theo_sensitive_spreads = new ITheoSensitiveSpread[] + { + new RiskReversalSpread(), + new CallPutTimeSpread() + }; + _bb.subscribe(_spread_spec_tag); + _bb.subscribe(_spread_value_tag); + _bb.subscribe(_kill_tag); + _bb.data_callback += _on_data; + myUpdate(); + } + + private void myUpdate() { + // SpreadWindowSettings spread_window_settings = ShellUserSettingsHelper.get_spread_window_settings(myBB) ?? new SpreadWindowSettings(); + // if (spread_window_settings.layout_settings.spread_initialization_action == SpreadInitialization.LeftClickBuyRightClickSell || + // spread_window_settings.layout_settings.spread_initialization_action == SpreadInitialization.RightUpSwipeBuyRightDownSwipeSell) + _update_name_only(); + // else + // _update_smart(); + } + + // private void _update_smart() { + // if (!myDisabledInitially) { + // SpreadValue sv = (SpreadValue) + // myBB.read(mySpreadValueTag); + + // if (sv == null) + // return; + + // SpreadSpec newSpread = null; + // SpreadSpec spec = sv.spec; + // bool hasMatched = false; + + // foreach (ITheoInsensitiveSpread st in myTheoInsensitiveSpreads) { + // if (st.matches(spec, out newSpread)) { + // hasMatched = true; + // break; + // } + // } + + + // if (!hasMatched) + // foreach (ITheoSensitiveSpread st in myTheoSensitiveSpreads) + // if (st.matches(sv, out newSpread)) { + // hasMatched = true; + // break; + // } + + // if (!hasMatched) { + // DefaultSpread def = new DefaultSpread(); + // def.matches(spec, out newSpread); + // } + + // if (newSpread != null) { + // SpreadWindowSettings spread_window_settings = ShellUserSettingsHelper.get_spread_window_settings(myBB) ?? new SpreadWindowSettings(); + // if (spread_window_settings.layout_settings.spread_leg_display_order != SpreadLegDisplayOrder.Sorted) { + // newSpread = SpreadSpec.changeSpreadLegOrder(spec, newSpread); + // } + // myBB.write(mySpreadSpecTag, newSpread); + // } + // } + // } + + private string _last_processed_spec_desc = String.Empty; + private void _update_name_only() { + try { + SpreadValue sv = _bb.read_state(_spread_value_tag); + if (sv == null || sv.spec == null) + return; + else { + string new_spread_desc = SpreadSpec.getSpreadDefinition(sv.spec); + if (new_spread_desc != _last_processed_spec_desc) { + _last_processed_spec_desc = new_spread_desc; + System.Collections.Generic.List all_symbols; + string sym, detail, summary, long_spec; + SingleSpreadLeg[] legs; + SpreadInterpreter.interpret(new_spread_desc, + out sym, out all_symbols, out legs, out detail, out summary, out long_spec); + _bb.post(_spread_spec_tag, + new SpreadSpec(sv.spec.contracts, long_spec, summary, sv.spec.wasEdited)); + } + } + } catch (Exception ex) { + bts.Log.Ui.error(ex.Message); + } + } + + #region IDisposable Members + + private void _on_data(object tag, object data) { + if (tag.Equals(_spread_value_tag)) { + myUpdate(); + } else if (tag.Equals(_kill_tag)) { + string spread_id = _bb.read_state(_kill_tag); + if (spread_id == _spread_id) { + Dispose(); + } + } + } + + public void Dispose() { + _bb.data_callback += _on_data; + } + + #endregion + } +} diff --git a/src/client/spark/SpreadBox/Bus/SpreadDisplayForm.cs b/src/client/spark/SpreadBox/Bus/SpreadDisplayForm.cs new file mode 100644 index 000000000..15a07da6e --- /dev/null +++ b/src/client/spark/SpreadBox/Bus/SpreadDisplayForm.cs @@ -0,0 +1,381 @@ +using System; +using System.Drawing; +using System.Collections; +using System.Collections.Generic; +using System.Linq; +using System.IO; +using System.ComponentModel; +using System.Windows.Forms; +using System.Reflection; +using System.Runtime.InteropServices; + +using BCG.Utilities; +using BCG.Utilities.General; +using mbts.spark; +using bts.api; + +namespace BCG { + // 3.7.12 : changed the call to SpreadUI.init (line 498) + /// + /// reads : KillSpreadTag, (if someone external kills this spread) + /// CurrentSpreadTag, + /// SpreadSpecTag (in commit) - this is not needed + /// SpreadValueTag (in commit) + /// ProductConfigTableTag, TheoGridConfigTag, SpreadConfigTag + /// writes : KillSpreadTag, + /// SpreadLockedTag, + /// CurrentSpreadTag, + /// SpreadSpecTag (for changes made in the spreadUI) + /// + public class SpreadDisplayForm : Form { + private bool myLockedForSpreads = false; + private bool myWasClosed = false; + private ITag myKillSpreadTag = SparkTags.SpreadBoxTags.KillSpreadTag; + private ITag mySpreadValueTag; + private string mySpreadId; + private ITag mySpreadSpecTag; + private SpreadUI mySpreadControl; + private ITag myCurrentSpreadTag; + private ITag mySpreadLockedTag; + private ITag _spread_min_tag = SparkTags.SpreadBoxTags.SpreadWindowMinimizeTag; + ThreadedBlackboard _bb; + + //private Blackboard myBB; + private readonly string _user; + private static Hashtable myOriginForms = new Hashtable(); + private System.Windows.Forms.Timer _timer = new Timer(); + + private SpreadDisplayForm(ThreadedBlackboard bb, string spreadId, Control originForm, SpreadInititialState initial_state, string user) { + _user = user; + _bb = bb; + // Icon = new System.Drawing.Icon(System.Windows.Application.GetResourceStream(uri).Stream); + Visible = false; + InitializeComponent(); + SetStyle(ControlStyles.DoubleBuffer, true); + mySpreadControl.onNewSpec += new GUIChange(myOnNewSpec); + mySpreadControl.onLocked += new GUIChange(myOnLockStateChange); + mySpreadControl.onSizeChange += new GUIChange(myOnSpreadUIResize); + mySpreadControl.onTrade += new EventHandler(myHandleTrade); + myInit(spreadId, originForm, initial_state); + VisibleChanged += (o, e) => myRefresh(); + } + + private void myInit(string spreadId, Control originForm, SpreadInititialState initial_state) { + mySpreadControl.spread_id = spreadId; + myLockedForSpreads = false; + myWasClosed = false; + mySpreadId = spreadId; + myKillSpreadTag = SparkTags.SpreadBoxTags.KillSpreadTag; + mySpreadValueTag = SparkTags.SpreadBoxTags.SpreadValueTag(spreadId); + mySpreadSpecTag = SparkTags.SpreadBoxTags.SpreadSpecTag(spreadId); + myCurrentSpreadTag = SparkTags.SpreadBoxTags.CurrentSpreadTag; + mySpreadLockedTag = SparkTags.SpreadBoxTags.SpreadLockedTag(spreadId); + _bb.subscribe(mySpreadSpecTag); + _bb.subscribe(myKillSpreadTag); + _bb.subscribe(mySpreadValueTag); + _bb.data_callback += _on_data; + + if (myOriginForms[originForm] == null) + myOriginForms[originForm] = 0; + + /// clicking windows should always start at the same place + bool location_set = false; + SpreadSpec spec = _bb.read_state(mySpreadSpecTag); + string symbol = myGetSymbol(); + if (!String.IsNullOrEmpty(symbol)) { + SpreadWindowSettings spread_window_settings = ShellUserSettingsHelper.get_spread_window_settings(_bb) ?? new SpreadWindowSettings(); + if (spread_window_settings.layout_settings.spread_window_startup_location == WindowStartupLocation.LastWindowLocation) { + FormConfig f_conf = _bb.read_state(SparkTags.SpreadBoxTags.SpreadFormLocationTag(symbol)); + if (f_conf != null) { + Location = new Point(f_conf.left, f_conf.top); + location_set = true; + } + } + } + if (!location_set) + mySetLocationToDefaultLocation(originForm); + _adjust_for_phantom_location(); + myOriginForms[originForm] = (int)myOriginForms[originForm] + 1; + mySpreadControl.Focus(); + _timer.Interval = 1; + _timer.Enabled = true; + _timer.Tick += new EventHandler(_on_timer_tick); + SizeChanged += _on_size_changed; + } + + private bool _form_minimized = true; + private void _on_size_changed(object sender, EventArgs e) { + if (WindowState != FormWindowState.Minimized && _form_minimized) + myRefresh(); + _form_minimized = WindowState == FormWindowState.Minimized; + } + + void _on_timer_tick(object sender, EventArgs e) { + bts.Log.assert(!Visible); + _timer.Tick -= new EventHandler(_on_timer_tick); + _timer.Dispose(); + Show(); + } + + private void mySetLocationToDefaultLocation(Control originForm) { + int cascadingIndex = (int)myOriginForms[originForm] % 10; + this.Left = originForm.Left + originForm.Width - this.Width - cascadingIndex * 30; + this.Top = originForm.Top + cascadingIndex * 30 + 80; + } + + private void _adjust_for_phantom_location() { + if (!_is_window_visible(new Rectangle(Location, new Size(1, 1)))) + Top = Left = 16; + } + + internal static bool _is_window_visible(Rectangle rect) { + foreach (Screen screen in Screen.AllScreens) + if (screen.Bounds.IntersectsWith(rect)) + return true; + return false; + } + + private void _trading_strip_size_changed(object sender, EventArgs e) { + //myResizeToFitControls(); + } + + private void myDeactivate() { + SizeChanged -= _on_size_changed; + string symbol = myGetSymbol(); + if (!String.IsNullOrEmpty(symbol)) + _bb.post(SparkTags.SpreadBoxTags.SpreadFormLocationTag(symbol), + new FormConfig(Location.X, Location.Y, Height, Width)); + mySpreadControl.setTimesSpread(1); + mySpreadControl.hideEnhancedValue(); + _bb.data_callback -= _on_data; + } + + private string myGetSymbol() { + SpreadSpec spec = _bb.read_state(mySpreadSpecTag); + if (spec != null && spec.contracts != null && spec.contracts.Length > 0) + return spec.contracts[0].contract.product; + else + return String.Empty; + } + + protected override void Dispose(bool disposing) { + if (disposing) { + if (_bb != null) { + _bb.data_callback -= _on_data; + if (!myWasClosed) { + myWasClosed = true; + _bb.post(myKillSpreadTag, mySpreadId); + if (_bb.read_state(myCurrentSpreadTag) != null && _bb.read_state(myCurrentSpreadTag).Equals(mySpreadId)) { + _bb.post(mySpreadLockedTag, null); + _bb.post(myCurrentSpreadTag, null); + } + } + } + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() { + this.mySpreadControl = new SpreadUI(); + this.SuspendLayout(); + // + // mySpreadControl + // + this.mySpreadControl.BackColor = System.Drawing.SystemColors.Control; + this.mySpreadControl.Dock = System.Windows.Forms.DockStyle.Fill; + this.mySpreadControl.Font = new System.Drawing.Font("Arial Narrow", 8F); + this.mySpreadControl.Location = new System.Drawing.Point(0, 0); + this.mySpreadControl.Name = "mySpreadControl"; + this.mySpreadControl.Size = new System.Drawing.Size(258, 125); + this.mySpreadControl.TabIndex = 0; + // + // SpreadDisplayForm + // + this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); + this.ClientSize = new System.Drawing.Size(258, 125); + this.Controls.Add(this.mySpreadControl); + this.Font = new System.Drawing.Font("Arial", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle; + this.MaximizeBox = false; + this.Name = "SpreadDisplayForm"; + this.StartPosition = System.Windows.Forms.FormStartPosition.Manual; + this.Text = "Spread"; + this.TopMost = true; + this.Activated += new System.EventHandler(this.SpreadDisplayForm_Activated); + this.Closing += new System.ComponentModel.CancelEventHandler(this.SpreadDisplayForm_Closing); + this.Resize += new System.EventHandler(this.SpreadDisplayForm_Resize); + this.ResumeLayout(false); + + } + #endregion + + public static SpreadDisplayForm make(ThreadedBlackboard bb, string spreadId, + Control originForm, SpreadInititialState initial_state, string user) { + var f = new SpreadDisplayForm(bb, spreadId, originForm, initial_state, user); + return f; + } + + private void _on_data(object tag, object data) { + if (tag.Equals(myKillSpreadTag) && data.Equals(mySpreadId)) { + myDeactivate(); + Close(); + } else if (tag.Equals(myCurrentSpreadTag) && data.Equals(mySpreadId)) { + Activated -= new System.EventHandler(SpreadDisplayForm_Activated); + myRestoreForm(); + Activated += new System.EventHandler(SpreadDisplayForm_Activated); + } else if (tag.Equals(mySpreadValueTag)) // || tag is ProductConfigTableTag || tag is TheoGridConfigTag || tag is SpreadWindowSettingsTag) + { + myRefresh(); + if (tag.Equals(mySpreadValueTag)) { + SpreadValue sv = _bb.read_state(mySpreadValueTag); + if (sv == null || sv.spec == null || sv.spec.contracts == null || sv.spec.contracts.Length == 0) + Close(); + } + } else if (_spread_min_tag.Equals(tag)) { + WindowState = FormWindowState.Minimized; + } + } + + private void myRestoreForm() { + if (WindowState != FormWindowState.Normal) + WindowState = FormWindowState.Normal; + BringToFront(); + Activate(); + } + + private void myRefresh() { + if (WindowState != FormWindowState.Minimized && Visible) { + SpreadValue sv = _bb.read_state(mySpreadValueTag); + if (sv != null) { + bts.Log.Ui.info("SpreadValue.myRefresh"); + //BCG.Utilities.General.HighPerformanceTimer perf_timer = new HighPerformanceTimer(); + //perf_timer.start(); + Hashtable infos = new Hashtable(); + foreach (OptionContractPosition p in sv.spec.contracts) { + // object pconfig = myBB.read(new ProductConfigTableTag(p.contract.product)); + // GridConfig gridconfig = (GridConfig)myBB.read(new TheoGridConfigTag(p.contract.product)); + // if (gridconfig == null) + // gridconfig = new GridConfig(); + SpreadWindowSymbolBasedFormatting formatting = + ShellUserSettingsHelper.get_spread_window_display_formatting( + p.contract.exchange, p.contract.product, _bb); + TickConverter2.TickType theo_format = formatting.theo_format; + TickConverter2.TickType driver_format = formatting.driver_format; + double driver_shift_interval = formatting.driver_shift_interval; + // if (pconfig != null) + // { + // TickConverter2.TickType secondaryFormat = ProductConfigTableTag.getSecondaryFormatEnum(pconfig); + // TickConverter2.TickType strikeFormat = TickTypeResolver.getTickType(p.contract.product, TickTypeResolver.ValueType.strike); + + + // infos[p.contract.product] = new SpreadUI.SpreadProductInfo(new TheoFormatter(theo_format, strikeFormat), + // driver_format, + // secondaryFormat, + // driver_shift_interval, + // ProductConfigTableTag.getSecondaryAnchorInterval(pconfig), + // ProductConfigTableTag.getShowSecondaryAnchor(pconfig), + // gridconfig); + // } + // else + { + infos[p.contract.product] = new SpreadUI.SpreadProductInfo(new TheoFormatter(theo_format), + driver_format, + TickConverter2.TickType.tickDecimal2, + driver_shift_interval, + 0.25, false); + } + } + + SpreadWindowSettings spread_window_settings = ShellUserSettingsHelper.get_spread_window_settings(_bb) ?? new SpreadWindowSettings(); + + mySpreadControl.init(sv, infos, spread_window_settings); + mySetCaption(); + myResizeToFitControls(); + //string log_msg = String.Format("SpreadDisplayForm.myRefresh {0} legs {1} msecs", sv.spec.contracts.Length, perf_timer.lastIntervalTime); + //System.Diagnostics.Trace.WriteLine(String.Format("SpreadDisplayForm.myRefresh {0} legs {1} msecs", sv.spec.contracts.Length, perf_timer.lastIntervalTime)); + //mbts.Logger.log(bts.log.Level.Diag, bts.log.Subsystem.ui, log_msg); + } + } + } + + private void mySetCaption() { + SpreadSpec spec = _bb.read_state(mySpreadSpecTag); + if (spec != null) { + string detail, summary; + get_spread_info(spec, out detail, out summary); + SpreadWindowSettings spread_window_settings = ShellUserSettingsHelper.get_spread_window_settings(_bb) ?? new SpreadWindowSettings(); + string header_text = spread_window_settings.header_settings.show_detailed_title ? String.Format("{0} {1}", summary, detail) : summary; + Text = String.Format("{0} {1}", header_text, _get_edge_str()); + } + //Text = "TODO"; + } + + private string _get_edge_str() { + return String.Empty; + } + + internal static void get_spread_info(SpreadSpec spec, out string detail, out string summary) { + string sprText = String.Empty; + foreach (OptionContractPosition p in spec.contracts) + sprText += p.contract.product + " " + + p.contract.expiration.ToShortDateString() + " " + p.contract.strike.ToString() + " " + + (p.contract.isCall ? "C" : "P") + " " + p.position.ToString() + ";"; + SpreadInterpreter.interpret(sprText, out detail, out summary); + + } + + private void myResizeToFitControls() { + Size window_client_size = mySpreadControl.minSize; + window_client_size.Width += 1; + window_client_size.Height += 1; + ClientSize = window_client_size; + } + + private void myOnNewSpec(object sender, object spec) { + if (spec == null) + return; + bts.Log.assert(spec is SpreadSpec); + if (!myWasClosed) + _bb.post(mySpreadSpecTag, spec as SpreadSpec); + } + + private void myOnLockStateChange(object sender, object isLocked) { + if (!myWasClosed) { + _bb.post(mySpreadLockedTag, new SpreadBoxLockedState(myLockedForSpreads = (bool)isLocked)); + if (!myLockedForSpreads) + _bb.post(myCurrentSpreadTag, mySpreadId); + } + } + + private void SpreadDisplayForm_Closing(object sender, System.ComponentModel.CancelEventArgs e) { + Hide(); + e.Cancel = true; + myWasClosed = true; + _bb.post(myKillSpreadTag, mySpreadId); + _bb.post(mySpreadLockedTag, null); + _bb.post(myCurrentSpreadTag, null); + } + + private void SpreadDisplayForm_Activated(object sender, System.EventArgs e) { + if (!myLockedForSpreads) + _bb.post(myCurrentSpreadTag, mySpreadId); + } + + private void myHandleTrade(object sender, EventArgs e) { } + + private void SpreadDisplayForm_Resize(object sender, System.EventArgs e) { + if (this.WindowState == FormWindowState.Minimized && + mySpreadId.Equals(_bb.read_state(myCurrentSpreadTag))) { + _bb.post(mySpreadLockedTag, null); + _bb.post(myCurrentSpreadTag, null); + } + } + + private void myOnSpreadUIResize(object sender, object value) { myResizeToFitControls(); } + } +} diff --git a/src/client/spark/SpreadBox/Bus/SpreadDisplayForm.resx b/src/client/spark/SpreadBox/Bus/SpreadDisplayForm.resx new file mode 100644 index 000000000..d58980a38 --- /dev/null +++ b/src/client/spark/SpreadBox/Bus/SpreadDisplayForm.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/src/client/spark/SpreadBox/Bus/SpreadManager.cs b/src/client/spark/SpreadBox/Bus/SpreadManager.cs new file mode 100644 index 000000000..3d7258f6d --- /dev/null +++ b/src/client/spark/SpreadBox/Bus/SpreadManager.cs @@ -0,0 +1,304 @@ +using System; +using System.Windows.Forms; +using System.Collections; +using System.Collections.Generic; +using bts.api; +using mbts.spark; +using mbts; + +namespace BCG { + /// + /// Listens to spreads being added via the gui, and publishes the corresponding SpreadSpecs. Is also responsible + /// for managing SpreadForms and calculator + /// 3/7/12 : Changed arg to MultiplierStream, to enable the proxy + /// Reads : AddSpreadLegTag, + /// Writes : SpreadSpecTag + /// SpreadLockedTag + /// CurrentSpreadTag + /// + + public enum SpreadInitialization { + SingleClickSystem = 0, + DoubleClickSystem = 1, + LeftClickBuyRightClickSell = 2, + RightUpSwipeBuyRightDownSwipeSell = 3 + } + + public class SpreadBoxLockedState { + public bool locked = false; + public SpreadBoxLockedState(bool locked_arg) { + locked = locked_arg; + } + } + + public class SpreadManager { + public enum SpreadInitialization { + DoubleClickSystem = 0, + SingleClickSytstem = 1, + LeftClickBuyRightClickSell = 2, + RightUpSwipeBuyRightDownSwipeSell = 3 + } + + private ThreadedBlackboard _bb; + private readonly string _user; + private readonly ITag _add_leg_tag = SparkTags.SpreadBoxTags.AddSpreadLegTag; + + public SpreadManager(ThreadedBlackboard bb, string user) { + _bb = bb; + _user = user; + _bb.subscribe(_add_leg_tag); + _bb.data_callback += _on_data; + } + + private void _on_data(object tag, object data) { + if (tag.Equals(_add_leg_tag)) { + AddSpreadLegMessage m = _bb.read_state(_add_leg_tag); + myHandleNewSpreadLeg(m.originForm, m.contract, m.spec, m.originatedExternally, + m.legSize, m.initial_state, _user); + } + } + + // #region IAgent Members + + // public void begin() {} + + // public void change (object tag) + // { + // if (tag.Equals (new AddSpreadLegTag ())) + // { + // AddSpreadLegMessage m = _bb.read (tag) as AddSpreadLegMessage; + // myHandleNewSpreadLeg(m.originForm, m.contract, m.spec, m.originatedExternally, m.legSize, m.initial_state, _user); + // } + // else if (tag.Equals (new ExternalSpreadTradeRequestTag ())) + // { + // ExternalSpreadTradeRequest spread_trade_request = _bb.read (tag) as ExternalSpreadTradeRequest; + // mbts.Logger.log(String.Format("Received spread {0} ", spread_trade_request.ToString())); + // SpreadUtilities.SpreadType type = SpreadUtilities.getSpreadType(spread_trade_request.bts_spread_def); + // if (type == SpreadUtilities.SpreadType.PureOptions || type == SpreadUtilities.SpreadType.Covered) + // { + // bool completely_resolved; + // string error_message; + // SpreadSpec spec = _convert_to_spreadspec(spread_trade_request.bts_spread_def, spread_trade_request.exchange, out completely_resolved, out error_message); + // if (completely_resolved && spec != null && spec.contracts != null && spec.contracts.Length > 0) + // myCreateBrandNewSpreadWhole(spec, spread_trade_request.originating_control, true, spread_trade_request.initial_state, _user); + // else + // { + // if (spread_trade_request != null && spread_trade_request.bts_spread_def != null) + // _bb.write(new MessageDisplayTag(), new MessageDisplayData("Click Trading Error", String.Format("Unable to launch \n{0}\n{1}", spread_trade_request.bts_spread_def, error_message))); + // } + // } + // } + // } + + // public void commit(IDictionary changedTags) { } + + // #endregion + + // private SpreadSpec _convert_to_spreadspec(string bts_desc, Exchange.type exchange, out bool completely_resolved, out string error_message) + // { + // error_message = String.Empty; + // completely_resolved = true; + // SpreadUtilities.SpreadType type = SpreadUtilities.getSpreadType(bts_desc); + // SingleSpreadLeg[] legs = SingleSpreadLeg.parse(bts_desc); + // List rv = new List(); + // if (type == SpreadUtilities.SpreadType.Covered) + // { + // /// assumption is that all legs are + // /// driven by the same future + // /// (can there be 2 diff future exps + // /// in a covered spread) + // SingleSpreadLeg[] option_legs, future_legs; + // SpreadUtilities.parseLegs(legs, out option_legs, out future_legs); + // if (future_legs.Length > 1) + // { + // error_message = "Covered Spreads with multiple future legs are not supported"; + // completely_resolved = false; + // return null; + // } + // foreach (SingleSpreadLeg l in option_legs) + // { + // rv.Add(new OptionContractPosition(new OptionContract(exchange, l.symbol, l.exp, l.strike, l.isCall()), l.size, + // new PriceSpec(l.symbol, future_legs[0].symbol, future_legs[0].exp, future_legs[0].size, future_legs[0].strike, -1.0))); + // } + // return new SpreadSpec(rv.ToArray()); + // } + // else if (type == SpreadUtilities.SpreadType.PureOptions) + // { + // foreach (SingleSpreadLeg l in legs) + // { + // PriceSpec leg_price_spec = null; + // object v = _bb.read(new MarketDataTags.OptionDriverBBOTag(l.symbol)); + // if (v != null) + // { + // Dictionary> option_exp_to_driver_data = (Dictionary>)v; + // Triplet fut_exp_data = null; + // if (option_exp_to_driver_data.TryGetValue(l.exp, out fut_exp_data)) + // { + // leg_price_spec = new PriceSpec(l.symbol, fut_exp_data.first, fut_exp_data.second, 0.0, -1.0, -1.0); + // } + // } + // if (leg_price_spec != null) + // rv.Add(new OptionContractPosition(new OptionContract(exchange, l.symbol, l.exp, l.strike, l.isCall()), l.size, leg_price_spec)); + // else + // { + // error_message = String.Format("Could not find the driver security"); + // completely_resolved = false; + // return null; + // } + // } + // } + // return new SpreadSpec(rv.ToArray()); + // } + + /// + /// Returns an unlocked spread + /// + private string mySearchLocking(string current) { + if (current != null) { + SpreadBoxLockedState locked = _bb.read_state(SparkTags.SpreadBoxTags.SpreadLockedTag(current)); + if (locked != null && !locked.locked) + return current; + } + List remove = new List(); + string ret = null; + foreach (string o in _id_map) { + SpreadBoxLockedState locked = _bb.read_state(SparkTags.SpreadBoxTags.SpreadLockedTag(o)); + if (locked == null) { + remove.Add(o); + continue; + } + if (!locked.locked) + ret = o; + } + _id_map.removeRange(remove); + return ret; + } + + /// + /// This is the only function in this class where BB items are written + /// 1. SpreadSpecTag + /// and if the spread is newly created + /// 1. SpreadSpecTag + /// 2. SpreadLockedTag + /// 3. CurrentSpreadTag + /// + private object myHandleNewSpreadLeg(Control originForm, OptionContract newLegContract, + PriceSpec newLegPriceSpec, bool originatedExternally, int newLegSize, + SpreadInititialState initial_state, string user) { + if (initial_state.preset_mode == SpreadWindowMode.Click) { + /// so any new CT click will open a new outrigth CT window, instead + /// of adding the leg to an existing spread + return myCreateBrandNewSpread(newLegContract, newLegPriceSpec, newLegSize, originForm, false, initial_state, user); + } else { + string currentSpreadId = _bb.read_state(SparkTags.SpreadBoxTags.CurrentSpreadTag, null); + currentSpreadId = mySearchLocking(currentSpreadId); + if (currentSpreadId != null) { + SpreadSpec spreadSpec = _bb.read_state(SparkTags.SpreadBoxTags.SpreadSpecTag(currentSpreadId)); + bts.Log.assert(spreadSpec != null, "A SpreadSpec can never be null, it can have 0 legs though"); + /// adds leg to an existing spread + + int existing_leg_index = spreadSpec.find_contract_index(newLegContract); + if (existing_leg_index >= 0) { + SpreadWindowSettings spread_window_settings = ShellUserSettingsHelper.get_spread_window_settings(_bb) ?? new SpreadWindowSettings(); + if (spread_window_settings.layout_settings.spread_initialization_action != BCG.SpreadInitialization.LeftClickBuyRightClickSell && + spread_window_settings.layout_settings.spread_initialization_action != BCG.SpreadInitialization.RightUpSwipeBuyRightDownSwipeSell) + return currentSpreadId; + else { + double new_pos = spreadSpec.contracts[existing_leg_index].position + newLegSize; + if (new_pos == 0) + spreadSpec = spreadSpec.removeContract(existing_leg_index); + else + spreadSpec = spreadSpec.changeContractPosition(existing_leg_index, new_pos); + _bb.post(SparkTags.SpreadBoxTags.SpreadSpecTag(currentSpreadId), spreadSpec); + return currentSpreadId; + } + } else { + if (initial_state.preset_mode == SpreadWindowMode.Click && (spreadSpec.contracts == null || spreadSpec.contracts.Length == 0)) + /// set it up as +ve leg for CTs + newLegSize = 1; + List t = new List(spreadSpec.contracts); + t.Add(myCreateLeg(spreadSpec, newLegContract, newLegPriceSpec, newLegSize)); + spreadSpec = new SpreadSpec(t.ToArray(), + spreadSpec.longName, + spreadSpec.shortName, + spreadSpec.wasEdited); + _bb.post(SparkTags.SpreadBoxTags.SpreadSpecTag(currentSpreadId), spreadSpec); + } + } else { + /// new spread + if (initial_state.preset_mode == SpreadWindowMode.Click) + /// set it up as +ve leg for CTs + newLegSize = 1; + currentSpreadId = myCreateBrandNewSpread(newLegContract, newLegPriceSpec, newLegSize, originForm, originatedExternally, initial_state, user); + } + return currentSpreadId; + } + } + + // private object myCreateBrandNewSpreadWhole(SpreadSpec new_spread_spec, Control origin_form, + // bool originated_externally, SpreadInititialState initial_state, string user) + // { + // string spread_id = myGetNewSpreadId(); + // _bb.post(SparkTags.SpreadBoxTags.SpreadLockedTag(spread_id), new SpreadBoxLockedState(false)); + // _bb.post(SparkTags.SpreadBoxTags.SpreadSpecTag(spread_id), new_spread_spec); + // _bb.post(SparkTags.SpreadBoxTags.CurrentSpreadTag, spread_id); + // myCreateSpreadSpecificAgents(_bb, new_spread_spec, spread_id, + // origin_form, originated_externally, initial_state, user); + // return spread_id; + // } + + private string myCreateBrandNewSpread(OptionContract newLegContract, PriceSpec newLegPriceSpec, + int newLegSize, Control originForm, bool originatedExternally, SpreadInititialState initial_state, string user) { + string spread_id = myGetNewSpreadId(); + _bb.post(SparkTags.SpreadBoxTags.SpreadLockedTag(spread_id), new SpreadBoxLockedState(false)); + SpreadSpec new_spread_spec = new SpreadSpec(new OptionContractPosition[] { new OptionContractPosition(newLegContract, newLegSize, newLegPriceSpec) }); + //myBB.write(new SpreadInitialTradingSideHintTag(newSpreadId), hint); + _bb.post(SparkTags.SpreadBoxTags.SpreadSpecTag(spread_id), new_spread_spec); + //also create a spread form here + _bb.post(SparkTags.SpreadBoxTags.CurrentSpreadTag, spread_id); + myCreateSpreadSpecificAgents(_bb, new_spread_spec, spread_id, originForm, originatedExternally, initial_state, user); + return spread_id; + } + + private void myCreateSpreadSpecificAgents(ThreadedBlackboard forBB, SpreadSpec newSpreadSpec, + string usingTag, Control originForm, bool originatedExternally, SpreadInititialState initial_state, string user) { + // TODO, no trading, that was horrible, will do it some other way + //SharedTimer.log(usingTag, "SpreadManager:myCreateSpreadSpecificAgents", "SpreadWindowLifeCycle"); + // if (newSpreadSpec.contracts.Length == 1 && initial_state.preset_mode == SpreadWindowMode.Click && + // (newSpreadSpec.contracts[0].legPriceSpec == null || newSpreadSpec.contracts[0].legPriceSpec.primaryDriverSize == 0)) + // { + // TradingStripForm f = TradingStripForm.TradingStripFormFactory.get_strip(); + // f.activate(forBB, usingTag, initial_state, user); + // } + // else + { + _bb.post(SparkTags.SpreadBoxTags.AllSpreadBoxIDsTag, _id_map); + //new SpreadAdvisor(forBB, usingTag, originatedExternally); + SpreadDisplayForm.make(forBB, usingTag, originForm, initial_state, user); + } + } + + private OptionContractPosition myCreateLeg(SpreadSpec existingSpreadSpec, OptionContract newLegContract, PriceSpec newLegPriceSpec, int newLegSize) { + /// need to check if there is a leg already withs + /// the same driver exp. This is so that if they + /// are driver by the same exp, they always + /// get the same driver size + PriceSpec existingPriceSpec = existingSpreadSpec.getPriceSpecForThisDriverExp(newLegPriceSpec.driverExpiration); + if (existingPriceSpec != null) { + newLegPriceSpec = existingPriceSpec.Clone() as PriceSpec; + bts.Log.assert(newLegPriceSpec.primaryDriverSymbol == existingPriceSpec.primaryDriverSymbol && + newLegPriceSpec.driverExpiration == existingPriceSpec.driverExpiration); + } + return new OptionContractPosition(newLegContract, newLegSize, newLegPriceSpec); + } + + /// list of all open spreads + private HashSet _id_map = new HashSet(); + private string myGetNewSpreadId() { + Guid g = Guid.NewGuid(); + string rv = g.ToString(); + _id_map.Add(rv); + return rv; + } + } +} diff --git a/src/client/spark/SpreadBox/Calculators/SimpleSpreadCalculator.cs b/src/client/spark/SpreadBox/Calculators/SimpleSpreadCalculator.cs new file mode 100644 index 000000000..69db4b346 --- /dev/null +++ b/src/client/spark/SpreadBox/Calculators/SimpleSpreadCalculator.cs @@ -0,0 +1,132 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using mbts.spark; +using mbts.ui; +using bts.api; +using mbts; + +namespace BCG { + public class SimpleSpreadCalculator : IDisposable { + private ThreadedBlackboard _bb; + public Action on_recompute; + private readonly ITag> + _future_theos_tag = SparkTags.TC2Tags.LiveFutureTheosTag; + + public SimpleSpreadCalculator(ThreadedBlackboard bb) { + bts.Log.Ui.info("Starting SimpleSpreadCalculator"); + _bb = bb; + _bb.subscribe(_future_theos_tag); + _bb.data_callback += _on_data; + } + + private void _on_data(object tag, object data) { + if (tag.Equals(_future_theos_tag)) { + on_recompute(); + } + } + + public SpreadValue compute(SpreadSpec spread_spec) { + var driver_price_map = _get_driver_map(spread_spec); + var live_theo_map = _get_live_theo_map(spread_spec); + SpreadValue sv = + StatelessSpreadCalculator.compute_any_spread(spread_spec, live_theo_map, + _get_interpolation_map(spread_spec), driver_price_map, + _get_live_future_theo_map(spread_spec), get_option_position: _get_option_position); + sv = _fill_edges(sv); + _fill_enhanced_price(spread_spec, sv, driver_price_map, live_theo_map); + return sv; + } + + private double _get_option_position(string option_symbol, + DateTime exp, double strike, bool is_call) { + // TODO + return Double.NaN; + } + + private SpreadValue _fill_edges(SpreadValue sv) { + // TODO + return sv; + } + + private void _fill_enhanced_price(SpreadSpec spec, SpreadValue sv, + Dictionary>> driver_price_map, + Dictionary> live_theo_map) { + // TODO + } + + #region Getters for drivers, theos, precomputed sparse theos + + private static Triplet _from_drivermd(DriverMD dmd) { + return new Triplet( + dmd.driver_security != null ? + dmd.driver_security.symbol_or_default() : String.Empty, + dmd.driver_security != null ? + dmd.driver_security.Value.security_expiration().Value : DateTime.MinValue, + dmd.get_driver()); + } + + // Gets the option driver map or a single option name + private Dictionary> + _get_option_driver_map(string option_name) { + IReadOnlyDictionary all_sym_map = + _bb.read_state(SparkTags.AllOptionDriverBBOTag); + OptionDriverPriceMap sym_data = null; + if (all_sym_map.TryGetValue(option_name, out sym_data) && sym_data != null) { + var rv = sym_data.exp_price_map.ToDictionary( + kv => kv.Key.expiration, + kv => _from_drivermd(kv.Value)); + return rv; + } else { + return new Dictionary>(); + } + } + + // Gets the driver map for each distinct option in the spread + private Dictionary>> + _get_driver_map(SpreadSpec spec) { + IReadOnlyDictionary all_sym_map = + _bb.read_state(SparkTags.AllOptionDriverBBOTag); + return all_sym_map.ToDictionary(kv => kv.Key, kv => _get_option_driver_map(kv.Key)); + } + + // Gets the ExpStrikeKeyedData for each unique option name in spec + private Dictionary> _get_live_theo_map(SpreadSpec spec) { + var rv = new Dictionary>(); + foreach (OptionContractPosition l in spec.contracts) + if (!rv.ContainsKey(l.contract.product)) { + ExpStrikeKeyedData sym_theos = + _bb.read_state(SparkTags.TC2Tags.LiveTheosTag(l.contract.product)) ?? + new ExpStrikeKeyedData(); + rv.Add(l.contract.product, sym_theos); + } + return rv; + } + + private Dictionary _get_interpolation_map(SpreadSpec spec) { + return new(_bb.read_state(SparkTags.AllInterpGreeks)); + } + + private Dictionary> + _get_live_future_theo_map(SpreadSpec spec) { + var rv = new Dictionary>(); + IReadOnlyDictionary fut_theo_map = + _bb.read_state(SparkTags.TC2Tags.LiveFutureTheosTag); + if (fut_theo_map != null) + foreach (var kv in fut_theo_map) { + string sym = kv.Key.symbol; + Dictionary sym_map; + if (!rv.TryGetValue(sym, out sym_map)) { + sym_map = new Dictionary(); + rv.Add(sym, sym_map); + } + sym_map[kv.Key.expiration] = kv.Value; + } + return rv; + } + + #endregion + + public void Dispose() { _bb.data_callback += _on_data; } + } +} \ No newline at end of file diff --git a/src/client/spark/SpreadBox/Calculators/SpreadCalculationSynchronizer.cs b/src/client/spark/SpreadBox/Calculators/SpreadCalculationSynchronizer.cs new file mode 100644 index 000000000..a9bacd9a8 --- /dev/null +++ b/src/client/spark/SpreadBox/Calculators/SpreadCalculationSynchronizer.cs @@ -0,0 +1,98 @@ +using mbts.spark; + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using bts.api; +using Microsoft.VisualBasic; +using mbts.ui.converters; +using System.Linq.Expressions; + +namespace BCG { + /// + /// Listens to SpreadSpec and publishes SpreadValues. Also listens to other + /// driver, vol shifts, theo shifts and republishes + /// + public class SpreadCalculationSynchronizer { + private readonly ThreadedBlackboard _bb; + private readonly ITag> _all_ids_tag = SparkTags.SpreadBoxTags.AllSpreadBoxIDsTag; + private readonly SimpleSpreadCalculator _spread_calc; + private readonly TimeSpan _throttle_period = TimeSpan.FromMilliseconds(300); + private bool _compute_all_dirty = true; + private DateTime _last_fire_time = DateTime.MinValue; + private Type _ss_tag_type = typeof(SparkTags.KeyedSparkTag); + + + public SpreadCalculationSynchronizer(ThreadedBlackboard bb) { + _bb = bb; + _spread_calc = new SimpleSpreadCalculator(_bb); + _spread_calc.on_recompute += _queue_compute_all; + _bb.subscribe(_all_ids_tag); + _bb.data_callback += _on_data; + _bb.timer_callback += _on_timer; + } + + private void _on_data(object tag, object data) { + if (tag.Equals(_all_ids_tag)) { + IEnumerable ids = _bb.read_state(_all_ids_tag); + // double subscribing doesnt do anything + foreach (string id in ids) { + _bb.subscribe(SparkTags.SpreadBoxTags.SpreadSpecTag(id)); + } + _queue_compute_all(); + return; + } else if (tag.GetType() == _ss_tag_type) { + _queue_compute_all(); + } + } + + private void _on_timer() { + if ((DateTime.Now - _last_fire_time) >= _throttle_period && _compute_all_dirty) { + try { + _last_fire_time = DateTime.Now; + _compute_all_dirty = false; + HighPerformanceTimer perf_timer = new HighPerformanceTimer(); + perf_timer.start(); + IEnumerable spread_ids = _bb.read_state(_all_ids_tag); + int count = 0; + if (spread_ids != null) { + foreach (string id in spread_ids) { + SpreadSpec ss = _bb.read_state(SparkTags.SpreadBoxTags.SpreadSpecTag(id)); + if (ss != null) { + count++; + _compute_and_publish_single_spread(id, ss); + } + } + } + perf_timer.stop(); + // bts.Log.Ui.info( + // String.Format("SpreadCalculationSynchronizer calculation compute_all {0} spreads {1} msecs", + // count, perf_timer.lastIntervalTime)); + } catch (Exception ex) { + bts.Log.Ui.error(ex.Message); + bts.Log.assert(false); + } + } + } + + private SpreadValue _compute(SpreadSpec spec) { + SpreadValue sv = _spread_calc.compute(spec); + // operations like vol shifts, theo shifts cna be handled here + return sv; + } + + private void _compute_and_publish_single_spread(string id, SpreadSpec spec) { + SpreadValue sv = _compute(spec); + bts.Log.Ui.info( + String.Format("SpreadCalculationSynchronizer._compute_and_publish_single_spread id: {0} sv: {1}", + id, sv.spec.contracts.Length)); + _bb.post(SparkTags.SpreadBoxTags.SpreadValueTag(id), sv); + } + + private void _queue_compute_all() { + _compute_all_dirty = true; + } + } +} diff --git a/src/client/spark/SpreadBox/Calculators/StatelessSpreadCalculator.cs b/src/client/spark/SpreadBox/Calculators/StatelessSpreadCalculator.cs new file mode 100644 index 000000000..096fbae15 --- /dev/null +++ b/src/client/spark/SpreadBox/Calculators/StatelessSpreadCalculator.cs @@ -0,0 +1,187 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +using mbts.ui; +using mbts.spark; + +namespace BCG { + /// + /// One stop stateless calculator for spreads. The callee is + /// expected to collect the data and call into it. See + /// SimpleSpreadCalculator for example + /// + public class StatelessSpreadCalculator { + private static SpreadValue _empty_sv = SpreadValue.get_nulled_sv(); + #region Public Interface + public static SpreadValue compute_any_spread(SpreadSpec spread_spec, Dictionary> live_theo_map, + Dictionary sparse_theo_map, + Dictionary>> driver_map, + Dictionary> future_theo_map, + Func> get_leg_edge = null, + Func get_option_position = null) { + if (spread_spec == null || spread_spec.contracts == null || spread_spec.contracts.Length == 0) + return _empty_sv; + else { + SpreadUtilities.SpreadType type = SpreadSpec.getSpreadType(spread_spec); + double[] drivers = new double[spread_spec.contracts.Length], + theos = new double[spread_spec.contracts.Length], + deltas = new double[spread_spec.contracts.Length], + gammas = new double[spread_spec.contracts.Length], + vegas = new double[spread_spec.contracts.Length], + adj_vegas = new double[spread_spec.contracts.Length], + oevs = new double[spread_spec.contracts.Length], + thetas = new double[spread_spec.contracts.Length], + slope_vegas = new double[spread_spec.contracts.Length], + qs_midpoint_theos = new double[spread_spec.contracts.Length], + pos = new double[spread_spec.contracts.Length]; + + double additional_delta = 0.0; + for (int i = 0; i < spread_spec.contracts.Length; i++) { + OptionContractPosition leg_sec = spread_spec.contracts[i]; + PriceSpec leg_price_spec = spread_spec.contracts[i].legPriceSpec; + double leg_size = leg_sec.position; + additional_delta += (additional_delta == 0 && leg_price_spec != null && leg_price_spec.primaryDriverSize != 0) ? leg_price_spec.primaryDriverSize : 0.0; + double effective_driver; + mbts.spark.TheoPoint tp = _compute_single_option_leg(leg_sec, live_theo_map, sparse_theo_map, driver_map, future_theo_map, out effective_driver); + if (leg_sec.contract.isCall) { + Pair leg_edge_pair = get_leg_edge == null ? null : get_leg_edge(leg_sec.contract.product, leg_sec.contract.expiration, leg_sec.contract.strike, true, i); + drivers[i] = effective_driver; theos[i] = tp.call; deltas[i] = tp.cdelta; gammas[i] = tp.cgamma; vegas[i] = tp.cvega; slope_vegas[i] = tp.c_slope_vega; adj_vegas[i] = tp.c_adj_vega; oevs[i] = tp.c_oev; thetas[i] = tp.c_theta; qs_midpoint_theos[i] = _get_leg_mid(tp.call, leg_edge_pair); + } else { + Pair leg_edge_pair = get_leg_edge == null ? null : get_leg_edge(leg_sec.contract.product, leg_sec.contract.expiration, leg_sec.contract.strike, false, i); + drivers[i] = effective_driver; theos[i] = tp.put; deltas[i] = tp.pdelta; gammas[i] = tp.pgamma; vegas[i] = tp.pvega; slope_vegas[i] = tp.p_slope_vega; adj_vegas[i] = tp.p_adj_vega; oevs[i] = tp.p_oev; thetas[i] = tp.p_theta; qs_midpoint_theos[i] = _get_leg_mid(tp.put, leg_edge_pair); + } + pos[i] = get_option_position == null ? Double.NaN : get_option_position(leg_sec.contract.product, leg_sec.contract.expiration, leg_sec.contract.strike, leg_sec.contract.isCall); + } + return new SpreadValue(spread_spec, theos, deltas, gammas, vegas, adj_vegas, oevs, thetas, slope_vegas, drivers, qs_midpoint_theos, pos, additional_delta); + } + } + + public static void compute_multi_symbol_pure_option_spread(SingleSpreadLeg[] spread_legs, Dictionary> theo_map, + out double driver_price, out double driver_bid_price, out double driver_ask_price, out double theo, out double delta, out double gamma, out double vega, out double theta, out double qs_midpoint_theo, + Func> get_leg_edge = null) { + driver_price = theo = delta = gamma = vega = theta = qs_midpoint_theo = 0.0; + driver_bid_price = driver_ask_price = Double.NaN; + int leg_no = 0; + foreach (SingleSpreadLeg l in spread_legs) { + ExpStrikeKeyedData symbol_theo_map; + theo_map.TryGetValue(l.symbol, out symbol_theo_map); + mbts.spark.TheoPoint tp = _compute_single_option_leg_at_live_price(l.exp, l.strike, l.isCall(), symbol_theo_map); + if (l.isCall()) { + Pair leg_edge_pair = get_leg_edge == null ? null : get_leg_edge(l.symbol, l.exp, l.strike, true, leg_no); + driver_price = tp.driver; driver_bid_price = tp.driver_bid; driver_ask_price = tp.driver_ask; theo += l.size * tp.call; delta += l.size * tp.cdelta; gamma += l.size * tp.cgamma; vega += l.size * tp.cvega; theta += l.size * tp.c_theta; qs_midpoint_theo += l.size * _get_leg_mid(tp.call, leg_edge_pair); + } else { + Pair leg_edge_pair = get_leg_edge == null ? null : get_leg_edge(l.symbol, l.exp, l.strike, false, leg_no); + driver_price = tp.driver; driver_bid_price = tp.driver_bid; driver_ask_price = tp.driver_ask; theo += l.size * tp.put; delta += l.size * tp.pdelta; gamma += l.size * tp.pgamma; vega += l.size * tp.pvega; theta += l.size * tp.p_theta; qs_midpoint_theo += l.size * _get_leg_mid(tp.put, leg_edge_pair); + } + leg_no++; + } + } + + public static void compute_single_symbol_pure_option_spread(SingleSpreadLeg[] spread_legs, ExpStrikeKeyedData theo_map, + out double driver_price, out double theo, out double delta, out double gamma, out double vega, out double theta) { + driver_price = theo = delta = gamma = vega = theta = 0.0; + foreach (SingleSpreadLeg l in spread_legs) { + mbts.spark.TheoPoint tp = _compute_single_option_leg_at_live_price(l.exp, l.strike, l.isCall(), theo_map); + if (l.isCall()) { driver_price = tp.driver; theo += l.size * tp.call; delta += l.size * tp.cdelta; gamma += l.size * tp.cgamma; vega += l.size * tp.cvega; theta += l.size * tp.c_theta; } else { driver_price = tp.driver; theo += l.size * tp.put; delta += l.size * tp.pdelta; gamma += l.size * tp.pgamma; vega += l.size * tp.pvega; theta += l.size * tp.p_theta; } + } + } + + public static void compute_future_spread_theos(SingleSpreadLeg[] spread_legs, + Dictionary future_theo_structure_map, + out double anchor_driver, out double theo, out double delta) { + anchor_driver = theo = delta = Double.NaN; + /// the assumption is that they are all the same future symbols + if (spread_legs != null && spread_legs.Length > 0) { + DateTime front_month = DateTime.MaxValue; + theo = delta = 0; + foreach (SingleSpreadLeg l in spread_legs) { + theo += l.size * (StatelessFutureTheoCalculator.get_theo(future_theo_structure_map, l.exp)); + delta += l.size * (StatelessFutureTheoCalculator.get_delta(future_theo_structure_map, l.exp)); + if (l.exp < front_month) { + front_month = l.exp; + anchor_driver = StatelessFutureTheoCalculator.get_driver_price(future_theo_structure_map, l.exp); + } + } + } + } + #endregion + + private static mbts.spark.TheoPoint _compute_single_option_leg_at_live_price(DateTime option_expiration, double strike, bool is_call, ExpStrikeKeyedData live_theo_map) { + mbts.spark.TheoPoint tp = live_theo_map == null ? mbts.spark.TheoPoint.getNulledObject() : live_theo_map.get_data(option_expiration, strike); + return tp ?? mbts.spark.TheoPoint.getNulledObject(); + } + + private static mbts.spark.TheoPoint _compute_single_option_leg_at_tied_price(DateTime option_expiration, double strike, bool is_call, OptionTheoInterpolationData sparse_theo_map, double driver_price) { + mbts.spark.TheoPoint tp = sparse_theo_map == null ? mbts.spark.TheoPoint.getNulledObject() : sparse_theo_map.interpolate_theos(option_expiration, strike, driver_price); + return tp ?? mbts.spark.TheoPoint.getNulledObject(); + } + + /// this is the only relatively tricky thing here + private static mbts.spark.TheoPoint _compute_single_option_leg(OptionContractPosition spread_option_leg, + Dictionary> live_theo_map, + Dictionary sparse_theo_map, + Dictionary>> option_driver_data_map, + Dictionary> future_theo_map, + out double effective_driver) { + ///check to see if the option leg has the same driver + ///instrument as the standard + Triplet driver_price_info = SpreadUtilities.get_option_driver_md(option_driver_data_map, spread_option_leg.contract.product, spread_option_leg.contract.expiration); + PriceSpec leg_price_spec = spread_option_leg.legPriceSpec; + if (driver_price_info != null) { + ExpStrikeKeyedData live_symbol_theo_map; + live_theo_map.TryGetValue(spread_option_leg.contract.product, out live_symbol_theo_map); + OptionTheoInterpolationData symbol_sparse_theo_map; + sparse_theo_map.TryGetValue(spread_option_leg.contract.product, out symbol_sparse_theo_map); + if (leg_price_spec == null) { + /// a leg with a null price spec is considered live + mbts.spark.TheoPoint tp = _compute_single_option_leg_at_live_price(spread_option_leg.contract.expiration, spread_option_leg.contract.strike, spread_option_leg.contract.isCall, live_symbol_theo_map); + effective_driver = tp.driver; + return tp; + } else if (leg_price_spec.primaryDriverSymbol == driver_price_info.first) { + if (leg_price_spec.driverExpiration == driver_price_info.second) { + /// the option is driven by its real driver + if (leg_price_spec.primaryFrozen) /// tied + { + effective_driver = leg_price_spec.primary; + return _compute_single_option_leg_at_tied_price(spread_option_leg.contract.expiration, spread_option_leg.contract.strike, spread_option_leg.contract.isCall, symbol_sparse_theo_map, leg_price_spec.primary); + } else { + mbts.spark.TheoPoint tp = _compute_single_option_leg_at_live_price(spread_option_leg.contract.expiration, spread_option_leg.contract.strike, spread_option_leg.contract.isCall, live_symbol_theo_map); + effective_driver = tp.driver; + return tp; + } + } else { + /// tied spread leg driven by a non driver expiration, need to convert + if (spread_option_leg.legPriceSpec.primaryFrozen) { + Dictionary symbol_future_theo_map = null; + if (future_theo_map != null) + future_theo_map.TryGetValue(driver_price_info.first, out symbol_future_theo_map); + double driver_price = StatelessFutureTheoCalculator.transform_price(symbol_future_theo_map, leg_price_spec.driverExpiration, leg_price_spec.primary, driver_price_info.second); + effective_driver = leg_price_spec.primary; + return _compute_single_option_leg_at_tied_price(spread_option_leg.contract.expiration, spread_option_leg.contract.strike, spread_option_leg.contract.isCall, symbol_sparse_theo_map, driver_price); + } else { + bts.Log.Ui.error(String.Format("This spread is live but the driver expiration {0} is different from the system driver expiration {1} for {2}", + spread_option_leg.legPriceSpec.driverExpiration, driver_price_info.second, spread_option_leg.contract.product)); + effective_driver = Double.NaN; + return mbts.spark.TheoPoint.getNulledObject(); + } + } + } else { + bts.Log.Ui.error(String.Format("This spread is driven by a symbol {0} which is different from the system driver expiration {1} for option {2}", + spread_option_leg.legPriceSpec.primaryDriverSymbol, driver_price_info.first, spread_option_leg.contract.product)); + effective_driver = Double.NaN; + return mbts.spark.TheoPoint.getNulledObject(); + } + } else { + effective_driver = Double.NaN; + return mbts.spark.TheoPoint.getNulledObject(); + } + } + + private static double _get_leg_mid(double theo, Pair edge_pair) { + return edge_pair == null ? Double.NaN : (theo - edge_pair.first + theo + edge_pair.second) / 2.0; + } + } +} diff --git a/src/client/spark/SpreadBox/ContractUtilities.cs b/src/client/spark/SpreadBox/ContractUtilities.cs new file mode 100644 index 000000000..2124d31eb --- /dev/null +++ b/src/client/spark/SpreadBox/ContractUtilities.cs @@ -0,0 +1,569 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using mbts; +using bts.api; +using MathNet.Numerics.Distributions; + +namespace BCG { + public class ContractUtilities { + public static bool is_strock(string sec_type) { + return String.Compare(sec_type, SecurityType.Stock.ToString(), true) == 0; + // return String.Compare(sec_type, SecurityType.Stock.ToString(), true) == 0 || + // String.Compare(sec_type, SecurityType.Equity.ToString(), true) == 0 || + // String.Compare(sec_type, SecurityType.ETF.ToString(), true) == 0 || + // String.Compare(sec_type, SecurityType.Index.ToString(), true) == 0 || + // String.Compare(sec_type, "cash", true) == 0; + } + + //also see SecurityType.cs extension method + public static SecurityType default_aw_stock_type { + get { return SecurityType.Stock; } + } + + public static string case_correct_symbol(string sym_type, SecurityType default_type = SecurityType.Future) { + SecurityType dummy = SecurityType.Unset; + return case_correct_symbol(sym_type, out dummy); + } + + public static string case_correct_symbol(string sym_type, out SecurityType instrument_type, SecurityType default_type = SecurityType.Future) { + string rv = sym_type.ToLower(); + foreach (string type in Enum.GetNames(typeof(SecurityType))) { + instrument_type = (SecurityType)Enum.Parse(typeof(SecurityType), type, true); + string lower_type = type.ToLower(); + int search_index = rv.IndexOf(lower_type); + if (search_index != -1) { + rv.Remove(search_index, type.Length); + if (instrument_type == SecurityType.Option) + return rv.ToLower(); + else + rv.ToUpper(); + } + } + instrument_type = default_type; + if (default_type == SecurityType.Option) + return sym_type.ToLower(); + else + return sym_type.ToUpper(); + } + + // public static SecurityType get_O2_security_type(SecurityType instrument_type) + // { + // if (instrument_type == SecurityType.Stock || instrument_type == SecurityType.ETF || instrument_type == SecurityType.Index) + // return bts.o2.msgs.SecurityType.type.STOCK; + // else if (instrument_type == SecurityType.Future || instrument_type == SecurityType.InterestRateFuture) + // return bts.o2.msgs.SecurityType.type.FUTURE; + // else if (instrument_type == SecurityType.Option) + // return bts.o2.msgs.SecurityType.type.OPTION; + // else if (instrument_type == SecurityType.Spread) + // return bts.o2.msgs.SecurityType.type.SPREAD; + // else + // return bts.o2.msgs.SecurityType.type.UNSET; + // } + + public static SecurityType get_O2_security_type(string sec_type_string) { + SecurityType rv = SecurityType.Unset; + if (Enum.TryParse(sec_type_string, true, out rv)) { + return rv; + } + return SecurityType.Unset; + } + + public static SecurityType from_O2_security_type(string sec_type_string) { + return get_O2_security_type(sec_type_string); + } + + public static bool get_O2_exchange(string exchange_text, out Venue parsed_exchange) { + return Enum.TryParse(exchange_text, true, out parsed_exchange) ? true : false; + } + + public static Venue get_O2_exchange(string exchange_text) { + Venue rv; + return get_O2_exchange(exchange_text, out rv) ? rv : Venue.Unset; + } + + // public static bts.api.SecurityTuple from_old_security_exchange(SymbolExchange se) + // { + // SecurityType.type sec_type = get_O2_security_type(se.instrument_type); + // Exchange.type sec_exchange = Exchange.type.TESTEXCHANGE; + // get_O2_exchange(se.exchange, out sec_exchange); + // return new SecurityTuple(sec_type, se.symbol, sec_exchange); + // } + + // public static mbts.SecurityTuple get_sectup_from_old_security_exchange(SymbolExchange se) + // { + // SecurityType.type sec_type = get_O2_security_type(se.instrument_type); + // Exchange.type sec_exchange = Exchange.type.TESTEXCHANGE; + // get_O2_exchange(se.exchange, out sec_exchange); + // return new mbts.SecurityTuple(sec_type, se.symbol, sec_exchange); + // } + + public static Security get_option_contract(string symbol, DateTime exp, double strike, bool is_call) { + Security rv = new Security(); + //rv.security_type = SecurityType.Option; + rv.Option = new bts.api.OptionContract(); + rv.Symbol = symbol; + rv.Option.ExpirationYear = Convert.ToUInt32(exp.Year); + rv.Option.ExpirationMonth = Convert.ToUInt32(exp.Month); + rv.Option.ExpirationDay = Convert.ToUInt32(exp.Day); + rv.Option.Strike = strike; + rv.Option.CallPut = is_call ? PutOrCall.Call : PutOrCall.Put; + return rv; + } + + // public static bts.o2.msgs.Security get_future_contract(string symbol, DateTime exp) + // { + // bts.o2.msgs.Security rv = new bts.o2.msgs.Security(); + // rv.security_type = bts.o2.msgs.SecurityType.type.FUTURE; + // rv.future = new bts.o2.msgs.FutureContract(); + // rv.future.symbol = symbol; + // rv.future.expiration_year = Convert.ToUInt32(exp.Year); + // rv.future.expiration_month = Convert.ToUInt32(exp.Month); + // rv.future.expiration_day = Convert.ToUInt32(exp.Day); + // return rv; + // } + + // public static bts.o2.msgs.Security get_future_contract(string symbol, DateTime exp, Exchange.type exchange) + // { + // Security rv = get_future_contract(symbol, exp); + // rv.exchange = exchange; + // return rv; + // } + + // public static bts.o2.msgs.Security get_stock_contract(string symbol) + // { + // bts.o2.msgs.Security rv = new bts.o2.msgs.Security(); + // rv.security_type = bts.o2.msgs.SecurityType.type.STOCK; + // rv.stock = new bts.o2.msgs.StockContract(); + // rv.stock.symbol = symbol; + // return rv; + // } + + // public static bts.o2.msgs.Security negate_spread(bts.o2.msgs.Security spread) + // { + // return get_spread_contract(SingleSpreadLeg.negate(spread.spread.summary), spread.security_desc, spread.security_id); + // } + + // public static bts.o2.msgs.Security get_spread_contract(string bts_spread_desc, string exchange_security_desc, string exchange_security_id) + // { + // bts.o2.msgs.Security rv = new bts.o2.msgs.Security(); + // rv.spread = new bts.o2.msgs.MultiLegSecurity(); + // rv.spread.summary = bts_spread_desc; + // rv.security_desc = exchange_security_desc; + // rv.security_id = exchange_security_id; + // rv.security_type = bts.o2.msgs.SecurityType.type.SPREAD; + // //List legs = new List(); + // foreach (SingleSpreadLeg l in SingleSpreadLeg.parse(bts_spread_desc)) + // rv.spread.legs.Add(get_spread_leg(l)); + // return rv; + // } + + // public static bts.o2.msgs.Security get_spread_contract(string bts_spread_desc, string exchange_security_desc, string exchange_security_id, Exchange.type exchange) + // { + // Security rv = get_spread_contract(bts_spread_desc, exchange_security_desc, exchange_security_id); + // rv.exchange = exchange; + // return rv; + // } + + // public static bts.o2.msgs.Security get_contract(SpreadSpec spec, + // string optional_exchange_security_desc, string optional_exchange_security_id) + // { + // if (spec.contracts.Length == 1) + // { + // if (spec.contracts[0].legPriceSpec != null && spec.contracts[0].legPriceSpec.primaryDriverSize != 0) + // /// covered spread with one leg + // return get_spread_contract(SpreadSpec.getSpreadDefinition(spec), optional_exchange_security_desc, optional_exchange_security_id); + // else + // { + // OptionContract c = spec.contracts[0].contract; + // return get_option_contract(c.product, c.expiration, c.strike, c.isCall); + // } + // } + // else if (spec.contracts.Length >= 2) + // return get_spread_contract(SpreadSpec.getSpreadDefinition(spec), optional_exchange_security_desc, optional_exchange_security_id); + // return null; + // } + + // public static bts.o2.msgs.Leg get_spread_leg(SingleSpreadLeg leg) + // { + // bts.o2.msgs.Leg rv = new bts.o2.msgs.Leg(); + // rv.leg_quantity = Convert.ToUInt32(Math.Abs(leg.size)); + // rv.leg_side = leg.size > 0 ? bts.o2.msgs.Side.type.BUY : bts.o2.msgs.Side.type.SELL; + // if (leg.callPut == 'F') + // { + // rv.security = get_future_contract(leg.symbol, leg.exp); + // /// strike is used for the future leg price + // rv.leg_price = leg.strike; + // } + // else if (leg.callPut == 'C' || leg.callPut == 'P') + // { + // rv.security = get_option_contract(leg.symbol, leg.exp, leg.strike, leg.isCall()); + // } + // else + // BCG.Utilities.BlueEventLog.logAssert(false, "Unknown security type in the spread"); + // return rv; + // } + + // public static DateTime get_expiration(bts.o2.msgs.Security security) + // { + // if (security.security_type == bts.o2.msgs.SecurityType.type.FUTURE) + // return new DateTime((int)security.future.expiration_year, (int)security.future.expiration_month, (int)security.future.expiration_day); + // else if (security.security_type == bts.o2.msgs.SecurityType.type.OPTION) + // return new DateTime((int)security.option.expiration_year, (int)security.option.expiration_month, (int)security.option.expiration_day); + // else + // return DateTime.MinValue; + // } + + // public static double get_strike(bts.o2.msgs.Security security) + // { + // return security.security_type == bts.o2.msgs.SecurityType.type.OPTION ? security.option.strike : 0; + // } + + // public static string get_spread_contract_summary(bts.o2.msgs.Security spread_security) + // { + // List legs = new List(); + // get_spread_contract_summary(spread_security, ref legs); + // return SingleSpreadLeg.toSortedString(legs); + // } + + // public static void get_spread_contract_summary(bts.o2.msgs.Security spread_security, ref List out_legs) + // { + // List> rv = new List>(); + // get_spread_contract_summary(spread_security, ref rv); + // out_legs.AddRange(rv.Select(p => p.first)); + // } + + // public static void get_spread_contract_summary(bts.o2.msgs.Security spread_security, ref List> out_legs, double parent_qty_mult = 1.0) + // { + // foreach (bts.o2.msgs.Leg l in spread_security.spread.legs) + // { + // if (l.security.security_type == bts.o2.msgs.SecurityType.type.OPTION) + // { + // bts.o2.msgs.OptionContract c = l.security.option; + // out_legs.Add(new Pair(new SingleSpreadLeg(c.symbol.ToLower(), get_expiration(l.security), c.strike, c.call_put == bts.o2.msgs.PutOrCall.type.CALL ? 'C' : 'P', + // (l.leg_side == bts.o2.msgs.Side.type.BUY ? 1 : -1) * l.leg_quantity * parent_qty_mult), l.security.security_key)); + // } + // else if (l.security.security_type == bts.o2.msgs.SecurityType.type.FUTURE) + // { + // bts.o2.msgs.FutureContract c = l.security.future; + // out_legs.Add(new Pair(new SingleSpreadLeg(c.symbol, get_expiration(l.security), l.leg_price, 'F', + // (l.leg_side == bts.o2.msgs.Side.type.BUY ? 1 : -1) * l.leg_delta * parent_qty_mult), l.security.security_key)); + // } + // else if (l.security.security_type == bts.o2.msgs.SecurityType.type.STOCK) + // { + // bts.o2.msgs.StockContract c = l.security.stock; + // out_legs.Add(new Pair(new SingleSpreadLeg(c.symbol, DateTime.MinValue, 0, 'S', + // (l.leg_side == bts.o2.msgs.Side.type.BUY ? 1 : -1) * l.leg_quantity * parent_qty_mult), l.security.security_key)); + // } + // else if (l.security.security_type == bts.o2.msgs.SecurityType.type.SPREAD) + // { + // mbts.Logger.log(bts.log.Level.Diag, bts.log.Subsystem.MarketData, "Hierarchical spreads"); + // get_spread_contract_summary(l.security, ref out_legs, (l.leg_side == Side.type.BUY ? 1 : -1) * l.leg_quantity * parent_qty_mult); + // } + // } + // } + + // public struct SpreadDetails { + // public string security_spread_def; + // public string security_spread_leg_keys; + // } + // public static SpreadDetails get_spread_strings(Security security) { + // if (security.security_type != SecurityType.type.SPREAD) return new SpreadDetails(); + // var legs = new List>(); + // get_spread_contract_summary(security, ref legs); + // legs.Sort((p1, p2) => p1.first.CompareTo(p2.first)); + // return new SpreadDetails() { + // security_spread_def = SingleSpreadLeg.toSortedString(legs.Select(p => p.first)), + // security_spread_leg_keys = string.Join(", ", legs.Select(p => p.second)) + // }; + // } + + // public static string get_contract_summary(bts.o2.msgs.Security security) + // { + // if (security != null) + // { + // if (security.security_type == bts.o2.msgs.SecurityType.type.FUTURE) + // return security.future.symbol + " " + get_expiration(security).ToShortDateString(); + // else if (security.security_type == bts.o2.msgs.SecurityType.type.OPTION) + // return security.option.symbol + " " + get_expiration(security).ToShortDateString() + " " + security.option.strike + " " + security.option.call_put.ToString(); + // else if (security.security_type == bts.o2.msgs.SecurityType.type.SPREAD) + // return String.IsNullOrEmpty(security.spread.summary) ? get_spread_contract_summary(security) : security.spread.summary; + // else if (security.security_type == bts.o2.msgs.SecurityType.type.STOCK) + // return security.stock.symbol; + // else if (security.security_type == bts.o2.msgs.SecurityType.type.UNSET) + // return String.Empty; + // else + // { + // BCG.Utilities.BlueEventLog.logAssert(false, "Unknown contract type"); + // return String.Empty; + // } + // } + // else + // return String.Empty; + // } + + // public static string get_size_summary(System.Collections.IDictionary row) + // { + // return + // String.Format("{0} {1}/{2}", row["side"].ToString() == bts.o2.msgs.Side.type.BUY.ToString() ? "+" : "-", + // row["cum_qty"], row["order_qty"]); + // } + + // public static bts.o2.msgs.Security get_contract_from_order_row(IBlueRow r) + // { + // string sec_type = r["security_type"].ToString(); + // Security rv = new Security() { security_type = SecurityType.type.UNSET }; + // if (sec_type == bts.o2.msgs.SecurityType.type.FUTURE.ToString()) + // { + // rv = ContractUtilities.get_future_contract(r["symbol"].ToString(), (DateTime)r["expiration"]); + // } + // else if (sec_type == bts.o2.msgs.SecurityType.type.OPTION.ToString()) + // { + // rv = ContractUtilities.get_option_contract(r["symbol"].ToString(), + // (DateTime)r["expiration"], + // (double)r["strike"], + // r["call_put"].ToString() == bts.o2.msgs.PutOrCall.type.CALL.ToString()); + // } + // else if (sec_type == bts.o2.msgs.SecurityType.type.SPREAD.ToString()) + // { + // rv = ContractUtilities.get_spread_contract(r["spread_summary"].ToString(), + // r["security_desc"].ToString(), + // r.Contains("security_id") ? r["security_id"].ToString() : String.Empty); + // } + // else if (sec_type == bts.o2.msgs.SecurityType.type.STOCK.ToString()) + // { + // rv = ContractUtilities.get_stock_contract(r["symbol"].ToString()); + // } + // rv.exchange = BlueDataUtility.get_row_enum_value(r, "exchange", bts.o2.msgs.Exchange.type.TESTEXCHANGE); + // return rv; + // } + + // public static string get_electronic_equivelant(bts.o2.msgs.SecurityType.type security_type, string symbol_name) + // { + // string rv = symbol_name; + // if (security_type == bts.o2.msgs.SecurityType.type.OPTION) + // { + // if (SecurityElectronicEquivalenceMapper.get_option_electronic_equivalent(symbol_name, out rv)) + // return rv; + // } + // else if (security_type == bts.o2.msgs.SecurityType.type.FUTURE) + // { + // if (SecurityElectronicEquivalenceMapper.get_future_electronic_equivalent(symbol_name, out rv)) + // return rv; + // } + // return symbol_name; + // } + + // public static string get_security_name(bts.o2.msgs.Security security) + // { + // if (security.security_type == bts.o2.msgs.SecurityType.type.OPTION) + // return security.option.symbol; + // else if (security.security_type == bts.o2.msgs.SecurityType.type.FUTURE) + // return security.future.symbol; + // else if (security.security_type == bts.o2.msgs.SecurityType.type.STOCK) + // return security.stock.symbol; + // else if (security.security_type == bts.o2.msgs.SecurityType.type.SPREAD) + // foreach (bts.o2.msgs.Leg l in security.spread.legs) + // return get_security_name(l.security); + // return String.Empty; + // } + + // public static string get_logical_key_from_security_row(IBlueRow r) + // { + // SecurityType.type security_type = (SecurityType.type)Enum.Parse(typeof(SecurityType.type), (string)r["security_type"], true); + // Exchange.type security_exchange = (Exchange.type)Enum.Parse(typeof(Exchange.type), (string)r["security_exchange"], true); + // if (security_type == SecurityType.type.OPTION) + // { + // string security_symbol = (string)r["security_symbol"]; + // DateTime security_expiration = (DateTime)r["security_expiration"]; + // double security_strike = (double)r["security_strike"]; + // PutOrCall.type security_callput = (PutOrCall.type)Enum.Parse(typeof(PutOrCall.type), (string)r["security_callput"], true); + // return String.Format("{0}_{1}_{2}_{3}_{4}_{5}", security_type, security_exchange, security_symbol, security_expiration.ToShortDateString(), security_strike, security_callput); + // } + // else if (security_type == SecurityType.type.FUTURE) + // { + // string security_symbol = (string)r["security_symbol"]; + // DateTime security_expiration = (DateTime)r["security_expiration"]; + // return String.Format("{0}_{1}_{2}_{3}", security_type, security_exchange, security_symbol, security_expiration.ToShortDateString()); + // } + // else if (security_type == SecurityType.type.SPREAD) + // { + // string security_spread_def = (string)r["security_spread_def"]; + // return String.Format("{0}_{1}_{2}", security_type, security_exchange, security_spread_def); + // } + // else if (security_type == SecurityType.type.STOCK) + // { + // string security_symbol = (string)r["security_symbol"]; + // return String.Format("{0}_{1}_{2}", security_type, security_exchange, security_symbol); + // } + // else + // { + // throw new ApplicationException(String.Format("ContractUtilities.get_logical_key_from_security_row unknown security type {0}", security_type)); + // } + // } + + // #region Config functions + + // public static IEnumerable get_config_traders() + // { + // var h = new mbts.user.UserConfigHelper(); + // SortedDictionary rv = new SortedDictionary(); + // foreach (var user in h.get_all_users_security_permissions()) + // rv[user.login.login_name] = true; + // return rv.Keys; + // } + + // public static IEnumerable> get_config_securities() + // { + // var h = new mbts.user.UserConfigHelper(); + // List> rv = new List>(); + // foreach (var user in h.get_all_users_security_permissions()) + // { + // foreach (var perm in user.security_permissions) + // { + // string security_symbol = mbts.o2.O2ClientUtil.security_symbol(perm.blue_security), + // security_exchange = perm.blue_security.exchange.ToString(); + // rv.Add(new Pair(security_exchange, security_symbol)); + // } + // } + // return rv; + // } + + // public static IEnumerable get_config_unique_security_names() + // { + // SortedDictionary rv = new SortedDictionary(); + // foreach (Pair p in get_config_securities()) + // rv[p.second] = true; + // return rv.Keys; + // } + + // #endregion + + // #region Display + + // public static string get_option_display_text(string security_symbol, DateTime security_expiration, double strike, bool is_call, bool map_security_expiration = true) + // { + // DateTime display_exp = map_security_expiration ? mbts.ui.utility.ExpirationFormatter.convert_real_to_mapped(bts.o2.msgs.SecurityType.type.OPTION, security_symbol, security_expiration) : security_expiration; + // return security_symbol + " " + DateTimeFormatter.format(display_exp, DateTimeFormatter.ExpirationShortForms.DayMonthYearDiff2000.ToString()) + " " + strike + " " + (is_call ? "C" : "P"); + // } + + // public static string get_option_display_text_no_cp(string security_symbol, DateTime security_expiration, double strike, bool map_security_expiration = true) { + // return string.Format("{0} {1}", get_option_display_expiration_text(security_symbol, security_expiration, map_security_expiration), strike); + // } + + // public static string get_option_display_expiration_text(string security_symbol, DateTime security_expiration, bool map_security_expiration = true) + // { + // string formatter = DateTimeFormatter.ExpirationShortForms.DayMonthYearDiff2000.ToString(); + // DateTime display_exp = map_security_expiration ? mbts.ui.utility.ExpirationFormatter.convert_real_to_mapped(bts.o2.msgs.SecurityType.type.OPTION, security_symbol, security_expiration) : security_expiration; + // if(display_exp.Day == 1) + // formatter = DateTimeFormatter.ExpirationShortForms.MonthYearDiff2000.ToString(); + // return security_symbol + " " + DateTimeFormatter.format(display_exp, formatter); + // } + + // public static string get_expiration_text_no_symbol(DateTime exp_date) + // { + // return String.Format("{0} {1} {2}", + // exp_date.Day, BCG.Utilities.Dates.DateCode.get_month_three_letters(exp_date.Month), + // (exp_date.Year - 2000).ToString("00")); + // } + + // public static string get_future_display_text(string security_symbol, DateTime security_expiration, bool map_security_expiration = true) + // { + // DateTime display_exp = map_security_expiration ? mbts.ui.utility.ExpirationFormatter.convert_real_to_mapped(bts.o2.msgs.SecurityType.type.FUTURE, security_symbol, security_expiration) : security_expiration; + // return security_symbol + " " + DateTimeFormatter.format(display_exp, DateTimeFormatter.ExpirationShortForms.DayMonthYearDiff2000.ToString()); + // } + + public static string add_offset_to_spreadleg_exps(string bts_spread_def) { + return SingleSpreadLeg.toSortedString(add_offset_to_spreadleg_exps(SingleSpreadLeg.parse(bts_spread_def))); + } + + public static SingleSpreadLeg[] add_offset_to_spreadleg_exps(IEnumerable legs) { + List mapped_legs = new List(); + foreach (SingleSpreadLeg l in legs) { + DateTime mapped_exp = mbts.ui.utility.ExpirationFormatter.convert_real_to_mapped((l.callPut == 'C' || l.callPut == 'P') ? SecurityType.Option : SecurityType.Future, + l.symbol, l.exp); + mapped_legs.Add(new SingleSpreadLeg(l.symbol, mapped_exp, l.strike, l.callPut, l.size)); + } + return mapped_legs.ToArray(); + } + + // public static string get_display_text(bts.o2.msgs.Security security, bool map_security_expiration = true) + // { + // if (security != null) + // { + // if (security.security_type == bts.o2.msgs.SecurityType.type.FUTURE) + // return get_future_display_text(security.future.symbol, get_expiration(security)); + // else if (security.security_type == bts.o2.msgs.SecurityType.type.OPTION) + // return get_option_display_text(security.option.symbol, get_expiration(security), security.option.strike, security.option.call_put == bts.o2.msgs.PutOrCall.type.CALL); + // else if (security.security_type == bts.o2.msgs.SecurityType.type.SPREAD) + // { + // string bts_spread_def = get_spread_contract_summary(security); + // bts_spread_def = add_offset_to_spreadleg_exps(bts_spread_def); + // string detail, summary; + // SpreadInterpreter.interpret(bts_spread_def, out detail, out summary); + // return detail; + // } + // else if (security.security_type == bts.o2.msgs.SecurityType.type.STOCK) + // return security.stock.symbol; + // else if (security.security_type == bts.o2.msgs.SecurityType.type.UNSET) + // return String.Empty; + // else + // { + // mbts.Logger.log(bts.log.Level.Error, bts.log.Subsystem.ui, "Unknown contract type"); + // return String.Empty; + // } + // } + // else + // return String.Empty; + // } + + // public static string get_expiration_display(string symbol_name, DateTime expiration, bool is_future, bool map_security_expiration = true) + // { + // return map_security_expiration ? mbts.ui.utility.ExpirationFormatter.convert_real_to_mapped(is_future ? SecurityType.type.FUTURE : SecurityType.type.OPTION, symbol_name, expiration).ToShortDateString() : + // expiration.ToShortDateString(); + // } + + // public static string get_symbol_with_inst_type_display_text(string symbol_name, SecurityType type) + // { + // switch(type) + // { + // case SecurityType.Option: + // return "O " + symbol_name; + // case SecurityType.Future: + // return "F " + symbol_name; + // default: + // return symbol_name; + // } + // } + + // #endregion + + // #region Ticks + + // public static IEnumerable> fill_gaps(IEnumerable> ladder, double interval, int rounding_digits = 7) + // { + // if (ladder == null || ladder.Count() <= 1) + // return ladder; + // else + // { + // List> rv = new List>(); + // IDictionary ladder_map = ladder.ToDictionaryDupes(t => t.Item1, t => t.Item2); + // double min = ladder.Min(t => t.Item1), max = ladder.Max(t => t.Item1), iter_price = min; + // while (true) + // { + // uint iter_sz; + // iter_sz = ladder_map.TryGetValue(iter_price, out iter_sz) ? iter_sz : 0; + // rv.Add(Tuple.Create(iter_price, iter_sz)); + + // iter_price = Math.Round(iter_price + interval, rounding_digits); + // if (iter_price > max) + // break; + // } + // return rv; + // } + // } + + // #endregion + } +} diff --git a/src/client/spark/SpreadBox/DateTimeFormatter.cs b/src/client/spark/SpreadBox/DateTimeFormatter.cs new file mode 100644 index 000000000..e38f61bbd --- /dev/null +++ b/src/client/spark/SpreadBox/DateTimeFormatter.cs @@ -0,0 +1,41 @@ +// using System; +// using System.Collections.Generic; +// using System.Linq; +// using System.Text; + +// namespace BCG +// { +// public class DateTimeFormatter +// { +// private delegate string MyFormatDateTime (DateTime v); +// public enum ExpirationShortForms +// { +// DayMonthYearDiff2000, +// MonthYearDiff2000 +// } +// public enum DateTimeFormats { Regular, ShortDate, DayMonthYearDiff2000, MonthYearDiff2000 } +// private static Dictionary _local_formats = null; +// private static void _init() +// { +// if (_local_formats == null) +// { +// _local_formats = new Dictionary(); +// _local_formats.Add(DateTimeFormats.Regular.ToString(), v => v.ToString()); +// _local_formats.Add(DateTimeFormats.ShortDate.ToString(), v => v.ToShortDateString()); +// _local_formats.Add(DateTimeFormats.DayMonthYearDiff2000.ToString(), +// (DateTime v) => { return String.Format("{0} {1}{2}", v.Day, BCG.Utilities.Dates.DateCode.getMonthSymbol(v.Month), v.Year - 2000); }); +// _local_formats.Add(DateTimeFormats.MonthYearDiff2000.ToString(), +// (DateTime v) => { return String.Format("{0}{1}", BCG.Utilities.Dates.DateCode.getMonthSymbol(v.Month), v.Year - 2000); }); +// } +// } +// public static string format(DateTime val, string format) +// { +// _init (); +// MyFormatDateTime f = null; +// if (_local_formats.TryGetValue(format, out f)) +// return f(val); +// else +// return val.ToString(format); +// } +// } +// } \ No newline at end of file diff --git a/src/client/spark/SpreadBox/GUI/SpreadLegDisplayOrder.cs b/src/client/spark/SpreadBox/GUI/SpreadLegDisplayOrder.cs new file mode 100644 index 000000000..2d08e5f1e --- /dev/null +++ b/src/client/spark/SpreadBox/GUI/SpreadLegDisplayOrder.cs @@ -0,0 +1,14 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace BCG +{ + public enum SpreadLegDisplayOrder + { + None = 0, + Sorted = 1 + } +} diff --git a/src/client/spark/SpreadBox/GUI/SpreadSummaryRowControl.Designer.cs b/src/client/spark/SpreadBox/GUI/SpreadSummaryRowControl.Designer.cs new file mode 100644 index 000000000..ab35b28af --- /dev/null +++ b/src/client/spark/SpreadBox/GUI/SpreadSummaryRowControl.Designer.cs @@ -0,0 +1,46 @@ +namespace BCG +{ + partial class SpreadSummaryRowControl + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Component Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + this.SuspendLayout(); + // + // SpreadSummaryRowControl + // + this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.Name = "SpreadSummaryRowControl"; + this.Size = new System.Drawing.Size(221, 20); + this.ResumeLayout(false); + + } + + #endregion + + } +} diff --git a/src/client/spark/SpreadBox/GUI/SpreadSummaryRowControl.cs b/src/client/spark/SpreadBox/GUI/SpreadSummaryRowControl.cs new file mode 100644 index 000000000..251068a27 --- /dev/null +++ b/src/client/spark/SpreadBox/GUI/SpreadSummaryRowControl.cs @@ -0,0 +1,86 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Drawing; +using System.Data; +using System.Linq; +using System.Text; +using System.Windows.Forms; +using BCG.Utilities; + +namespace BCG { + public partial class SpreadSummaryRowControl : UserControl { + internal event EventHandler onSelectSpread; + private int myLabelSpacing = 4; + private List