diff --git a/src/client/spark/AW2/Misc/SystemContractData.cs b/src/client/spark/AW2/Misc/SystemContractData.cs index a7ab11c07..6e2f60b21 100644 --- a/src/client/spark/AW2/Misc/SystemContractData.cs +++ b/src/client/spark/AW2/Misc/SystemContractData.cs @@ -200,7 +200,8 @@ namespace mbts.spark { return null; } - public IEnumerable get_option_expirations(string option_name) { + public IEnumerable get_option_expirations(string option_name, + bool is_display_expiration = false) { return exp_map.Keys.Where(e => e.security_type == SecurityType.Option && e.symbol == option_name).Select(e => e.expiration); } @@ -214,5 +215,19 @@ namespace mbts.spark { return sectup_map.Where(st => st.security_type == SecurityType.Option); } + public IEnumerable get_all_option_strikes(string option_name) { + HashSet rv = new HashSet(); + foreach (var kv in strike_map.Where(kv => kv.Key.symbol == option_name)) + foreach (var k in kv.Value) + rv.Add(k.strike); + return rv; + } + + public IEnumerable get_option_expirations_with_strikes(string option_name, + bool is_display_expiration) { + return strike_map.Where(kv => kv.Key.symbol == option_name && + kv.Value.Count > 0).Select(kv => kv.Key.expiration); + } + } } diff --git a/src/client/spark/NMSheets/BlackboardStructure/MNSheetTheoRequest.cs b/src/client/spark/NMSheets/BlackboardStructure/MNSheetTheoRequest.cs new file mode 100644 index 000000000..3ea2fc22f --- /dev/null +++ b/src/client/spark/NMSheets/BlackboardStructure/MNSheetTheoRequest.cs @@ -0,0 +1,42 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace BCG +{ + /// This is the theo request for an NMSheetGrid. Its send out by + /// the driver stip at the top (NMSheetDriverControlStrip). The + /// NMSheetSingleOptionMainDataSource filters it for its own + /// symbol and computes the data. + public class NMSheetDataRequest + { + public readonly IEnumerable> expiration_request_list; + public NMSheetDataRequest(IEnumerable> the_expiration_request_list) { expiration_request_list = the_expiration_request_list; } + + /// Returns a new request thats restricted for the + /// symbol in the argument + public static NMSheetDataRequest restrict_for_symbol(NMSheetDataRequest request, NMSheetSymbol option_symbol) + { + List> rv = new List>(); + foreach (Triplet t in request.expiration_request_list) + if (t.first.option_name == option_symbol.option_name && t.first.option_exchange == option_symbol.option_exchange) + rv.Add(t); + return new NMSheetDataRequest(rv); + } + + /// Returns a new request thats restricted for the + /// symbol in the argument + public static NMSheetDataRequest restrict_for_expirations(NMSheetDataRequest request, IEnumerable exps) + { + HashSet exp_map = new HashSet(exps); + List> rv = new List>(); + foreach (Triplet t in request.expiration_request_list) + if (exp_map.Contains(t.first)) + rv.Add(t); + return new NMSheetDataRequest(rv); + } + + } +} diff --git a/src/client/spark/NMSheets/BlackboardStructure/NMSheetData.cs b/src/client/spark/NMSheets/BlackboardStructure/NMSheetData.cs new file mode 100644 index 000000000..bf0b06232 --- /dev/null +++ b/src/client/spark/NMSheets/BlackboardStructure/NMSheetData.cs @@ -0,0 +1,179 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace BCG +{ + /// This is basically a fancy map of Dictionary + /// Its does 2 things + /// 1. Allows NMSheetExpiration based access for NMSheet data sources + /// 2. Serves as INMSheetGridFacingData for the grid, and talks to the + /// grid in Placeholder expiration terms + public class NMSheetData : INMSheetGridFacingData + { + private readonly IDictionary _sym_data_map; + private readonly IDictionary> _bbo_map; + private readonly IDictionary _complete_ticker_data; + private readonly TaskingConsolidatedData _task_data; + + private readonly double[] _cached_sorted_strikes; + private readonly NMSheetExpiration[] _cached_sorted_expirations; + private readonly SortedDictionary _cached_driver_data_map = new SortedDictionary(); + private readonly SortedDictionary _cached_atm_data; + + public NMSheetData(IDictionary sym_data_map, + IDictionary> bbo_map, + IDictionary complete_ticker_data, + TaskingConsolidatedData task_data) + { + _sym_data_map = sym_data_map; + _bbo_map = bbo_map; + _complete_ticker_data = complete_ticker_data; + _task_data = task_data; + foreach (KeyValuePair p in sym_data_map) + { + IDictionary symbol_bbo_map = null; + if (bbo_map.TryGetValue(p.Key, out symbol_bbo_map)) + p.Value.set_bbo(symbol_bbo_map); + p.Value.set_ticker(_complete_ticker_data); + p.Value.set_task_data(_task_data); + } + /// sorted strikes + _cached_sorted_strikes = _assemble_sorted_strikes_from_symbols(_sym_data_map); + /// computed drivers + _cached_driver_data_map = _assemble_driver_data_from_symbols(sym_data_map); + /// expirations + _cached_sorted_expirations = _cached_driver_data_map.Keys.ToArray(); + /// atm + _cached_atm_data = _assemble_atm_data_from_symbols(_sym_data_map); + } + + public static NMSheetData filter_data(NMSheetData data, HashSet restricted_seckey_map) + { + Dictionary main_data_map = new Dictionary(); + foreach (KeyValuePair p in data._sym_data_map) + main_data_map.Add(p.Key, NMSheetSingleOptionData.filter_data(p.Value, restricted_seckey_map)); + return new NMSheetData(main_data_map, data._bbo_map, data._complete_ticker_data, data._task_data); + } + + public NMSheetData filter_for_strikes_in_tasks(bool is_on_only = false) + { + if (_task_data != null) + { + IEnumerable eye_secs = _task_data.get_set_securities(mbts.tasks.TaskType.Eye, is_on_only), + quoter_secs = _task_data.get_set_securities(mbts.tasks.TaskType.Quoter, is_on_only); + HashSet all_secs = new HashSet(Enumerable.Concat(eye_secs, quoter_secs)); + return filter_data(this, all_secs); + } + else + return this; + } + + public NMSheetData filter_for_positive_edge() + { + List filtered_key_list = new List(); + foreach (var kv in _sym_data_map) + { + NMSheetSingleOptionData sym_data = kv.Value; + filtered_key_list.AddRange(sym_data.get_crossed_keys()); + } + return filter_data(this, new HashSet(filtered_key_list)); + } + public IDictionary get_driver_data() { return _cached_driver_data_map; } + + public HashSet get_expirations_with_same_driver(NMSheetExpiration nmsheet_expiration) + { + HashSet rv = new HashSet(); + NMSheetDriverData driver_data = null; + if (_cached_driver_data_map.TryGetValue (nmsheet_expiration, out driver_data)) + { + foreach (KeyValuePair driver_data_map_elem in _cached_driver_data_map) + { + NMSheetDriverData this_driver_data = driver_data_map_elem.Value; + if (this_driver_data != null && this_driver_data.driver_symbol == driver_data.driver_symbol && this_driver_data.driver_expiration == driver_data.driver_expiration) + rv.Add(driver_data_map_elem.Key); + } + } + return rv; + } + + public bool security_exist(NMSheetExpiration nmsheet_exp, double option_strike) + { + NMSheetSingleOptionData single_option_data = null; + return _sym_data_map.TryGetValue(nmsheet_exp.nmsheet_symbol, out single_option_data) && single_option_data.security_exist(nmsheet_exp.option_expiration, option_strike); + } + + public bool get_security_key(NMSheetExpiration exp, double strike, bool is_call, out uint security_key) + { + security_key = ExchangeSecurityMap.error_key; + NMSheetSingleOptionData symbol_data = null; + if (_sym_data_map.TryGetValue(exp.nmsheet_symbol, out symbol_data)) + return symbol_data.get_security_key(exp.option_expiration, strike, is_call, out security_key); + else + return false; + } + + public TaskingConsolidatedData get_task_data() { return _task_data; } + + #region INMSheetGridFacingData + + public NMSheetExpiration[] get_sorted_expirations() { return _cached_sorted_expirations; } + + public double[] get_sorted_strikes() { return _cached_sorted_strikes; } + + public IDictionary get_atm_data() { return _cached_atm_data; } + + public bool get_row_data(NMSheetSymbol nmsheet_symbol, DateTime option_expiration, double strike, ref double[] cp_row, out NMSheetRowAuxiliaryData aux_data) + { + aux_data = null; + NMSheetSingleOptionData this_option_data = null; + if (_sym_data_map.TryGetValue(nmsheet_symbol, out this_option_data)) + return this_option_data.get_row_data(option_expiration, strike, ref cp_row, out aux_data); + return false; + } + + #endregion + + #region Stateless Helpers + + private static SortedDictionary _assemble_atm_data_from_symbols(IDictionary sym_data_map) + { + SortedDictionary rv = new SortedDictionary(); + foreach (KeyValuePair symbol_elem in sym_data_map) + { + Dictionary symbol_atm_map = symbol_elem.Value.get_atm_data(); + foreach (KeyValuePair exp_elem in symbol_atm_map) + rv[new NMSheetExpiration(symbol_elem.Key, exp_elem.Key)] = exp_elem.Value; + } + return rv; + } + + private static double[] _assemble_sorted_strikes_from_symbols(IDictionary sym_data_map) + { + HashSet all_sym_strikes = new HashSet(); + foreach (NMSheetSingleOptionData d in sym_data_map.Values) + Array.ForEach(d.get_strikes(), (double k) => all_sym_strikes.Add(k)); + List strike_list = all_sym_strikes.ToList(); + strike_list.Sort(); + return strike_list.ToArray(); + } + + private static SortedDictionary _assemble_driver_data_from_symbols(IDictionary symbol_data_map) + { + SortedDictionary rv = new SortedDictionary(); + foreach (KeyValuePair option_data_pair in symbol_data_map) + { + NMSheetSymbol nmsheet_symbol = option_data_pair.Key; + NMSheetSingleOptionData symbol_data = option_data_pair.Value; + Dictionary symbol_driver_data = symbol_data.get_driver_data(); + foreach (KeyValuePair p in symbol_driver_data) + rv[new NMSheetExpiration(nmsheet_symbol, p.Key)] = p.Value; + } + return rv; + } + #endregion + } +} diff --git a/src/client/spark/NMSheets/BlackboardStructure/NMSheetDriverData.cs b/src/client/spark/NMSheets/BlackboardStructure/NMSheetDriverData.cs new file mode 100644 index 000000000..dfb2f8943 --- /dev/null +++ b/src/client/spark/NMSheets/BlackboardStructure/NMSheetDriverData.cs @@ -0,0 +1,26 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace BCG +{ + public class NMSheetDriverData + { + public readonly string driver_symbol; + public readonly DateTime driver_expiration; + public readonly double driver_live_price; + public readonly double driver_price_at_computed_theo; + public readonly bool is_frozen; + + public NMSheetDriverData(string the_driver_symbol, DateTime the_driver_expiration, double the_driver_live_price, double the_driver_price_at_computed_theo, bool the_is_frozen) + { + driver_symbol = the_driver_symbol; + driver_expiration = the_driver_expiration; + driver_live_price = the_driver_live_price; + driver_price_at_computed_theo = the_driver_price_at_computed_theo; + is_frozen = the_is_frozen; + } + } +} diff --git a/src/client/spark/NMSheets/BlackboardStructure/NMSheetFilterState.cs b/src/client/spark/NMSheets/BlackboardStructure/NMSheetFilterState.cs new file mode 100644 index 000000000..09204dfa1 --- /dev/null +++ b/src/client/spark/NMSheets/BlackboardStructure/NMSheetFilterState.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 NMSheetFilterState + { + applicable = 0, + dontcare + } +} diff --git a/src/client/spark/NMSheets/BlackboardStructure/NMSheetSingleOptionData.cs b/src/client/spark/NMSheets/BlackboardStructure/NMSheetSingleOptionData.cs new file mode 100644 index 000000000..cb6b05df5 --- /dev/null +++ b/src/client/spark/NMSheets/BlackboardStructure/NMSheetSingleOptionData.cs @@ -0,0 +1,291 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using bts.api; +using System.Text; + +using bts.utils; + +namespace BCG { + /// + /// Holds together data for one NMSheetSymbol. Its constructed by + /// NMSheetSingleOptionMainDataSource and is accessed ONLY by + /// NMSheetData + /// In essence this is a join, since it keeps data hashed + /// on the security for each symbol. The data is actually + /// put together in the get_theo_data_row function + /// + public partial class NMSheetSingleOptionData { + private readonly NMSheetSymbol _nmsheet_option; + private readonly NMSheetDataRequest _data_request; + private readonly ExpStrikeKeyedData> _theo_data_map = new ExpStrikeKeyedData>(); + private readonly Dictionary _option_exp_driver_data; + private readonly OptionContractKeyedData _theo_shift_map; + private readonly IDictionary _atm_data_map; + private readonly OptionContractKeyedData _roll_over_data; + private readonly ExpStrikeKeyedData> _position_map; + private readonly ExpStrikeKeyedData _presaved_aw2_theos; + private readonly NMSheetSettings _settings; + private readonly object /*IDictionary*/ _option_exp_driver_rows = "TODO"; + private readonly IDictionary> _option_exp_driver_detailed_price_data = new Dictionary>(); + private IDictionary _bbo_data_map = new Dictionary(); + private IDictionary _ticker_data = new Dictionary(); + private TaskingConsolidatedData _tasking_data; + private readonly ExchangeSecurityMap _sec_map; + + public NMSheetSingleOptionData(NMSheetSymbol option, + NMSheetDataRequest data_request, + ExpStrikeKeyedData> theo_data_map, + Dictionary option_exp_driver_data, + OptionContractKeyedData theo_shift_map, + IDictionary atm_data, + OptionContractKeyedData roll_over_data, + ExpStrikeKeyedData> position_map, + ExpStrikeKeyedData presaved_aw2_theos, + object option_exp_driver_detailed_price_data, + ExchangeSecurityMap sec_map, + NMSheetSettings settings) { + _nmsheet_option = option; + _data_request = data_request; + _theo_data_map = theo_data_map; + _option_exp_driver_data = option_exp_driver_data; + _theo_shift_map = theo_shift_map; + _atm_data_map = atm_data; + _roll_over_data = roll_over_data; + _position_map = position_map; + _presaved_aw2_theos = presaved_aw2_theos; + //_option_exp_driver_rows = option_exp_driver_detailed_price_data; + _settings = settings; + _sec_map = sec_map; + // foreach (KeyValuePair kvp in _option_exp_driver_rows) + // _option_exp_driver_detailed_price_data[kvp.Key] = Tuple.Create(BlueDataUtility.get_row_value(kvp.Value, "bid_price", Double.NaN), + // BlueDataUtility.get_row_value(kvp.Value, "ask_price", Double.NaN)); + } + + public static NMSheetSingleOptionData filter_data(NMSheetSingleOptionData data, HashSet seckey_map) { + ExpStrikeKeyedData> theo_data_map = new ExpStrikeKeyedData>(); + foreach (Triplet> t in data._theo_data_map.get_data_linearly()) + if (seckey_map.Contains(t.third.second) || seckey_map.Contains(t.third.third)) + theo_data_map.set_data(t.first, t.second, t.third); + HashSet exp_map = new HashSet(theo_data_map.get_expirations().Select(exp => new NMSheetExpiration(data._nmsheet_option.option_exchange, data._nmsheet_option.option_name, exp))); + NMSheetDataRequest req = NMSheetDataRequest.restrict_for_expirations(data._data_request, exp_map); + Dictionary driver_data = new Dictionary(); + foreach (KeyValuePair p in data._option_exp_driver_data) + if (exp_map.Contains(new NMSheetExpiration(data._nmsheet_option, p.Key))) + driver_data.Add(p.Key, p.Value); + return new NMSheetSingleOptionData(data._nmsheet_option, req, theo_data_map, + driver_data, data._theo_shift_map, data._atm_data_map, + data._roll_over_data, data._position_map, data._presaved_aw2_theos, data._option_exp_driver_rows, data._sec_map, data._settings) { + _bbo_data_map = data._bbo_data_map, + _ticker_data = data._ticker_data, + }; + } + + public HashSet get_crossed_keys() { + HashSet filtered_keys = new HashSet(); + foreach (var t in _theo_data_map.get_data_linearly()) { + var trp = t.third; + mbts.TheoPoint tp = trp.first; + uint call_key = trp.second, put_key = trp.third; + // call side + BBOPacket call_bbo = _bbo_data_map.TryGetValue(call_key, out call_bbo) ? call_bbo : null; + if (BBOPacket.bid_through_theo(call_bbo, tp, true) || BBOPacket.ask_through_theo(call_bbo, tp, true)) + filtered_keys.Add(call_key); + BBOPacket put_bbo = _bbo_data_map.TryGetValue(put_key, out put_bbo) ? put_bbo : null; + if (BBOPacket.bid_through_theo(put_bbo, tp, false) || BBOPacket.ask_through_theo(put_bbo, tp, false)) + filtered_keys.Add(put_key); + } + return filtered_keys; + } + + public void set_bbo(IDictionary bbo_data) { _bbo_data_map = bbo_data; } + + public void set_ticker(IDictionary ticker_data) { _ticker_data = ticker_data; } + + public void set_task_data(TaskingConsolidatedData tasking_data) { _tasking_data = tasking_data; } + + /// Strikes are not sorted + public double[] get_strikes() { return _theo_data_map.get_strikes(); } + + public Dictionary get_driver_data() { return _option_exp_driver_data; } + + public Dictionary get_atm_data() { + Dictionary rv = new Dictionary(_atm_data_map); + OptionATMDataSource.fill_in_bbo(ref rv, _theo_data_map, _bbo_data_map); + return rv; + } + + public bool security_exist(DateTime expiration, double strike) { return _theo_data_map.get_data(expiration, strike) != null; } + + public bool get_security_key(DateTime exp, double strike, bool is_call, out uint security_key) { + Triplet t = _theo_data_map.get_data(exp, strike); + security_key = t != null ? (security_key = is_call ? t.second : t.third) : ExchangeSecurityMap.error_key; + return security_key != ExchangeSecurityMap.error_key; + } + + #region Putting data together (Join) + + public bool get_row_data(DateTime expiration, double strike, ref double[] cp_row, out NMSheetRowAuxiliaryData aux_data) { + Triplet tp_with_seckey = _theo_data_map.get_data(expiration, strike); + mbts.TheoPoint v = tp_with_seckey == null ? null : tp_with_seckey.first; + if (v != null) { + Tuple driver_bid_ask = _option_exp_driver_detailed_price_data.TryGetValue(expiration, out driver_bid_ask) ? driver_bid_ask : Tuple.Create(Double.NaN, Double.NaN); + _fill_theo(v, expiration, strike, cp_row); + BBOPacket call_bbo_packet, put_bbo_packet; + _fill_bbo(tp_with_seckey.second, tp_with_seckey.third, cp_row, out call_bbo_packet, out put_bbo_packet); + _fill_position(cp_row, expiration, strike); + _fill_roll_over_data(cp_row, v, expiration, strike); + _fill_presave_theos(cp_row, v, expiration, strike); + NMSheetCallPutBidAskWrapper eye_data; + _fill_eye_data(tp_with_seckey, driver_bid_ask, call_bbo_packet, put_bbo_packet, ref cp_row, out eye_data); + NMSheetCallPutBidAskWrapper quoter_data; + _fill_quoter_data(tp_with_seckey, driver_bid_ask, cp_row, out quoter_data); + NMSheetTickerData c_trade_data, p_ticker_data; + _fill_ticker_data(tp_with_seckey.second, tp_with_seckey.third, out c_trade_data, out p_ticker_data); + NMSheetCallPutWrapper cross_data; + _fill_cross_alert(call_bbo_packet, put_bbo_packet, cp_row, v, out cross_data); + aux_data = new NMSheetRowAuxiliaryData(new NMSheetCallPutWrapper(call_bbo_packet, put_bbo_packet), + cross_data, c_trade_data, p_ticker_data, eye_data, quoter_data); + return true; + } else { + aux_data = null; + return false; + } + } + + private static void _fill_theo(mbts.TheoPoint v, DateTime exp, double strike, double[] row) { + row[(int)NMSheetColumnName.call_theo] = v.call; + row[(int)NMSheetColumnName.put_theo] = v.put; + row[(int)NMSheetColumnName.call_delta] = v.cdelta; + row[(int)NMSheetColumnName.put_delta] = v.pdelta; + row[(int)NMSheetColumnName.call_gamma] = v.cgamma; + row[(int)NMSheetColumnName.put_gamma] = v.pgamma; + row[(int)NMSheetColumnName.call_vega] = v.cvega; + row[(int)NMSheetColumnName.put_vega] = v.pvega; + row[(int)NMSheetColumnName.vol] = v.vol; + row[(int)NMSheetColumnName.straddle] = v.call + v.put; + row[(int)NMSheetColumnName.strike] = strike; + row[(int)NMSheetColumnName.standard_strike] = v.standard_strike; + } + + private void _fill_cross_alert(BBOPacket c_bbo, BBOPacket p_bbo, double[] data_row, mbts.TheoPoint tp, out NMSheetCallPutWrapper cross_data) { + double call_theo, put_theo; + bool is_proximity_alert_enabled = _settings.setting_alerts.n_proximity_alert_max_ticks > 0; + if (_settings.setting_alerts.use_quoteset_mid_for_cross_alerts.Value) { + call_theo = data_row[(int)NMSheetColumnName.call_quoteset_mid_price]; + put_theo = data_row[(int)NMSheetColumnName.put_quoteset_mid_price]; + } else { + call_theo = tp.call; + put_theo = tp.put; + } + NMSheetTheoBBOCross call_cross_data = NMSheetTheoBBOCross.get_cross_state(BBOPacket.get_bid_price(c_bbo), BBOPacket.get_ask_price(c_bbo), call_theo, tp.cdelta, true, _settings.setting_driver.driver_move_interval, is_proximity_alert_enabled), + put_cross_data = NMSheetTheoBBOCross.get_cross_state(BBOPacket.get_bid_price(p_bbo), BBOPacket.get_ask_price(p_bbo), put_theo, tp.pdelta, false, _settings.setting_driver.driver_move_interval, is_proximity_alert_enabled); + cross_data = new NMSheetCallPutWrapper(call_cross_data, put_cross_data); + } + + private void _fill_ticker_data(uint call_sec_key, uint put_sec_key, out NMSheetTickerData call_trade_alert, out NMSheetTickerData put_trade_alert) { + _ticker_data.TryGetValue(call_sec_key, out call_trade_alert); + _ticker_data.TryGetValue(put_sec_key, out put_trade_alert); + } + + private void _fill_position(double[] cp_row, DateTime exp, double strike) { + cp_row[(int)NMSheetColumnName.call_position] = cp_row[(int)NMSheetColumnName.put_position] = 0; + if (_position_map != null) { + Tuple pos = _position_map.get_data(exp, strike); + if (pos != null) { + cp_row[(int)NMSheetColumnName.call_position] = pos.Item1; + cp_row[(int)NMSheetColumnName.put_position] = pos.Item2; + } + } + } + + private void _fill_bbo(uint call_sec_key, uint put_sec_key, double[] cp_row, out BBOPacket call_bbo_packet, out BBOPacket put_bbo_packet) { + call_bbo_packet = put_bbo_packet = null; + if (_bbo_data_map != null) { + _bbo_data_map.TryGetValue(call_sec_key, out call_bbo_packet); + cp_row[(int)NMSheetColumnName.call_bid_price] = BBOPacket.get_bid_price(call_bbo_packet); + cp_row[(int)NMSheetColumnName.call_bid_size] = BBOPacket.get_bid_size(call_bbo_packet); + cp_row[(int)NMSheetColumnName.call_ask_price] = BBOPacket.get_ask_price(call_bbo_packet); + cp_row[(int)NMSheetColumnName.call_ask_size] = BBOPacket.get_ask_size(call_bbo_packet); + + _bbo_data_map.TryGetValue(put_sec_key, out put_bbo_packet); + cp_row[(int)NMSheetColumnName.put_bid_price] = BBOPacket.get_bid_price(put_bbo_packet); + cp_row[(int)NMSheetColumnName.put_bid_size] = BBOPacket.get_bid_size(put_bbo_packet); + cp_row[(int)NMSheetColumnName.put_ask_price] = BBOPacket.get_ask_price(put_bbo_packet); + cp_row[(int)NMSheetColumnName.put_ask_size] = BBOPacket.get_ask_size(put_bbo_packet); + } + } + + #region Presave Theos + private void _fill_presave_theos(double[] cp_row, mbts.TheoPoint tp, DateTime option_exp, double option_strike) { + if (_presaved_aw2_theos != null) { + mbts.analytics.Theos theos = _presaved_aw2_theos.get_data(option_exp, option_strike); + if (theos != null) { + double call_theo = theos.call, put_theo = theos.put; + /// Since the theos computed by AW2 might be at a slightly different driver + /// this adjusts it to be computed at the sheet driver + if (theos.driver != tp.driver) { + call_theo = mbts.analytics.VolSurfaceCoreFunctions.compute_theo_at_nearbydriver(theos.driver, theos.call, theos.cdelta, theos.cgamma, tp.driver); + put_theo = mbts.analytics.VolSurfaceCoreFunctions.compute_theo_at_nearbydriver(theos.driver, theos.put, theos.pdelta, theos.pgamma, tp.driver); + } + cp_row[(int)NMSheetColumnName.presave_call_theo] = call_theo; + cp_row[(int)NMSheetColumnName.presave_put_theo] = put_theo; + cp_row[(int)NMSheetColumnName.presave_call_theo_diff] = call_theo - tp.call; + cp_row[(int)NMSheetColumnName.presave_put_theo_diff] = put_theo - tp.put; + } else { + cp_row[(int)NMSheetColumnName.presave_call_theo] = cp_row[(int)NMSheetColumnName.presave_put_theo] = + cp_row[(int)NMSheetColumnName.presave_call_theo_diff] = cp_row[(int)NMSheetColumnName.presave_put_theo_diff] = Double.NaN; + } + } + } + + private static double _get_time_diff_in_trading_days(double new_theo_time, double current_theo_time) { + try { + if (_is_theo_time_legal(new_theo_time) && _is_theo_time_legal(current_theo_time)) { + double hours_diff = (DateTime.FromOADate(new_theo_time) - DateTime.FromOADate(current_theo_time)).TotalHours; + return hours_diff / 6.75; /// number of hours in the trading day + } else { + return Double.NaN; + } + } catch (Exception ex) { + bts.Log.Ui.error(ex.Message); + return Double.NaN; + } + } + + private static double _min_theo_time_double = new DateTime(2000, 1, 1).ToOADate(); + private static double _max_theo_time_double = new DateTime(2100, 1, 1).ToOADate(); + private static bool _is_theo_time_legal(double theo_time) { + return !Double.IsNaN(theo_time) && theo_time > _min_theo_time_double && theo_time < _max_theo_time_double; + } + #endregion + + private void _fill_roll_over_data(double[] cp_row, mbts.TheoPoint tp, DateTime exp, double strike) { + PNLRollOverDataUnit u; + if (_roll_over_data != null && (u = _roll_over_data.getValue(exp, strike, true)) != null) { + cp_row[(int)NMSheetColumnName.vol_change] = tp.vol - u.vol; + cp_row[(int)NMSheetColumnName.straddle_change] = (tp.vol - u.vol) * tp.cvega * 2.0 * 100.0; + } else { + cp_row[(int)NMSheetColumnName.vol_change] = Double.NaN; + cp_row[(int)NMSheetColumnName.straddle_change] = Double.NaN; + } + } + + #endregion + + private static double _compute_theo(mbts.TheoPoint tp, bool is_call, double driver) { + if (is_call) + return mbts.analytics.VolSurfaceCoreFunctions.compute_theo_at_nearbydriver(tp.driver, tp.call, tp.cdelta, tp.cgamma, driver); + else + return mbts.analytics.VolSurfaceCoreFunctions.compute_theo_at_nearbydriver(tp.driver, tp.put, tp.pdelta, tp.pgamma, driver); + } + + private static double _compute_theo(mbts.TheoPoint tp, PutOrCall cp, Side side, Tuple driver_bid_ask) { + double effective_driver = ((cp == PutOrCall.Call && side == Side.Buy) || (cp == PutOrCall.Put && side == Side.Sell)) ? driver_bid_ask.Item1 : driver_bid_ask.Item2; + if (cp == PutOrCall.Call) + return mbts.analytics.VolSurfaceCoreFunctions.compute_theo_at_nearbydriver(tp.driver, tp.call, tp.cdelta, tp.cgamma, effective_driver); + else + return mbts.analytics.VolSurfaceCoreFunctions.compute_theo_at_nearbydriver(tp.driver, tp.put, tp.pdelta, tp.pgamma, effective_driver); + } + } +} \ No newline at end of file diff --git a/src/client/spark/NMSheets/BlackboardStructure/NMSheetSingleOptionDataTaskEye.cs b/src/client/spark/NMSheets/BlackboardStructure/NMSheetSingleOptionDataTaskEye.cs new file mode 100644 index 000000000..35531b6be --- /dev/null +++ b/src/client/spark/NMSheets/BlackboardStructure/NMSheetSingleOptionDataTaskEye.cs @@ -0,0 +1,45 @@ +using System; + +using bts.api; + +namespace BCG { + public partial class NMSheetSingleOptionData { + private void _fill_eye_data(Triplet tp_with_seckeys, Tuple driver_bid_ask, BBOPacket call_bbo, BBOPacket put_bbo, + ref double[] cp_row, out NMSheetCallPutBidAskWrapper out_eye_data) { + NMSheetTaskEyeData call_bid_data, call_ask_data, put_bid_data, put_ask_data; + _get_eye_security_side_data(tp_with_seckeys.first, PutOrCall.Call, Side.Buy, tp_with_seckeys.second, driver_bid_ask, call_bbo, out call_bid_data, ref cp_row, + NMSheetColumnName.call_ee_set_bid_edge, NMSheetColumnName.call_ee_set_bid_size, NMSheetColumnName.call_ee_bid_price); + _get_eye_security_side_data(tp_with_seckeys.first, PutOrCall.Call, Side.Sell, tp_with_seckeys.second, driver_bid_ask, call_bbo, out call_ask_data, ref cp_row, + NMSheetColumnName.call_ee_set_ask_edge, NMSheetColumnName.call_ee_set_ask_size, NMSheetColumnName.call_ee_ask_price); + _get_eye_security_side_data(tp_with_seckeys.first, PutOrCall.Put, Side.Buy, tp_with_seckeys.third, driver_bid_ask, put_bbo, out put_bid_data, ref cp_row, + NMSheetColumnName.put_ee_set_bid_edge, NMSheetColumnName.put_ee_set_bid_size, NMSheetColumnName.put_ee_bid_price); + _get_eye_security_side_data(tp_with_seckeys.first, PutOrCall.Put, Side.Sell, tp_with_seckeys.third, driver_bid_ask, put_bbo, out put_ask_data, ref cp_row, + NMSheetColumnName.put_ee_set_ask_edge, NMSheetColumnName.put_ee_set_ask_size, NMSheetColumnName.put_ee_ask_price); + out_eye_data = new NMSheetCallPutBidAskWrapper(call_bid_data, call_ask_data, put_bid_data, put_ask_data); + } + + private void _get_eye_security_side_data(mbts.TheoPoint tp, PutOrCall cp, Side side, uint sec_key, Tuple driver_bid_ask, BBOPacket bbo, + out NMSheetTaskEyeData inp_out_data, + ref double[] out_array, + NMSheetColumnName inp_edge_col, NMSheetColumnName inp_size_col, NMSheetColumnName eye_price_col) { + mbts.tasks.TaskSecurityEyeData eye_data = _tasking_data.get_eye_data(sec_key, side); + double edge = Double.NaN, eye_price = Double.NaN; + uint size = 0; + if (eye_data != null) { + edge = eye_data.edge; + size = eye_data.size; + /// Why is the eye sending the price instead of theo ? + if (eye_data.is_on) + eye_price = eye_data.eye_published_price; + else { + double theo = _compute_theo(tp, cp, side, driver_bid_ask); + eye_price = Math.Max(0.0, side == Side.Buy ? theo - edge : theo + edge); + } + } + out_array[(int)inp_edge_col] = edge; + out_array[(int)inp_size_col] = (double)size; + out_array[(int)eye_price_col] = eye_price; + inp_out_data = new NMSheetTaskEyeData(eye_data, side == Side.Buy ? eye_price >= BBOPacket.get_ask_price(bbo) : eye_price <= BBOPacket.get_bid_price(bbo)); + } + } +} diff --git a/src/client/spark/NMSheets/BlackboardStructure/NMSheetSingleOptionDataTaskQuoter.cs b/src/client/spark/NMSheets/BlackboardStructure/NMSheetSingleOptionDataTaskQuoter.cs new file mode 100644 index 000000000..ea37094a9 --- /dev/null +++ b/src/client/spark/NMSheets/BlackboardStructure/NMSheetSingleOptionDataTaskQuoter.cs @@ -0,0 +1,52 @@ +using System; + +using bts.api; + +namespace BCG { + public partial class NMSheetSingleOptionData { + private void _fill_quoter_data(Triplet tp_with_seckeys, Tuple driver_bid_ask, double[] cp_row, out NMSheetCallPutBidAskWrapper out_quoter_data) { + NMSheetTaskQuoterData call_bid_data, call_ask_data, put_bid_data, put_ask_data; + _get_quoter_security_side_data(tp_with_seckeys.first, PutOrCall.Call, Side.Buy, tp_with_seckeys.second, driver_bid_ask, out call_bid_data, ref cp_row, + NMSheetColumnName.call_quoter_set_bid_edge, NMSheetColumnName.call_quoter_set_bid_size, NMSheetColumnName.call_quoter_bid_price, NMSheetColumnName.call_quoter_bid_size); + _get_quoter_security_side_data(tp_with_seckeys.first, PutOrCall.Call, Side.Sell, tp_with_seckeys.second, driver_bid_ask, out call_ask_data, ref cp_row, + NMSheetColumnName.call_quoter_set_ask_edge, NMSheetColumnName.call_quoter_set_ask_size, NMSheetColumnName.call_quoter_ask_price, NMSheetColumnName.call_quoter_ask_size); + _get_quoter_security_side_data(tp_with_seckeys.first, PutOrCall.Put, Side.Buy, tp_with_seckeys.third, driver_bid_ask, out put_bid_data, ref cp_row, + NMSheetColumnName.put_quoter_set_bid_edge, NMSheetColumnName.put_quoter_set_bid_size, NMSheetColumnName.put_quoter_bid_price, NMSheetColumnName.put_quoter_bid_size); + _get_quoter_security_side_data(tp_with_seckeys.first, PutOrCall.Put, Side.Sell, tp_with_seckeys.third, driver_bid_ask, out put_ask_data, ref cp_row, + NMSheetColumnName.put_quoter_set_ask_edge, NMSheetColumnName.put_quoter_set_ask_size, NMSheetColumnName.put_quoter_ask_price, NMSheetColumnName.put_quoter_ask_size); + out_quoter_data = new NMSheetCallPutBidAskWrapper(call_bid_data, call_ask_data, put_bid_data, put_ask_data); + } + + private void _get_quoter_security_side_data(mbts.TheoPoint tp, PutOrCall cp, Side side, uint sec_key, Tuple driver_bid_ask, + out NMSheetTaskQuoterData sheet_quoter_data, + ref double[] out_array, + NMSheetColumnName inp_edge_col, NMSheetColumnName inp_size_col, + NMSheetColumnName quoter_price_col, NMSheetColumnName quoter_size_col) { + out_array = new double[] { }; + sheet_quoter_data = new NMSheetTaskQuoterData(new mbts.tasks.TaskSecurityQuoterData()); + // mbts.tasks.TaskSecurityQuoterData quoter_data = _tasking_data.get_quoter_data(sec_key, side); + // double edge = Double.NaN, quoter_working_price = Double.NaN; + // uint size = 0, quoter_working_size = 0; + // if (quoter_data != null) { + // /// If its on, get it from the quoter, + // /// else compute it + // edge = quoter_data.edge; + // size = quoter_data.size; + // if (quoter_data.is_on) { + // quoter_working_price = quoter_data.quoter_published_working_price; + // quoter_working_size = quoter_data.quoter_published_working_size; + // } else { + // quoter_working_size = size; + // double theo = _compute_theo(tp, cp, side, driver_bid_ask); + // quoter_working_price = Math.Max(0.0, side == Side.Buy ? theo - edge : theo + edge); + // quoter_working_price = NMSheetQuoterHelper.round_price_to_market(_sec_map.get_o2_security(sec_key), side, quoter_working_price); + // } + // } + // out_array[(int)inp_edge_col] = edge; + // out_array[(int)inp_size_col] = (double)size; + // out_array[(int)quoter_price_col] = quoter_working_price; + // out_array[(int)quoter_size_col] = (double)quoter_working_size; + // sheet_quoter_data = new NMSheetTaskQuoterData(quoter_data); + } + } +} \ No newline at end of file diff --git a/src/client/spark/NMSheets/BlackboardStructure/NMSheetTags.cs b/src/client/spark/NMSheets/BlackboardStructure/NMSheetTags.cs new file mode 100644 index 000000000..217ce3a0c --- /dev/null +++ b/src/client/spark/NMSheets/BlackboardStructure/NMSheetTags.cs @@ -0,0 +1,65 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +using mbts.bb; + +namespace BCG { + /// + /// All these tags are for a single instance of a sheet + /// (which has a unique id) + /// + public class NMSheetTags { + + public class ExchangeSecurityMapTag : EqualsHelper { } + /// Settings for a sheet, corresponding value is NMSheetSettings + public class NMSheetSettingsTag : NamedTag { + public NMSheetSettingsTag(object id) : base(id) { } + } + + /// Data request for a sheet, corresponding value is NMSheetDataRequest + public class NMSheetDataRequestTag : NamedTag { + public NMSheetDataRequestTag(object id) : base(id) { } + } + + /// Coordinates for a sheet, corresponding value is double[8] + /// (see NMSheetTheoGrid.get_position_details) + public class NMSheetViewableAreaTag : NamedTag { + public NMSheetViewableAreaTag(object id) : base(id) { } + } + + /// Data published as a result of NMSheetDataRequestTag, + /// corresponding data is NMSheetData + public class NMSheetDataTag : NamedTag { + public NMSheetDataTag(object id) : base(id) { } + } + + /// Corresponding value is a map of NMSheetExpiration vs VolShifts + public class NMSheetVolShiftTag : NamedTag { + public NMSheetVolShiftTag(object id) : base(id) { } + } + + public class NMSheetQuotesetOutputTag : NamedTag { + public NMSheetQuotesetOutputTag(object id) : base(id) { } + } + + /// A boolean is published to indicate if an NMSheet + /// is hidden/tabbed (false) or visible (true) + public class NMSheetVisibilityTag : NamedTag { + public NMSheetVisibilityTag(object id) : base(id) { } + } + + /// These are the AW2 preaved theos. Data is + /// ExpStrikeKeyedData of Theos + public class NMSheetPresavedTheosTag : NamedTag { + public NMSheetPresavedTheosTag(object id) : base(id) { } + } + + /// This is the list of all expirations across all open sheets + public class NMSheetActiveExpirationsTag : mbts.bb.EqualsHelper { + public NMSheetActiveExpirationsTag() : base() { } + } + } +} diff --git a/src/client/spark/NMSheets/DataProviders/NMSheetActiveExpirationsProvider.cs b/src/client/spark/NMSheets/DataProviders/NMSheetActiveExpirationsProvider.cs new file mode 100644 index 000000000..555d17fcc --- /dev/null +++ b/src/client/spark/NMSheets/DataProviders/NMSheetActiveExpirationsProvider.cs @@ -0,0 +1,71 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +using bts.utils; + +using mbts; + +namespace BCG { + /// + /// Publishes the list of all expirations that are active + /// in the sheets. This is used as a proxy for the active + /// list of contracts + /// + public class NMSheetActiveExpirationsProvider : IDisposable { + private HashSet _active_exp_map = new HashSet(); + private readonly ThreadedBlackboard _bb; + private IDictionary _setting_map = new Dictionary(); + private mbts.spark.SystemContractData _contract_data = null; + + public NMSheetActiveExpirationsProvider(ThreadedBlackboard bb) { + _bb = bb; + _bb.add_to_subscription_list(new ContractTags.SystemContractsTag()); + _bb.add_to_subscription_list(t => t is NMSheetTags.NMSheetSettingsTag); + _bb.data_callback += _handle_data; + } + + private void _handle_data(object tag, object data) { + if (tag is NMSheetTags.NMSheetSettingsTag) { + _setting_map[tag as NMSheetTags.NMSheetSettingsTag] = data as NMSheetSettings; + _compute_and_fire(); + } + if (tag is ContractTags.SystemContractsTag) { + _contract_data = data as mbts.spark.SystemContractData; + _compute_and_fire(); + } + + } + + private void _compute_and_fire() { + HashSet new_active_exps = new HashSet(); + foreach (NMSheetSettings setting in _setting_map.Values) + new_active_exps.AddRange(_get_single_sheet_exps(_contract_data, setting)); + if (!CollectionHelper.hashset_equals(new_active_exps, _active_exp_map)) { + _active_exp_map = new_active_exps; + _bb.sec_thread_write(new NMSheetTags.NMSheetActiveExpirationsTag(), _active_exp_map); + } + } + + private static IEnumerable _get_single_sheet_exps(mbts.spark.SystemContractData contract_data, NMSheetSettings settings) { + HashSet rv = new HashSet(); + if (contract_data != null && settings != null) { + foreach (NMSheetSymbol symbol in settings.setting_option_list) { + IEnumerable exps = contract_data.get_option_expirations(symbol.option_name, false); + rv.AddRange(exps.Select(e => new NMSheetExpiration(symbol, e))); + } + HashSet removed_exps = new HashSet(settings.setting_unselected_expirations); + rv.RemoveWhere(e => removed_exps.Contains(e)); + } + return rv; + } + + #region Disposable + public void Dispose() { + _bb.data_callback -= _handle_data; + } + #endregion + } +} \ No newline at end of file diff --git a/src/client/spark/NMSheets/DataProviders/NMSheetBBODataSource.cs b/src/client/spark/NMSheets/DataProviders/NMSheetBBODataSource.cs new file mode 100644 index 000000000..85e0c9848 --- /dev/null +++ b/src/client/spark/NMSheets/DataProviders/NMSheetBBODataSource.cs @@ -0,0 +1,50 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +using mbts; +using mbts.spark; + +namespace BCG { + /// This is created by the NMSheetDataCoalescer, it subsribes to the + /// bbo for each NMSheetSymbol and keeps the data around in an Dictionary> + public class NMSheetBBODataSource : IDisposable { + private readonly ThreadedBlackboard _threaded_bb; + private readonly Dictionary _tag_to_nmsymbol = new Dictionary(); + private Dictionary> _data_map = new Dictionary>(); + private Action _cb; + + public NMSheetBBODataSource(ThreadedBlackboard threaded_bb, List nmsheet_symbol_list, Action cb) { + _threaded_bb = threaded_bb; + foreach (NMSheetSymbol s in nmsheet_symbol_list) + _tag_to_nmsymbol[_get_bbo_tag(s)] = s; + _cb = cb; + _threaded_bb.add_to_subscription_list(_tag_to_nmsymbol.Keys.ToArray()); + _threaded_bb.data_callback += _react_to_bb; + } + + private object _get_bbo_tag(NMSheetSymbol s) { + // TODO + return null; + // string option_symbol = ContractUtilities.get_electronic_equivelant(bts.o2.msgs.SecurityType.OPTION, s.option_name); + // SecurityTuple sec_tuple = new SecurityTuple(bts.o2.msgs.SecurityType.OPTION, option_symbol, s.option_exchange); + // return new ShellBBODispenser.OptionBBOKeyedMapTag(sec_tuple); + } + + private void _react_to_bb(object tag, object value) { + NMSheetSymbol callback_nmsymbol = null; + if (_tag_to_nmsymbol.TryGetValue(tag, out callback_nmsymbol)) { + _data_map[callback_nmsymbol] = (IDictionary)value; + _cb(); + } + } + + public IDictionary> get_all_data() { + return new Dictionary>(_data_map); + } + + public void Dispose() { _threaded_bb.data_callback -= _react_to_bb; } + } +} diff --git a/src/client/spark/NMSheets/DataProviders/NMSheetMainDataSource.cs b/src/client/spark/NMSheets/DataProviders/NMSheetMainDataSource.cs new file mode 100644 index 000000000..a3c5c4352 --- /dev/null +++ b/src/client/spark/NMSheets/DataProviders/NMSheetMainDataSource.cs @@ -0,0 +1,42 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +using BCG.Utilities; +using BCG.Utilities.General; + +using bts.utils; + +namespace BCG { + /// Much like NMSheetBBODataSource, is created by the NMSheetDataCoalescer. + /// It creates a NMSheetSingleOptionMainDataSource for each NMSheetSymbol + /// and callbacks if the data changes. + public class NMSheetMainDataSource : IDisposable { + private readonly List _data_sources; + private Dictionary _option_data = new Dictionary(); + private Action _cb; + + public NMSheetMainDataSource(ThreadedBlackboard threaded_bb, object req_id, List nmsheet_symbol_list, Action cb) { + _cb = cb; + _data_sources = new List(); + foreach (NMSheetSymbol s in nmsheet_symbol_list) + _data_sources.Add(new NMSheetSingleOptionMainDataSource(req_id, threaded_bb, s, _on_data)); + } + + private void _on_data(Pair data) { + _option_data[data.first] = data.second; + bts.Log.Ui.diag(String.Format("NMSheetMainDataSource._on_data {0} calling back {1}", data.first, DateTime.Now)); + _cb(); + } + + public Dictionary get_data() { return new Dictionary(_option_data); } + + #region IDisposable + public void Dispose() { + foreach (NMSheetSingleOptionMainDataSource d in _data_sources) + d.Dispose(); + } + #endregion + } +} diff --git a/src/client/spark/NMSheets/DataProviders/NMSheetPresavedTheosProvider.cs b/src/client/spark/NMSheets/DataProviders/NMSheetPresavedTheosProvider.cs new file mode 100644 index 000000000..1202d1cdf --- /dev/null +++ b/src/client/spark/NMSheets/DataProviders/NMSheetPresavedTheosProvider.cs @@ -0,0 +1,60 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace BCG { + public class NMSheetPresavedTheosProvider : IDisposable { + // private readonly ThreadedBlackboard _bb; + // private readonly IEnumerable _symbols; + // private readonly object _req_id; + // private readonly object _in_usage_tag = new VolSurfaceBlackboardTags.VolSurfaceUsageTag(); + // private IDictionary _usage_map = new Dictionary(); + + public NMSheetPresavedTheosProvider(ThreadedBlackboard bb, IEnumerable symbols, object req_id) { + // _bb = bb; + // _symbols = symbols; + // _req_id = req_id; + // _bb.add_to_subscription_list(_in_usage_tag); + // _bb.add_to_subscription_list(t => (t != null && t is TheoTags.PresaveTheoTag)); + // _bb.data_callback += _on_bb_data; + } + + private void _on_bb_data(object tag, object data) { + // if (_in_usage_tag.Equals(tag)) { + // IEnumerable> usage_list = data as IEnumerable>; + // if (usage_list != null) { + // foreach (NMSheetSymbol s in _symbols) { + // Tuple f = usage_list.FirstOrDefault(t => t.Item1 == bts.o2.msgs.SecurityType.OPTION && t.Item2 == s.option_name); + // if (f != null) + // _usage_map[s] = f.Item3; + // } + // } + // _compute_and_fire(); + // } else if (tag != null && tag is TheoTags.PresaveTheoTag) { + // _compute_and_fire(); + // } + } + + private void _compute_and_fire() { + // IDictionary> rv = new Dictionary>(); + // if (_usage_map != null) + // foreach (KeyValuePair kv in _usage_map) { + // NMSheetSymbol sym = kv.Key; int vs_id = kv.Value; + // VolSurfaceTheoData vs_theo_data = _bb.sec_thread_retrieve_from_cache(new TheoTags.PresaveTheoTag(vs_id)) as VolSurfaceTheoData; + // if (vs_theo_data != null) + // rv[sym] = vs_theo_data.get_exp_mapped_data(sym.option_name, true); + // else + // rv[sym] = new ExpStrikeKeyedData(); + // } + // _bb.sec_thread_write(new NMSheetTags.NMSheetPresavedTheosTag(_req_id), rv); + } + + #region IDisposable + public void Dispose() { + // _bb.data_callback -= _on_bb_data; + } + #endregion + } +} \ No newline at end of file diff --git a/src/client/spark/NMSheets/DataProviders/NMSheetSingleOptionMainDataSource.cs b/src/client/spark/NMSheets/DataProviders/NMSheetSingleOptionMainDataSource.cs new file mode 100644 index 000000000..123f72d75 --- /dev/null +++ b/src/client/spark/NMSheets/DataProviders/NMSheetSingleOptionMainDataSource.cs @@ -0,0 +1,252 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +using BCG.Utilities; +using BCG.Utilities.General; + +using bts.utils; + +using mbts.bb; + +namespace BCG { + /// For each NMSheetSymbol in an NMSheet gets all the + /// data together (theos, position, vol change etc) + /// and fires a callback. + /// This is where all the data is gathered, the rest + /// is all access to this + public class NMSheetSingleOptionMainDataSource : IDisposable { + private ThreadedBlackboard _threaded_bb; + private readonly object _in_bb_main_sheet_request_tag, _in_bb_secmap_tag, _in_bb_live_theos_tag, _in_bb_live_driver_bbo_tag, _in_bb_precomputed_sparse_theos_tag, + _in_bb_vol_shift_tag, _in_bb_symbol_theo_shift_tag, _in_bb_rollover_data_tag, _in_bb_presaved_aw2_theos_tag, + _in_exp_param_tag, _in_bb_position_tag, _in_bb_sheet_settings_tag, _in_bb_onefive_value_tag, _in_bb_qs_tag, + _in_bb_main_sheet_visibility_tag, _in_bb_option_driver_detailed_price_tag; + private readonly NMSheetSymbol _nmsheet_symbol; + private Action> _cb; + private PerfStatsLogger _logger = new PerfStatsLogger(); + private readonly string _log_msg_id; + private string _electronic_equivelant_symbol; + + public NMSheetSingleOptionMainDataSource(object req_id, ThreadedBlackboard threaded_bb, NMSheetSymbol option, Action> callback) { + _threaded_bb = threaded_bb; + _nmsheet_symbol = option; + _electronic_equivelant_symbol = option.option_name; // TODO ContractUtilities.get_electronic_equivelant(bts.o2.msgs.SecurityType.OPTION, option.option_name); + _cb = callback; + _log_msg_id = String.Format("NMSheetSingleOptionMainDataSource._compute_and_fire_{0} sheet id {1}", _nmsheet_symbol, req_id); + /// input + _in_bb_main_sheet_request_tag = new NMSheetTags.NMSheetDataRequestTag(req_id); + _in_bb_secmap_tag = new NMSheetTags.ExchangeSecurityMapTag(); + _in_bb_live_theos_tag = new TheoTags.LiveOptionTheoTag(_nmsheet_symbol.option_name); + _in_bb_live_driver_bbo_tag = new MarketDataTags.OptionDriverBBOTag(_nmsheet_symbol.option_name); + _in_bb_precomputed_sparse_theos_tag = new TheoTags.PrecomputedOptionTheoTag(_nmsheet_symbol.option_name); + _in_bb_vol_shift_tag = new NMSheetTags.NMSheetVolShiftTag(req_id); + _in_bb_symbol_theo_shift_tag = new OptionSymbolTheoShiftTag(_nmsheet_symbol.option_name); + _in_bb_rollover_data_tag = new TheoTags.PNLRollOverDataTag(_nmsheet_symbol.option_name); + _in_bb_presaved_aw2_theos_tag = new NMSheetTags.NMSheetPresavedTheosTag(req_id); + _in_exp_param_tag = new TheoTags.OptionRollsTag(_nmsheet_symbol.option_name); + _in_bb_position_tag = new TradeAndPositionTags.OptionSymbolPositionTag(_nmsheet_symbol.option_name); + _in_bb_sheet_settings_tag = new NMSheetTags.NMSheetSettingsTag(req_id); + _in_bb_onefive_value_tag = new OneFiveValueTag(_nmsheet_symbol.option_name); + _in_bb_qs_tag = new NMSheetTags.NMSheetQuotesetOutputTag(req_id); + _in_bb_main_sheet_visibility_tag = new NMSheetTags.NMSheetVisibilityTag(req_id); + _in_bb_option_driver_detailed_price_tag = new MarketDataTags.OptionDriverDetailedBBOTag(option.option_name); + /// output + _threaded_bb.data_callback += _react_to_bb; + _threaded_bb.add_to_subscription_list(_in_bb_main_sheet_request_tag, _in_bb_secmap_tag, _in_bb_live_driver_bbo_tag, _in_bb_live_theos_tag, _in_bb_precomputed_sparse_theos_tag, + _in_bb_vol_shift_tag, _in_bb_symbol_theo_shift_tag, _in_bb_rollover_data_tag, _in_bb_presaved_aw2_theos_tag, + _in_exp_param_tag, _in_bb_position_tag, _in_bb_sheet_settings_tag, _in_bb_onefive_value_tag, _in_bb_qs_tag, + _in_bb_main_sheet_visibility_tag, _in_bb_option_driver_detailed_price_tag); + + } + + private void _react_to_bb(object tag, object value) { + if (_in_bb_main_sheet_request_tag.Equals(tag) || _in_bb_secmap_tag.Equals(tag) || _in_bb_live_theos_tag.Equals(tag) || /*_in_bb_live_driver_bbo_tag.Equals(tag) ||*/ _in_bb_precomputed_sparse_theos_tag.Equals(tag) || + _in_bb_vol_shift_tag.Equals(tag) || _in_bb_symbol_theo_shift_tag.Equals(tag) || _in_exp_param_tag.Equals(tag) || _in_bb_presaved_aw2_theos_tag.Equals(tag) || + _in_bb_position_tag.Equals(tag) || _in_bb_rollover_data_tag.Equals(tag) || _in_bb_sheet_settings_tag.Equals(tag) || _in_bb_qs_tag.Equals(tag) || + _in_bb_main_sheet_visibility_tag.Equals(tag)) + _compute_and_fire(); + } + + private void _compute_and_fire() { + if (_is_main_sheet_active()) { + HighPerformanceTimer timer = new HighPerformanceTimer(); + timer.start(); + NMSheetDataRequest data_request = (NMSheetDataRequest)_threaded_bb.sec_thread_retrieve_from_cache(_in_bb_main_sheet_request_tag) ?? new NMSheetDataRequest(new List>()); + data_request = NMSheetDataRequest.restrict_for_symbol(data_request, _nmsheet_symbol); + Dictionary> live_driver_map = (Dictionary>)_threaded_bb.sec_thread_retrieve_from_cache(_in_bb_live_driver_bbo_tag); + IDictionary> sym_presaved_aw2_theos = _threaded_bb.sec_thread_retrieve_from_cache(_in_bb_presaved_aw2_theos_tag) as IDictionary>; + ExpStrikeKeyedData presaved_aw2_theos = (sym_presaved_aw2_theos != null && sym_presaved_aw2_theos.TryGetValue(_nmsheet_symbol, out presaved_aw2_theos)) ? presaved_aw2_theos : null; + NMSheetSettings sheet_settings = (NMSheetSettings)_threaded_bb.sec_thread_retrieve_from_cache(_in_bb_sheet_settings_tag) ?? new NMSheetSettings(); + ExpStrikeKeyedData shared_live_theo_data_map = (ExpStrikeKeyedData)_threaded_bb.sec_thread_retrieve_from_cache(_in_bb_live_theos_tag); + + if (data_request != null && live_driver_map != null && shared_live_theo_data_map != null) { + ExpStrikeKeyedData output_theo_data_map = _limit_to_requested_securities(shared_live_theo_data_map, data_request, sheet_settings); + output_theo_data_map = _adjust_for_freezes(output_theo_data_map, data_request); + _add_vol_shift(output_theo_data_map); + ExpStrikeKeyedData> output_theo_key_data_map = _attach_sec_keys(output_theo_data_map); + Dictionary option_exp_driver_data_map = _get_option_exp_driver_data_map(data_request, output_theo_data_map, shared_live_theo_data_map, live_driver_map); + NMSheetSingleOptionData theo_data = new NMSheetSingleOptionData(_nmsheet_symbol, + data_request, + output_theo_key_data_map, + option_exp_driver_data_map, + (OptionContractKeyedData)_threaded_bb.sec_thread_retrieve_from_cache(_in_bb_symbol_theo_shift_tag) ?? new OptionContractKeyedData(), + _get_atm_data(output_theo_data_map), + _get_rollover_data(), + _get_position_map(), + presaved_aw2_theos, + _threaded_bb.sec_thread_retrieve_from_cache(_in_bb_option_driver_detailed_price_tag)/* as IDictionary ?? new Dictionary()*/, + _threaded_bb.sec_thread_retrieve_from_cache(_in_bb_secmap_tag) as ExchangeSecurityMap, + sheet_settings); + timer.stop(); + _cb(new Pair(_nmsheet_symbol, theo_data)); + _logger.log(_log_msg_id, _log_msg_id, timer.lastIntervalTime); + } + } + } + + private bool _is_main_sheet_active() { + object rv = _threaded_bb.sec_thread_retrieve_from_cache(_in_bb_main_sheet_visibility_tag); + return rv == null || (bool)rv; + } + + private ExpStrikeKeyedData _limit_to_requested_securities(ExpStrikeKeyedData theo_data, NMSheetDataRequest data_request, NMSheetSettings sheet_settings) { + HashSet selected_exp_map = new HashSet(); + HashSet selected_strike_map = new HashSet(sheet_settings.setting_unselected_strikes); + foreach (Triplet t in data_request.expiration_request_list) { + NMSheetExpiration nm_exp = t.first; + if (nm_exp != null && nm_exp.option_name == _nmsheet_symbol.option_name) + selected_exp_map.Add(nm_exp.option_expiration); + } + return theo_data.clone_filtered_set(selected_exp_map, true, selected_strike_map, false); + } + + private ExpStrikeKeyedData> _attach_sec_keys(ExpStrikeKeyedData theo_map) { + theo_map = theo_map ?? new ExpStrikeKeyedData(); + ExchangeSecurityMap sec_map = _threaded_bb.sec_thread_retrieve_from_cache(_in_bb_secmap_tag) as ExchangeSecurityMap; + if (sec_map != null) + return sec_map.attach_sec_keys(theo_map, _electronic_equivelant_symbol, _nmsheet_symbol.option_exchange); + else { + ExpStrikeKeyedData> rv = new ExpStrikeKeyedData>(); + foreach (Triplet t in theo_map.get_data_linearly()) + rv.set_data(t.first, t.second, new Triplet(t.third, 0, 0)); + return rv; + } + } + + private ExpStrikeKeyedData _adjust_for_freezes(ExpStrikeKeyedData live_theo_map, NMSheetDataRequest data_request) { + return live_theo_map; + // TODO + // ExpStrikeKeyedData rv = new ExpStrikeKeyedData(); + // OptionTheoInterpolationData interp_sparse_theo_data = (OptionTheoInterpolationData)_threaded_bb.sec_thread_retrieve_from_cache(_in_bb_precomputed_sparse_theos_tag); + // foreach (Triplet t in data_request.expiration_request_list) { + // NMSheetExpiration nm_exp = t.first; + // bool frozen = t.second; + // double frozen_price = t.third; + // if (frozen) { + // if (interp_sparse_theo_data != null) { + // List strike_list_for_exp = live_theo_map.get_strike_list_for_expiration(nm_exp.option_expiration); + // Dictionary strike_theos = StatelessInterpolationCalculator.compute_theos(nm_exp.option_expiration, strike_list_for_exp, interp_sparse_theo_data, frozen_price); + // rv.set_data_for_expiration(nm_exp.option_expiration, strike_theos); + // } + // } else { + // IDictionary data_for_this_exp = live_theo_map.get_data_for_single_exp(nm_exp.option_expiration); + // if (data_for_this_exp != null) + // rv.set_data_for_expiration(nm_exp.option_expiration, data_for_this_exp); + // } + // } + // return rv; + } + + private Dictionary _get_option_exp_driver_data_map(NMSheetDataRequest data_request, + ExpStrikeKeyedData output_theo_data_map, ExpStrikeKeyedData shared_live_theo_data_map, + Dictionary> live_driver_map) { + Dictionary rv = new Dictionary(); + foreach (Triplet theo_request in data_request.expiration_request_list) { + DateTime option_expiration = theo_request.first.option_expiration; + /// live driver + Triplet live_driver_info; + live_driver_map.TryGetValue(option_expiration, out live_driver_info); + live_driver_info = live_driver_info ?? new Triplet(String.Empty, DateTime.MinValue, Double.NaN); + /// computed driver + double computed_driver_price = _get_driverprice_for_expiration(output_theo_data_map, option_expiration); + rv[option_expiration] = new NMSheetDriverData(live_driver_info.first, live_driver_info.second, live_driver_info.third, computed_driver_price, theo_request.second); + } + return rv; + } + + private static double _get_driverprice_for_expiration(ExpStrikeKeyedData theo_data_map, DateTime option_expiration) { + IDictionary exp_data = theo_data_map.get_data_for_single_exp(option_expiration); + if (exp_data != null) + foreach (mbts.TheoPoint tp in exp_data.Values) + return tp.driver; + return Double.NaN; + } + + private IDictionary _get_atm_data(ExpStrikeKeyedData theo_data) { + NMSheetSettings sheet_settings = (NMSheetSettings)_threaded_bb.sec_thread_retrieve_from_cache(_in_bb_sheet_settings_tag) ?? new NMSheetSettings(); + IDictionary option_exp_roll_data = (_threaded_bb.sec_thread_retrieve_from_cache(_in_exp_param_tag) as IDictionary) ?? new Dictionary(); + IDictionary atm_data = OptionATMDataSource.compute_atm_data(_nmsheet_symbol.option_name, _get_onefive(), theo_data, option_exp_roll_data); + if (sheet_settings.setting_atm.select_atm_nearest_strike_only) + foreach (ATMData exp_atm_data in atm_data.Values) + exp_atm_data.reduce_to_nearest_expiration(); + return atm_data; + } + + private OptionContractKeyedData _get_rollover_data() { return (OptionContractKeyedData)_threaded_bb.sec_thread_retrieve_from_cache(_in_bb_rollover_data_tag); } + + private ExpStrikeKeyedData> _get_position_map() { return (ExpStrikeKeyedData>)_threaded_bb.sec_thread_retrieve_from_cache(_in_bb_position_tag); } + + private double _get_onefive() { + // object dp_obj = _threaded_bb.sec_thread_retrieve_from_cache(_in_bb_onefive_value_tag); + // if (dp_obj != null) { + // DataPacket dp = dp_obj as DataPacket; + // if (dp.newRows.Count > 0) + // return BlueDataUtility.get_row_value(BlueDataUtility.extractRow(dp.newRows, 0), "scalarData", 0.0); + // } + return 0.0; + } + + #region Vol Shift + + private void _add_vol_shift(ExpStrikeKeyedData theo_data) { + object obj_map = _threaded_bb.sec_thread_retrieve_from_cache(_in_bb_vol_shift_tag); + if (obj_map != null) + add_vol_shift(_nmsheet_symbol, theo_data, obj_map as Dictionary); + } + + internal static void add_vol_shift(NMSheetSymbol apply_to_symbol, ExpStrikeKeyedData theo_data, Dictionary exp_shift_map) { + foreach (KeyValuePair p in exp_shift_map) { + if (p.Key.nmsheet_symbol.Equals(apply_to_symbol)) { + DateTime option_expiration = p.Key.option_expiration; + double shift = p.Value; + if (shift != 0) { + IDictionary exp_theos = theo_data.get_data_for_single_exp(option_expiration); + if (exp_theos != null) { + Dictionary shifted_exp_theos = new Dictionary(); + foreach (KeyValuePair strike_tp in exp_theos) { + mbts.TheoPoint new_tp = (mbts.TheoPoint)strike_tp.Value.Clone(); + add_vol_shift(new_tp, shift); + shifted_exp_theos[strike_tp.Key] = new_tp; + } + theo_data.set_data_for_expiration(option_expiration, shifted_exp_theos); + } + } + } + } + } + + internal static void add_vol_shift(mbts.TheoPoint v, double shift) { + v.call += v.cvega * shift; + v.put += v.pvega * shift; + } + + #endregion + + #region IDisposable + public void Dispose() { + _threaded_bb.data_callback -= _react_to_bb; + } + #endregion + } +} \ No newline at end of file diff --git a/src/client/spark/NMSheets/DataProviders/NMSheetTickerDataSource.cs b/src/client/spark/NMSheets/DataProviders/NMSheetTickerDataSource.cs new file mode 100644 index 000000000..621b2d391 --- /dev/null +++ b/src/client/spark/NMSheets/DataProviders/NMSheetTickerDataSource.cs @@ -0,0 +1,140 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace BCG { + public enum NMSheetTradeAlert { + OverTheo = 0, + UnderTheo, + None + } + + public class NMSheetTickerData { + public readonly NMSheetTradeAlert trade_alert; + public readonly DateTime trade_time; + public readonly double trade_price; + public readonly uint trade_size; + public NMSheetTickerData(DateTime the_trade_time, double the_trade_price, uint the_trade_size, double the_theo_price) { + trade_time = the_trade_time; + trade_price = the_trade_price; + trade_size = the_trade_size; + trade_alert = trade_price >= the_theo_price ? NMSheetTradeAlert.OverTheo : NMSheetTradeAlert.UnderTheo; + } + } + + public class NMSheetTickerDataSource : IDisposable { + // private readonly ThreadedBlackboard _threaded_bb; + // private readonly List _nmsheet_symbol_list; + // private Action _cb; + // private readonly Dictionary _in_data_tag_map = new Dictionary(); + // private readonly Dictionary _out_req_tag = new Dictionary(); + // private readonly NMSheetTags.NMSheetSettingsTag _in_nmsheet_setting_tag; + // private IDictionary _data_map = new Dictionary(); + // private PerfStatsLogger _logger = new PerfStatsLogger(); + // private BCG.Utilities.General.HighPerformanceTimer _timer = new Utilities.General.HighPerformanceTimer(); + // private readonly TimeSpan _cleanup_period = TimeSpan.FromMilliseconds(1000.0); + // private DateTime _last_cleanup_time = DateTime.MinValue; + + //private int _security_key_index = -1, _trade_time_index = -1, _trade_price_index, _trade_size_index, _trade_theo_index = -1; + + public NMSheetTickerDataSource(ThreadedBlackboard threaded_bb, List nmsheet_symbol_list, object nmsheet_req_id, Action cb) { + // _threaded_bb = threaded_bb; + // _nmsheet_symbol_list = nmsheet_symbol_list; + // _cb = cb; + // _in_nmsheet_setting_tag = new NMSheetTags.NMSheetSettingsTag(nmsheet_req_id); + + // foreach (NMSheetSymbol s in nmsheet_symbol_list) { + // string ticker_req_id = Guid.NewGuid().ToString(); + // _out_req_tag[new GeneralTradeTickerRequest.GeneralTradeTickerRequestTag(ticker_req_id)] = s; + // _in_data_tag_map[new GeneralTradeTickerData.GeneralTradeTickerDataTag(ticker_req_id)] = s; + // } + // _threaded_bb.add_to_subscription_list(_in_nmsheet_setting_tag); + // foreach (GeneralTradeTickerData.GeneralTradeTickerDataTag t in _in_data_tag_map.Keys) + // _threaded_bb.add_to_subscription_list(t); + // _threaded_bb.data_callback += _react_to_bb; + // _send_request(); + } + + private void _send_request() { + // NMSheetSettings settings = _threaded_bb.sec_thread_retrieve_from_cache(_in_nmsheet_setting_tag) as NMSheetSettings ?? new NMSheetSettings(); + // foreach (KeyValuePair p in _out_req_tag) { + // NMSheetSymbol nmsheet_sym = p.Value; + // mbts.SecurityTuple st = new mbts.SecurityTuple(bts.o2.msgs.SecurityType.OPTION, nmsheet_sym.option_name, nmsheet_sym.option_exchange); + // _threaded_bb.sec_thread_write(p.Key, new GeneralTradeTickerRequest(new mbts.SecurityTuple[] { st }, + // new string[] { bts.o2.msgs.SecurityType.OPTION.ToString() }, + // new DateTime[] { }, new string[] { }, String.Empty, + // settings.setting_alerts.trade_alert_size.Value, 1, 10)); + // } + } + + private void _react_to_bb(object tag, object value) { + // NMSheetSymbol nmsheet_symbol; + // if (_in_nmsheet_setting_tag.Equals(tag)) + // _send_request(); + // else if (tag is GeneralTradeTickerData.GeneralTradeTickerDataTag && _in_data_tag_map.TryGetValue(tag as GeneralTradeTickerData.GeneralTradeTickerDataTag, out nmsheet_symbol)) { + // GeneralTradeTickerData ticker_data = value as GeneralTradeTickerData; + // _handle_data(ticker_data, nmsheet_symbol); + // } + } + + // private void _handle_data(GeneralTradeTickerData ticker_data, NMSheetSymbol nmsheet_symbol) { + // if (ticker_data != null && ticker_data.dp != null) { + // _timer.start(); + // foreach (IBlueRow r in ticker_data.dp.addedRows) { + // _init_index(ticker_data.dp.schema); + // uint security_key = BlueDataUtility.get_row_value(r, _security_key_index, 0); + // DateTime trade_time = BlueDataUtility.get_row_datetime_value(r, _trade_time_index, DateTime.MinValue); + // double trade_price = BlueDataUtility.get_row_value(r, _trade_price_index, Double.NaN); + // uint trade_size = BlueDataUtility.get_row_value(r, _trade_size_index, 0); + // double trade_theo = BlueDataUtility.get_row_value(r, _trade_theo_index, Double.NaN); + // _data_map[security_key] = new NMSheetTickerData(trade_time, trade_price, trade_size, trade_theo); + // } + // _timer.stop(); + // _logger.log("NMSheetTickerDataSource", String.Format("NMSheetTickerDataSource {0} {1}", nmsheet_symbol.ToString(), ticker_data.dp.ToString()), _timer.lastIntervalTime); + // } + // } + + // private void _init_index(IBlueTableSchema schema) { + // if (_security_key_index == -1) { + // _security_key_index = schema["security_key"].colNo; + // _trade_time_index = schema["last_trade_time"].colNo; + // _trade_price_index = schema["last_trade_price"].colNo; + // _trade_size_index = schema["last_trade_size"].colNo; + // _trade_theo_index = schema["theo"].colNo; + // } + // } + + public IDictionary get_data() { + return new Dictionary(); + // _cleanup_old_trades(); + // return new Dictionary(_data_map); + } + + // private void _cleanup_old_trades() { + // if (DateTime.Now - _last_cleanup_time >= _cleanup_period) { + // _timer.start(); + // _last_cleanup_time = DateTime.Now; + // NMSheetSettings settings = _threaded_bb.sec_thread_retrieve_from_cache(_in_nmsheet_setting_tag) as NMSheetSettings ?? new NMSheetSettings(); + // UInt32 threshold_seconds = settings.setting_alerts.trade_alert_time_seconds.Value; + // foreach (KeyValuePair p in _data_map.ToArray()) + // if (_last_cleanup_time.Subtract(p.Value.trade_time).Seconds >= threshold_seconds) + // _data_map.Remove(p.Key); + // _timer.stop(); + // _logger.log("NMSheetTickerDataSource:_udpate_time_stamps", String.Format("NMSheetTickerDataSource:_udpate_time_stamps"), _timer.lastIntervalTime); + // } + // } + + private bool _is_disposed = false; + #region IDisposable + public void Dispose() { + if (!_is_disposed) { + _is_disposed = true; + //_threaded_bb.data_callback -= _react_to_bb; + } + } + #endregion + + } +} diff --git a/src/client/spark/NMSheets/INMSheetGridFacingData.cs b/src/client/spark/NMSheets/INMSheetGridFacingData.cs new file mode 100644 index 000000000..b649b3191 --- /dev/null +++ b/src/client/spark/NMSheets/INMSheetGridFacingData.cs @@ -0,0 +1,143 @@ +using System; +using System.Collections; +using System.Collections.Generic; + +using bts.api; + +namespace BCG { + public class NMSheetCallPutWrapper { + private readonly T _c_data, _p_data; + public NMSheetCallPutWrapper(T c_data, T p_data) { + _c_data = c_data; + _p_data = p_data; + } + public T get_data(PutOrCall cp) { + return cp == PutOrCall.Call ? _c_data : _p_data; + } + } + + public class NMSheetBidAskWrapper { + private readonly T _bid_data, _ask_data; + public NMSheetBidAskWrapper(T bid_data, T ask_data) { + _bid_data = bid_data; + _ask_data = ask_data; + } + public T get_data(Side side) { + return side == Side.Buy ? _bid_data : _ask_data; + } + } + + public class NMSheetCallPutBidAskWrapper { + private readonly T _c_bid, _c_ask, _p_bid, _p_ask; + + public NMSheetCallPutBidAskWrapper(T the_c_bid, T the_c_ask, T the_p_bid, T the_p_ask) { + _c_bid = the_c_bid; + _c_ask = the_c_ask; + _p_bid = the_p_bid; + _p_ask = the_p_ask; + } + + public T get_data(PutOrCall cp, Side side) { + return cp == PutOrCall.Call ? (side == Side.Buy ? _c_bid : _c_ask) : (side == Side.Buy ? _p_bid : _p_ask); + } + + public T get_data(bool is_call, bool is_bid) { + return get_data(is_call ? PutOrCall.Call : PutOrCall.Put, is_bid ? Side.Buy : Side.Sell); + } + } + + public class NMSheetTheoBBOCross { + public enum CrossState { + bid_cross, /// theo <= bid + ask_cross, /// theo >= ask + bid_proximity, /// theo is closer to bid + ask_proximity, /// theo is closer to ask + none, + } + public readonly CrossState cross_state; + public readonly uint tick_distance; + + public NMSheetTheoBBOCross(CrossState the_cross_state, uint the_tick_distance) { + cross_state = the_cross_state; + tick_distance = the_tick_distance; + } + + public static NMSheetTheoBBOCross get_cross_state(double bid_price, double ask_price, double theo, double delta, bool is_call, double driver_tick_size, bool is_proximity_alert_enabled) { + double abs_delta = Math.Abs(delta); + abs_delta = abs_delta == 0 ? Double.Epsilon : abs_delta; + if (!Double.IsNaN(theo) && !Double.IsNaN(bid_price) && theo < bid_price) + return new NMSheetTheoBBOCross(CrossState.bid_cross, 0); + else if (!Double.IsNaN(theo) && !Double.IsNaN(ask_price) && theo > ask_price) + return new NMSheetTheoBBOCross(CrossState.ask_cross, 0); + else if (is_proximity_alert_enabled) { + /// bool is passed to bypass doing the below + /// if the user has proximity alert turned off + double bid_distance = theo - bid_price, ask_distance = ask_price - theo; + /// call_theo will cross the bid_price on a down move, and the ask_price on an up move; + /// opposite for put_theo. however since we are not alerting on the direction but + /// on the proximity directionlessly, hence we dont need to distinguish + if (!Double.IsNaN(bid_distance) && bid_distance < _nan_wrapper(ask_distance, Double.PositiveInfinity)) { + double n_ticks = Math.Min(bid_distance / (abs_delta * driver_tick_size), _n_max_ticks); + return new NMSheetTheoBBOCross(CrossState.bid_proximity, Convert.ToUInt32(Math.Ceiling(n_ticks))); + } else if (!Double.IsNaN(ask_distance) && ask_distance < _nan_wrapper(bid_distance, Double.PositiveInfinity)) { + double n_ticks = Math.Min(ask_distance / (abs_delta * driver_tick_size), _n_max_ticks); + return new NMSheetTheoBBOCross(CrossState.ask_proximity, Convert.ToUInt32(Math.Ceiling(n_ticks))); + } + } + return NMSheetTheoBBOCross.get_nulled_obj(); + } + + private static double _n_max_ticks = 100.0; + private static NMSheetTheoBBOCross _nulled_obj = new NMSheetTheoBBOCross(CrossState.none, 0); + public static NMSheetTheoBBOCross get_nulled_obj() { return _nulled_obj; } + private static double _nan_wrapper(double v, double nan_replacelement) { return !Double.IsNaN(v) ? v : nan_replacelement; } + + } + + public class NMSheetTaskEyeData { + public readonly mbts.tasks.TaskSecurityEyeData eye_data; + public readonly bool is_eye_cross; + + public NMSheetTaskEyeData(mbts.tasks.TaskSecurityEyeData eye_data, bool is_eye_cross) { + this.eye_data = eye_data; + this.is_eye_cross = is_eye_cross; + } + } + + public class NMSheetTaskQuoterData { + public readonly mbts.tasks.TaskSecurityQuoterData quoter_data; + + public NMSheetTaskQuoterData(mbts.tasks.TaskSecurityQuoterData quoter_data) { + this.quoter_data = quoter_data; + } + } + + public class NMSheetRowAuxiliaryData { + public readonly NMSheetCallPutWrapper cross_state; + public readonly NMSheetCallPutWrapper bbo_data; + public readonly NMSheetTickerData call_ticker_data, put_ticker_data; + public readonly NMSheetCallPutBidAskWrapper task_ee_data; + public readonly NMSheetCallPutBidAskWrapper task_quoter_data; + + public NMSheetRowAuxiliaryData(NMSheetCallPutWrapper the_bbo_data, + NMSheetCallPutWrapper the_cross_state, + NMSheetTickerData the_call_trade_alert, + NMSheetTickerData the_put_trade_alert, + NMSheetCallPutBidAskWrapper the_task_ee_data, + NMSheetCallPutBidAskWrapper the_task_quoter_data) { + bbo_data = the_bbo_data; + cross_state = the_cross_state; + call_ticker_data = the_call_trade_alert; + put_ticker_data = the_put_trade_alert; + task_ee_data = the_task_ee_data; + task_quoter_data = the_task_quoter_data; + } + } + + public interface INMSheetGridFacingData { + NMSheetExpiration[] get_sorted_expirations(); + double[] get_sorted_strikes(); + IDictionary get_atm_data(); + bool get_row_data(NMSheetSymbol nmsheet_symbol, DateTime option_expiration, double strike, ref double[] row_value, out NMSheetRowAuxiliaryData aux_data); + } +} \ No newline at end of file diff --git a/src/client/spark/NMSheets/Misc/NMSheetDisplayFormatter.cs b/src/client/spark/NMSheets/Misc/NMSheetDisplayFormatter.cs new file mode 100644 index 000000000..cb67be315 --- /dev/null +++ b/src/client/spark/NMSheets/Misc/NMSheetDisplayFormatter.cs @@ -0,0 +1,157 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace BCG { + /// + /// Formatter for the NMSheetTheoGrid. Mainly + /// 2 functions format_expiration and format_value. + /// Uses NMSheetFormattingCacheHelper to cache values + /// to avoid formatting. + /// + public class NMSheetDisplayFormatter { + private NMSheetFormattingCacheHelper _cache_helper; + private readonly BCG.Utilities.General.TickConverter2.TickType[] _tick_type_list; + //private static bool _use_cached_values = "true".Equals(BCG.Utilities.BlueConfiguration.ConfigurationRequester.request("cacheTheoFormat")); + private static HashSet _empty_nan_col_map = new HashSet( + new NMSheetColumnName[] + { + ///market price + NMSheetColumnName.call_bid_price, + NMSheetColumnName.call_ask_price, + NMSheetColumnName.put_bid_price, + NMSheetColumnName.put_ask_price, + /// quoteset edge + NMSheetColumnName.call_quoteset_resolved_bid_edge, + NMSheetColumnName.call_quoteset_resolved_ask_edge, + NMSheetColumnName.put_quoteset_resolved_bid_edge, + NMSheetColumnName.put_quoteset_resolved_ask_edge, + ///final quoter edge/size + NMSheetColumnName.call_quoter_set_bid_edge, + NMSheetColumnName.call_quoter_set_ask_edge, + NMSheetColumnName.put_quoter_set_bid_edge, + NMSheetColumnName.put_quoter_set_ask_edge, + NMSheetColumnName.call_quoter_set_bid_size, + NMSheetColumnName.call_quoter_set_ask_size, + NMSheetColumnName.put_quoter_set_bid_size, + NMSheetColumnName.put_quoter_set_ask_size, + /// final quoter edge/size + NMSheetColumnName.call_quoter_bid_price, + NMSheetColumnName.call_quoter_ask_price, + NMSheetColumnName.put_quoter_bid_price, + NMSheetColumnName.put_quoter_ask_price, + NMSheetColumnName.call_quoter_bid_size, + NMSheetColumnName.call_quoter_ask_size, + NMSheetColumnName.put_quoter_bid_size, + NMSheetColumnName.put_quoter_ask_size, + /// quoteset mid point + NMSheetColumnName.call_quoteset_mid_price, + NMSheetColumnName.put_quoteset_mid_price, + NMSheetColumnName.quoteset_mid_price_straddle, + NMSheetColumnName.call_quoteset_mid_theo_diff, + NMSheetColumnName.put_quoteset_mid_theo_diff, + /// presaved theos + NMSheetColumnName.presave_call_theo, + NMSheetColumnName.presave_put_theo, + NMSheetColumnName.presave_call_theo_diff, + NMSheetColumnName.presave_put_theo_diff, + /// ee set edge and size + NMSheetColumnName.call_ee_set_bid_edge, + NMSheetColumnName.call_ee_set_bid_size, + NMSheetColumnName.call_ee_set_ask_edge, + NMSheetColumnName.call_ee_set_ask_size, + NMSheetColumnName.put_ee_set_bid_edge, + NMSheetColumnName.put_ee_set_bid_size, + NMSheetColumnName.put_ee_set_ask_edge, + NMSheetColumnName.put_ee_set_ask_size, + /// ee edge price + NMSheetColumnName.call_ee_bid_price, + NMSheetColumnName.call_ee_ask_price, + NMSheetColumnName.put_ee_bid_price, + NMSheetColumnName.put_ee_ask_price, + }); + + private static HashSet _empty_zero_col_map = new HashSet( + new NMSheetColumnName[] + { + /// position + NMSheetColumnName.call_position, + NMSheetColumnName.put_position, + ///market size + NMSheetColumnName.call_bid_size, + NMSheetColumnName.call_ask_size, + NMSheetColumnName.put_bid_size, + NMSheetColumnName.put_ask_size, + /// quoteset size + NMSheetColumnName.call_quoteset_resolved_bid_size, + NMSheetColumnName.call_quoteset_resolved_ask_size, + NMSheetColumnName.put_quoteset_resolved_bid_size, + NMSheetColumnName.put_quoteset_resolved_ask_size, + ///final quoteset size + NMSheetColumnName.call_quoter_set_bid_size, + NMSheetColumnName.call_quoter_set_ask_size, + NMSheetColumnName.put_quoter_set_bid_size, + NMSheetColumnName.put_quoter_set_ask_size, + ///// final quoter size + NMSheetColumnName.call_quoter_bid_size, + NMSheetColumnName.call_quoter_ask_size, + NMSheetColumnName.put_quoter_bid_size, + NMSheetColumnName.put_quoter_ask_size, + /// eye size + NMSheetColumnName.call_ee_set_bid_size, + NMSheetColumnName.call_ee_set_ask_size, + NMSheetColumnName.put_ee_set_bid_size, + NMSheetColumnName.put_ee_set_ask_size + }); + + + public NMSheetDisplayFormatter(NMSheetSettings settings) { + _cache_helper = new NMSheetFormattingCacheHelper(_real_format_value); + _tick_type_list = new BCG.Utilities.General.TickConverter2.TickType[settings.setting_column_organization.column_configuration_list.Count]; + foreach (NMSheetColumnConfiguration col in settings.setting_column_organization.column_configuration_list) + _tick_type_list[(int)col.column_name] = col.display_format; + } + + public string format_expiration(NMSheetExpiration nmsheet_exp) { + return mbts.ui.utility.ExpirationFormatter.format_symbol_expiration_standard(bts.api.SecurityType.Option, nmsheet_exp.option_name, nmsheet_exp.option_expiration, true); + } + + public string format_value(NMSheetColumnName col_name, double value) { + _n_total_calls++; + return _cache_helper.format_number(col_name, value); + } + + private int _n_total_calls = 0, _n_formatting_calls = 0; + public void start() { + _n_total_calls = _n_formatting_calls = 0; + } + + public void stop(out double hit_ratio) { + int n_cached_calls = _n_total_calls - _n_formatting_calls; + hit_ratio = 100.0 * (double)n_cached_calls / (double)Math.Max(1, _n_total_calls); + bts.Log.Ui.diag(String.Format("{0}/{1} Formatting HitRatio {2}", n_cached_calls, _n_total_calls, hit_ratio)); + } + + private string _real_format_value(NMSheetColumnName col_name, double value) { + _n_formatting_calls++; + if (Double.IsNaN(value) && _empty_nan_col_map.Contains(col_name)) + return String.Empty; + else if (value == 0.0 && _empty_zero_col_map.Contains(col_name)) + return String.Empty; + else if (col_name == NMSheetColumnName.call_delta || col_name == NMSheetColumnName.put_delta) { + value = Math.Abs(value * 100); + value = value < TC2Settings.instance.deltaRoundingThreshold ? Math.Floor(value * 10.0 + 0.5) / 10.0 : Math.Floor(value + 0.5); + } else if (col_name == NMSheetColumnName.call_gamma || col_name == NMSheetColumnName.put_gamma) + value = value * 100; + else if (col_name == NMSheetColumnName.vol || col_name == NMSheetColumnName.vol_change) + value = value * 100; + return _format_number(col_name, value); + } + + private string _format_number(NMSheetColumnName theo_type, double v) { + return BCG.Utilities.General.TickConverter2.toTick(v, _tick_type_list[(int)theo_type]); + } + } +} diff --git a/src/client/spark/NMSheets/Misc/NMSheetExpirationMapper.cs b/src/client/spark/NMSheets/Misc/NMSheetExpirationMapper.cs new file mode 100644 index 000000000..3994b61e3 --- /dev/null +++ b/src/client/spark/NMSheets/Misc/NMSheetExpirationMapper.cs @@ -0,0 +1,25 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace BCG { + /// Maps NMExpirations into placeholder expirations + /// Keeps a locked map around (instead of doing it algorithmically) + public class NMSheetExpirationMapper { + public static List filter_expirations(mbts.spark.SystemContractData contract_data, List symbol_list, List excluded_exp_list) { + List rv = new List(); + if (contract_data != null && symbol_list != null && excluded_exp_list != null) { + HashSet exluded_exp_map = new HashSet(excluded_exp_list); + foreach (NMSheetSymbol s in symbol_list) + foreach (DateTime exp in contract_data.get_option_expirations_with_strikes(s.option_name, false)) { + NMSheetExpiration nmsheet_exp = new NMSheetExpiration(s, exp); + if (!excluded_exp_list.Contains(nmsheet_exp)) + rv.Add(new NMSheetExpiration(s, exp)); + } + } + return rv; + } + } +} diff --git a/src/client/spark/NMSheets/Misc/NMSheetFixedExpStrikeDataMap.cs b/src/client/spark/NMSheets/Misc/NMSheetFixedExpStrikeDataMap.cs new file mode 100644 index 000000000..d6a568cea --- /dev/null +++ b/src/client/spark/NMSheets/Misc/NMSheetFixedExpStrikeDataMap.cs @@ -0,0 +1,79 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace BCG +{ + public class NMSheetFixedExpStrikeDataMap + { + private class MyTWrapper + { + public readonly S data; + public MyTWrapper(S the_data) { data = the_data; } + } + + private MyTWrapper[,] _data_map; + private readonly NMSheetExpiration[] _sorted_exps; + private readonly double[] _sorted_strikes; + private readonly T _def_value = default(T); + + public NMSheetFixedExpStrikeDataMap(IEnumerable sorted_exps, IEnumerable sorted_strikes) + { + _sorted_exps = sorted_exps.ToArray(); + _sorted_strikes = sorted_strikes.ToArray(); + _data_map = new MyTWrapper[sorted_exps.Count(), sorted_strikes.Count()]; + } + + public bool set_value(int exp_index, int strike_index, T data) + { + if (_within_limits(exp_index, strike_index)) + { + _data_map[exp_index, strike_index] = new MyTWrapper(data); + return true; + } + else + return false; + } + + public bool get_value(int exp_index, int strike_index, out T out_data) + { + out_data = _def_value; + if (_within_limits(exp_index, strike_index)) + { + MyTWrapper data = _data_map[exp_index, strike_index]; + if (data != null) + { + out_data = data.data; + return true; + } + else + return false; + } + else + return false; + } + + public bool contains(int exp_index, int strike_index) + { + T t; + return get_value(exp_index, strike_index, out t); + } + + public bool contains(NMSheetExpiration exp, double strike) + { + int exp_index = Array.IndexOf(_sorted_exps, exp), strike_index = Array.BinarySearch(_sorted_strikes, strike); + return contains(exp_index, strike_index); + } + + public double[] get_sorted_strikes() { return _sorted_strikes; } + + public NMSheetExpiration[] get_sorted_expirations() { return _sorted_exps; } + + private bool _within_limits(int exp_index, int strike_index) + { + return exp_index >= 0 && exp_index < _sorted_exps.Length && strike_index >= 0 && strike_index < _sorted_strikes.Length; + } + } +} diff --git a/src/client/spark/NMSheets/Misc/NMSheetFormattingCacheHelper.cs b/src/client/spark/NMSheets/Misc/NMSheetFormattingCacheHelper.cs new file mode 100644 index 000000000..e770e17ff --- /dev/null +++ b/src/client/spark/NMSheets/Misc/NMSheetFormattingCacheHelper.cs @@ -0,0 +1,76 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace BCG +{ + public class NMSheetFormattingCacheHelper + { + public delegate string FormatNumberDelegate(NMSheetColumnName value_type, double value); + private struct CacheEntry + { + public string value; + public DateTime last_access; + } + + public NMSheetFormattingCacheHelper(FormatNumberDelegate real_formatting_func) + { + _real_formatting_func = real_formatting_func; + } + + private Dictionary> _cached_data = new Dictionary>(); + private DateTime _last_clean = DateTime.Now; + private DateTime _now = DateTime.Now; + private FormatNumberDelegate _real_formatting_func; + + private void evict_old_cache_entries() + { + const int max_cache_duration_minutes = 5; + + if ((_now - _last_clean).TotalMinutes > max_cache_duration_minutes) + { + _last_clean = DateTime.Now; + foreach (var cache in _cached_data.Values) + { + List to_clean = new List(); + foreach (var kvp in cache) + { + if ((_now - kvp.Value.last_access).TotalMinutes > max_cache_duration_minutes) + to_clean.Add(kvp.Key); + } + foreach (double d in to_clean) + cache.Remove(d); + } + } + } + + UInt64 _cycle_count = 0; + public string format_number(NMSheetColumnName value_type, double v) + { + _cycle_count++; + if (_cycle_count % 10000 == 0) + _now = DateTime.Now; + evict_old_cache_entries(); + v = Math.Round(v, 4); + Dictionary val_to_string; + if (!_cached_data.TryGetValue(value_type, out val_to_string)) + { + val_to_string = new Dictionary(); + _cached_data.Add(value_type, val_to_string); + } + CacheEntry rv; + if (!val_to_string.TryGetValue(v, out rv)) + { + rv = new CacheEntry + { + value = _real_formatting_func(value_type, v), + }; + val_to_string.Add(v, rv); + } + rv.last_access = _now; + return rv.value; + } + } +} diff --git a/src/client/spark/NMSheets/NMSheetDataCoalescer.cs b/src/client/spark/NMSheets/NMSheetDataCoalescer.cs new file mode 100644 index 000000000..e2a70cfd7 --- /dev/null +++ b/src/client/spark/NMSheets/NMSheetDataCoalescer.cs @@ -0,0 +1,80 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +using mbts.tasks; + +namespace BCG { + public class NMSheetDataCoalescer : IDisposable { + private readonly object _req_id; + private readonly ThreadedBlackboard _threaded_bb; + private readonly object _in_bb_settings_tag; + + private readonly NMSheetMainDataSource _main_data_source; + private readonly NMSheetBBODataSource _bbo_data_source; + private readonly NMSheetTickerDataSource _ticker_data_source; + private readonly NMSheetPresavedTheosProvider _presaved_theos_provider; + + private bool _is_dirty = true; + private PerfStatsLogger _stats_logger = new PerfStatsLogger(); + private BCG.Utilities.General.HighPerformanceTimer _timer = new Utilities.General.HighPerformanceTimer(); + + public NMSheetDataCoalescer(ThreadedBlackboard threaded_bb, object req_id, List nmsheet_symbol_list, NMSheetSettings settings) { + _threaded_bb = threaded_bb; + _req_id = req_id; + _in_bb_settings_tag = new NMSheetTags.NMSheetSettingsTag(_req_id); + _main_data_source = new NMSheetMainDataSource(threaded_bb, req_id, nmsheet_symbol_list, () => { _is_dirty = true; }); + _bbo_data_source = new NMSheetBBODataSource(threaded_bb, nmsheet_symbol_list, () => { _is_dirty = true; }); + _ticker_data_source = new NMSheetTickerDataSource(threaded_bb, nmsheet_symbol_list, req_id, () => { _is_dirty = true; }); + _presaved_theos_provider = new NMSheetPresavedTheosProvider(threaded_bb, nmsheet_symbol_list, req_id); + //_threaded_bb.add_to_subscription_list(TaskingTags.ConsolidatedDataTag); + _threaded_bb.data_callback += _on_bb_update; + } + + private void _on_bb_update(object tag, object data) { + if (/*TaskingTags.ConsolidatedDataTag.Equals(tag) ||*/ _in_bb_settings_tag.Equals(tag)) + _is_dirty = true; + } + + public NMSheetData get_data() { + if (_is_dirty) { + _is_dirty = false; + _timer.start(); + TaskingConsolidatedData d = null;//_threaded_bb.sec_thread_retrieve_from_cache (TaskingTags.ConsolidatedDataTag) as TaskingConsolidatedData; + NMSheetData rv = new NMSheetData(_main_data_source.get_data(), _bbo_data_source.get_all_data(), _ticker_data_source.get_data(), + d ?? TaskingConsolidatedData.empty); + rv = _filter_data(rv, _threaded_bb.sec_thread_retrieve_from_cache(_in_bb_settings_tag) as NMSheetSettings); + _timer.stop(); + _stats_logger.log(String.Format("NMSheetDataCoalescer_{0}", _req_id), "NMSheetData.cons", _timer.lastIntervalTime); + return rv; + } else { + return null; + } + } + + private NMSheetData _filter_data(NMSheetData data, NMSheetSettings settings) { + NMSheetData rv = data; + if (data != null && settings != null) { + if (settings.setting_filter.filter_ee_task_strikes) + rv = rv.filter_for_strikes_in_tasks(); + if (settings.setting_filter.filter_on_ee_task_strikes) + rv = rv.filter_for_strikes_in_tasks(true); + if (settings.setting_filter.filter_positive_edge_strikes.Value) + rv = rv.filter_for_positive_edge(); + } + return rv; + } + + #region IDisposable + public void Dispose() { + _main_data_source.Dispose(); + _bbo_data_source.Dispose(); + _ticker_data_source.Dispose(); + _presaved_theos_provider.Dispose(); + _threaded_bb.data_callback -= _on_bb_update; + } + #endregion + } +} \ No newline at end of file diff --git a/src/client/spark/NMSheets/NMSheetExpiration.cs b/src/client/spark/NMSheets/NMSheetExpiration.cs new file mode 100644 index 000000000..36f15400a --- /dev/null +++ b/src/client/spark/NMSheets/NMSheetExpiration.cs @@ -0,0 +1,54 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +using bts.api; + +namespace BCG { + /// Encapulsates an expiration in the NMSheet + /// which is defined by the tuple option_exchange, + /// option_name, option_expiration + [Serializable] + public class NMSheetExpiration : IComparable { + private readonly string _to_string; + private readonly NMSheetSymbol _nmsheet_symbol; + private readonly DateTime _option_exp; + + public NMSheetExpiration(NMSheetSymbol option_symbol, DateTime the_option_expiration) + : this(option_symbol.option_exchange, option_symbol.option_name, the_option_expiration) { } + + public NMSheetExpiration(Venue the_option_exchange, string the_option_name, DateTime the_option_expiration) { + _nmsheet_symbol = new NMSheetSymbol(the_option_exchange, the_option_name); + _option_exp = the_option_expiration; + _to_string = get_display_text(); + } + + public string option_name { get { return _nmsheet_symbol.option_name; } } + public Venue option_exchange { get { return _nmsheet_symbol.option_exchange; } } + public DateTime option_expiration { get { return _option_exp; } } + public NMSheetSymbol nmsheet_symbol { get { return _nmsheet_symbol; } } + + public int CompareTo(NMSheetExpiration other) { + if (other == null) + return 1; + else { + int rv = option_expiration.Date.CompareTo(other.option_expiration.Date); + if (rv == 0) + rv = option_name.CompareTo(other.option_name); + if (rv == 0) + rv = option_exchange.CompareTo(other.option_exchange); + return rv; + } + } + + public string get_display_text() { + return mbts.ui.utility.ExpirationFormatter.format_symbol_expiration_standard(SecurityType.Option, option_name, option_expiration, true); + } + + public override string ToString() { return _to_string; } + public override int GetHashCode() { return _to_string.GetHashCode(); } + public override bool Equals(object obj) { return CompareTo(obj as NMSheetExpiration) == 0; } + } +} diff --git a/src/client/spark/NMSheets/NMSheetShellModule.cs b/src/client/spark/NMSheets/NMSheetShellModule.cs new file mode 100644 index 000000000..234a85ef5 --- /dev/null +++ b/src/client/spark/NMSheets/NMSheetShellModule.cs @@ -0,0 +1,146 @@ +// using System.Collections; +// using System.Collections.Generic; +// using System.Collections.ObjectModel; +// using System.ComponentModel.Composition; +// using System.IO; +// using System.Linq; +// using System.Threading.Tasks; +// using bts.o2.msgs; +// using mbts.ui; +// using mbts.ui.controls; +// using mbts; + +//TODO: Bring it back + +// namespace BCG { +// [Export(typeof(IShellModule))] +// public class NMSheetsShellModule : IShellModule, IAgent { +// [ImportingConstructor] +// public NMSheetsShellModule(ITimer timer, IWindowManager wm, Blackboard bb) { +// _wm = wm; +// _bb = bb; +// _launch_menu_vm = new BTSTreeViewExchangeSymbolsVM(_bb, exch => true, inst => inst == InstrumentType.Option) { +// ButtonText = "Launch Sheet", +// Command = new DelegateCommand(_ => { _launch_sheet(); _launch_menu_vm.deselect_all(); }) +// }; +// _bb.join(this); +// timer.Tick += () => { +// foreach (NMSheetShellWindow w in wm.Windows.OfType()) +// w.is_visibile = wm.IsVisible(w); +// }; +// } + +// private readonly IWindowManager _wm; +// private readonly Blackboard _bb; +// private readonly BTSTreeViewExchangeSymbolsVM _launch_menu_vm; + +// /// new sheet +// private void _launch_sheet() { +// List securities = _launch_menu_vm.get_selected_securities(); +// List converted = new List(); +// foreach (SecurityTuple security in securities) { +// SymbolExchange se = CommonGUIUtilities.convert_security_tuple(security); +// if (se != null) +// converted.Add(se); +// } +// if (converted.Count() > 0) { +// NMSheetSettings settings = _get_default_settings() ?? new NMSheetSettings() { setting_column_organization = new NMSheetSettingColumnOrganization(converted.First().symbol) }; +// settings.setting_option_list = _convert_to_o2(converted); +// settings.setting_strike_navigator = new NMSheetSettingStrikeNavigator(); +// _wm.Windows.Add(new NMSheetShellWindow(_wm, _bb, settings) { Owner = this }); +// } +// } + +// private NMSheetSettings _get_default_settings() { +// foreach (var w in _wm.Windows.Where(w => w is NMSheetShellWindow)) +// return (w as NMSheetShellWindow).get_settings().Clone() as NMSheetSettings; +// return null; +// } + +// private static List _convert_to_o2(IEnumerable symbol_exchanges) { +// List rv = new List(); +// foreach (SymbolExchange se in symbol_exchanges) { +// Venue o2_exchange; +// if (O2ExchangeTranslator.db_to_o2_name(se.exchange, out o2_exchange)) +// rv.Add(new NMSheetSymbol(o2_exchange, se.symbol)); +// } +// return rv; +// } + +// private List _quoter_ids_awaiting_symbols_for_launch = new List(); + +// #region IAgent Members + +// public void begin() { } + +// public void change(object tag) { } + +// public void commit(IDictionary changedTags) { } + +// #endregion + +// private void _launch_quotecontrol_sheet(int quoter_id, IEnumerable securities) { +// if (securities != null) { +// /// if it already exist then just bring it to the front +// IShellWindow existing_outright_win = null; +// foreach (IShellWindow w in _wm.Windows) { +// if (w != null) { +// if (w is NMSheetShellWindow) { +// NMSheetSettings w_settings = (w as NMSheetShellWindow).get_settings(); +// uint w_quoter_id; +// if (w_settings.setting_quoter.get_quoter_id(out w_quoter_id) && quoter_id == (int)w_quoter_id) { +// existing_outright_win = w; +// break; +// } +// } +// } +// } +// if (existing_outright_win != null) { +// _wm.AlertWindow(existing_outright_win); +// _wm.MakeVisible(existing_outright_win); +// } else { +// List sheet_syms = new List(); +// foreach (SecurityTuple t in securities) +// if (t.security_type == bts.o2.msgs.SecurityType.OPTION) +// sheet_syms.Add(new NMSheetSymbol(t.security_exchange, t.security_name)); + +// NMSheetSettings settings = NMSheetQuoterHelper.get_default_quoter_control_settings(quoter_id, sheet_syms); +// _wm.Windows.Add(new NMSheetShellWindow(_wm, _bb, settings) { Owner = this }); +// } +// } +// } + +// #region IShellModule Members + +// public System.Windows.Media.ImageSource icon { get { return Icons.Sheets; } } + +// public string name { get { return "Sheets"; } } + +// public int priority { get { return -1; } } + +// public IShellWindow launch_ui { get { return new BTSTreeViewLaunchMenu(_launch_menu_vm); } } + +// public void load_state(Stream state = null) { } + +// public void get_state(Stream save_here) { } + +// public void start() { } + +// public Task create(Stream load_stream) { +// NMSheetSettings nmsheet_settings = CommonGUIUtilities.deserialize_from_stream(load_stream); +// if (nmsheet_settings.setting_strike_navigator == null) +// nmsheet_settings.setting_strike_navigator = new NMSheetSettingStrikeNavigator(); +// NMSheetSettings.handle_bad_data(nmsheet_settings); +// IShellWindow w = new NMSheetShellWindow(_wm, _bb, nmsheet_settings) { Owner = this }; +// return Task.FromResult(w); +// } + +// #endregion + +// #region IDisposable Members + +// public void Dispose() { } + +// #endregion +// } +// } \ No newline at end of file diff --git a/src/client/spark/NMSheets/NMSheetShellWindow.cs b/src/client/spark/NMSheets/NMSheetShellWindow.cs new file mode 100644 index 000000000..338befb5f --- /dev/null +++ b/src/client/spark/NMSheets/NMSheetShellWindow.cs @@ -0,0 +1,119 @@ +using mbts.ui; + +using System; +using System.IO; +using System.Linq; +using System.Threading.Tasks; +using System.Windows.Media; +using mbts.ui.shell; +using System.Text.Json; + +namespace BCG { + public class NMSheetShellWindow : IShellWindow, ISlowWindow, IAgent { + private NMSheetControl _sheet_control; + private Blackboard _bb; + private string _form_title; + private bool _is_visibile; + private readonly NMSheetSettings _settings; + private readonly IWindowManager _wm; + + public NMSheetShellWindow(IWindowManager wm, Blackboard bb, NMSheetSettings settings) { + _wm = wm; + _bb = bb; + _bb.join(this); + _settings = settings; + Icon = Icons.Sheets; + _bb.write(new ResourceManagementTags.AquireTag(this), + new SymbolResourceAllocationUnit(_settings.setting_option_list.Select(s => s.to_security_tuple()), this, true)); + } + + public NMSheetSettings get_settings() { return _settings; } + + public IWindowManager get_window_manager() { return _wm; } + + public bool is_visibile { + set { _is_visibile = value; } + get { return _is_visibile; } + } + + #region IShellWindow Members + public string Title { + get { return _form_title; } + set { + _form_title = value; + if (TitleChanged != null) + TitleChanged(); + } + } + + public string window_type { + get { + return "Option Sheets"; + } + } + + public event Action TitleChanged; + + public ImageSource Icon { get; private set; } + + public event Action IconChanged = () => { }; + + public ShellWindowUI GetContent() { + _sheet_control = new NMSheetControl(_bb, this, _settings); + IntPtr ptr = _sheet_control.Handle; + return new mbts.ui.ShellWindowUI(new System.Runtime.InteropServices.HandleRef(_sheet_control, ptr)); + } + + public void GetState(Stream save_here) { + JsonSerializer.SerializeAsync(save_here, _sheet_control.get_setting()); + } + + public void Dispose() { + _sheet_control.Dispose(); + } + + private IShellModule _owner; + public IShellModule Owner { + get { return _owner; } + set { _owner = value; } + } + + public void on_shell_window_vm(ShellWindowVM shell_window_vm) { } + + + #endregion + + public void begin() { + } + + public void change(object tag) { + if (tag is TheoTags.PrecomputedOptionTheoTag) { + string option_symbol = (tag as TheoTags.PrecomputedOptionTheoTag).key; + if (_settings.setting_option_list.Select(nms => nms.option_name).Contains(option_symbol)) + FlashIcon(); + } + } + + public void commit(System.Collections.IDictionary changedTags) { + } + + async void FlashIcon() { + if (_sheet_control != null) { + var start = DateTime.Now; + bool is_green = true; + while ((DateTime.Now - start) < TimeSpan.FromSeconds(_sheet_control.get_setting().setting_alerts.vol_change_flash_seconds.Value)) { + Icon = is_green ? Icons.SheetsGreen : Icons.SheetsRed; + if (IconChanged != null) + IconChanged(); + is_green = !is_green; + await Task.Delay(500); + } + Icon = Icons.Sheets; + if (IconChanged != null) + IconChanged(); + } + } + + public void thread_init() { } + } +} diff --git a/src/client/spark/NMSheets/NMSheetSymbol.cs b/src/client/spark/NMSheets/NMSheetSymbol.cs new file mode 100644 index 000000000..32b69a372 --- /dev/null +++ b/src/client/spark/NMSheets/NMSheetSymbol.cs @@ -0,0 +1,41 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +using bts.api; + +namespace BCG { + /// Encapulsates a symbol in the NMSheet + /// which is defined by the tuple option_name, + /// option_expiration + [Serializable] + public class NMSheetSymbol : IComparable { + public readonly Venue option_exchange; + public readonly string option_name; + private readonly string _to_string; + + public NMSheetSymbol(Venue the_option_exchange, string the_option_name) { + option_exchange = the_option_exchange; + option_name = the_option_name; + _to_string = String.Format("{0}{1}", option_exchange, option_name); + } + + public int CompareTo(NMSheetSymbol other) { + if (other == null) + return 1; + else { + int rv = option_exchange.CompareTo(other.option_exchange); + return rv == 0 ? option_name.CompareTo(other.option_name) : rv; + } + } + + public mbts.SecurityTuple to_security_tuple() { return new mbts.SecurityTuple(SecurityType.Option, option_name, option_exchange); } + + public override bool Equals(object obj) { return CompareTo(obj as NMSheetSymbol) == 0; } + public override int GetHashCode() { return _to_string.GetHashCode(); } + public override string ToString() { return _to_string; } + + } +} diff --git a/src/client/spark/NMSheets/Outside/BBOPacket.cs b/src/client/spark/NMSheets/Outside/BBOPacket.cs new file mode 100644 index 000000000..b63bafcf3 --- /dev/null +++ b/src/client/spark/NMSheets/Outside/BBOPacket.cs @@ -0,0 +1,132 @@ +using mbts.analytics; + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace BCG { + public enum BidAskAlertZone { buy, sell, none } + public class BBOPacket { + public enum MarketSide { + Bid, Ask, Mid, Last + } + + private readonly double _bid_price = Double.NaN, _ask_price = Double.NaN; + private readonly UInt32 _bid_size = 0, _ask_size = 0; + private readonly UInt32 _security_key = 0; + private static BBOPacket _null_pack = new BBOPacket(VolSurfaceMDUnit.empty); + public readonly VolSurfaceMDUnit md; + + public BBOPacket(VolSurfaceMDUnit md) { + this.md = md; + } + + public static BBOPacket get_null_packet() { return _null_pack; } + + public static BidAskAlertZone theo_through_md(BBOPacket md, mbts.TheoPoint tp, bool is_call) { + if (tp != null && md != null) { + double theo = (is_call ? tp.call : tp.put), bid_price = get_bid_price(md), ask_price = get_ask_price(md); + if (!Double.IsNaN(theo)) { + if (!Double.IsNaN(bid_price)) + if (bid_price > theo) + return BidAskAlertZone.sell; + if (!Double.IsNaN(ask_price)) + if (ask_price < theo) + return BidAskAlertZone.buy; + } + } + return BidAskAlertZone.none; + } + + public static bool bid_through_theo(BBOPacket md, mbts.TheoPoint tp, bool is_call) { + return false; + // if (tp != null && md != null && md._md_row != null) + // return get_bid_price(md) > (is_call ? tp.call : tp.put); + // else + // return false; + } + + public static BidAskAlertZone get_alert_zone(BBOPacket md, mbts.TheoPoint tp, bool is_call, double cross_over) { + // if (tp != null && md != null && md._md_row != null) { + // double theo_price = is_call ? tp.call : tp.put; + // double bid_price = get_bid_price(md); + // if (bid_price + cross_over >= theo_price) + // return BidAskAlertZone.sell; + // double ask_price = get_ask_price(md); + // if (ask_price - cross_over <= theo_price) + // return BidAskAlertZone.buy; + // } + return BidAskAlertZone.none; + } + + public static BidAskAlertZone get_alert_zone(double theo_price, double bid_price, double ask_price, double cross_over) { + if (bid_price + cross_over >= theo_price) + return BidAskAlertZone.sell; + else if (ask_price - cross_over <= theo_price) + return BidAskAlertZone.buy; + else + return BidAskAlertZone.none; + } + + public static bool ask_through_theo(BBOPacket md, mbts.TheoPoint tp, bool is_call) { + // if (tp != null && md != null && md._md_row != null) + // return get_ask_price(md) < (is_call ? tp.call : tp.put); + // else + return false; + } + + public static double get_mid_price(BBOPacket md) { + return (get_bid_price(md) + get_ask_price(md)) / 2.0; + } + + public static double get_bid_price(BBOPacket md) { + return md != null ? md._bid_price : Double.NaN; + } + + public static UInt32 get_bid_size(BBOPacket md) { + return md != null ? md._bid_size : (UInt32)0; + } + + public static double get_ask_price(BBOPacket md) { + return md != null ? md._ask_price : Double.NaN; + } + + public static UInt32 get_ask_size(BBOPacket md) { + return md != null ? md._ask_size : (UInt32)0; + } + + public static UInt32 get_security_key(BBOPacket md) { + return md != null ? md._security_key : (UInt32)0; + } + + public static string get_security_exchange_desc(BBOPacket md) { + //return (md != null && md._md_row != null) ? BlueDataUtility.get_row_value(md._md_row, "security_exchange_desc", String.Empty) : String.Empty; + return String.Empty; + } + + public static string get_security_exchange_id(BBOPacket md) { + //return (md != null && md._md_row != null) ? BlueDataUtility.get_row_value(md._md_row, "security_exchange_id", String.Empty) : String.Empty; + return String.Empty; + } + + public static bool is_price_equal(BBOPacket p1, BBOPacket p2) { + if (p1 != null && p2 != null) + return get_bid_price(p1) == get_bid_price(p2) && get_ask_price(p1) == get_ask_price(p2); + else + return false; + } + + public static bool is_price_on_market(BBOPacket md, bool is_buy_side, double price) { + if (is_buy_side) { + if (!Double.IsNaN(md._bid_price) && !Double.IsNaN(price)) + return price >= md._bid_price; + } else { + if (!Double.IsNaN(md._ask_price) && !Double.IsNaN(price)) + return price <= md._ask_price; + } + return false; + } + } +} diff --git a/src/client/spark/NMSheets/Outside/Blackboard.cs b/src/client/spark/NMSheets/Outside/Blackboard.cs new file mode 100644 index 000000000..af42b410b --- /dev/null +++ b/src/client/spark/NMSheets/Outside/Blackboard.cs @@ -0,0 +1,270 @@ +using System; +using System.Collections; +using BCG.Utilities.General; + +using BCG.Utilities; +//using System.ComponentModel.Composition; +using System.Composition; + +namespace BCG { + [Export] + public class Blackboard : IBlackboard { + public Blackboard() { } + // temporary used when processing a set of changes + // do determine the complete of tags affected + // within a transaction. used as an argument to commit + private Hashtable myChangedTags = new Hashtable(); + + // all the agents attached to the blackboard + private IDictionary myAgents = new Hashtable(); + + // a map of real tags in the blackboard to MyRealTagInfo + // instances holding information about the value of a + // tag as well as all its aliases (i.e. all virtual tags + // currently mapped to it) + private IDictionary myRealTags = new Hashtable(); + + // a map from virtual tags to their currently mapped + // real tags + private IDictionary myVirtualTags = new Hashtable(); + + // used to hold information about a real tag (the + // value side of myRealTags) + private class MyRealTagInfo { + public MyRealTagInfo(object currentValue) { + this.currentValue = currentValue; + this.virtualTags = new ArrayList(); + } + + public object currentValue; + public ArrayList virtualTags = new ArrayList(); + } + + // The blackboard state determines what operations + // are illegal, what operations need to queued + // and what operations can be executed right away + enum BlackboardState { + idle, + inWrite, + inBegin, + inCommit + } + private BlackboardState myState = BlackboardState.idle; + + // temporary used for queuing nested writes in the + // middle of a write operation. + private Queue myPendingWrites = new Queue(); + + + // registering a virtual tag is an idempotent operation. + // the point of this call is, if possible, to create a + // mapping between the virtual tag and the corresponding + // real tag. since later it will be necessary to find + // out which virtual tags correspond to a real tag and + // vice-versa we maintain two maps, myVirtualTags and + // myRealTags. + public void registerVirtualTag(IVirtualTag vt) { + if (myVirtualTags.Contains(vt)) + return; // idempotency + else { + // first update the virtual tag map with + // whatever real tag (possibly none) is + // currently mapped to the virtual tag + object realTag = vt.getRealTag(null, null, this); + myVirtualTags.Add(vt, realTag); + + // now do the opposite. if a real tag mapping exists then + // add a link from the real tag to the virtual tag (creating the + // real tag if necessary) + if (realTag != null) + myFindOrCreateRealTag(realTag).virtualTags.Add(vt); + } + } + + + // returns all the tags known to Blackboard + public ICollection getAllTags() { + ArrayList result = new ArrayList(); + + result.AddRange(myRealTags.Keys); + result.AddRange(myVirtualTags.Keys); + return result; + } + + // register an agent for blackboard change notification. + public void join(IAgent agent) { myAgents[agent] = agent; } + + // unregisters an agent for blackboard change notification. + public void leave(IAgent agent) { myAgents.Remove(agent); } + + + // to obtain the value associated with a tag we first check + // if the tag is a virtual tag. if so we resolve it and + // return the value associated with the real tag. + // otherwise we assume it's a real tag and return it's value + public object read(object tag) { + object vt = myVirtualTags[tag]; + if (vt != null) + tag = vt; + + MyRealTagInfo ti = (MyRealTagInfo) + myRealTags[tag]; + if (ti != null) + return ti.currentValue; + else + return null; + } + + + // writing is complicated by reentrancy. a write often will + // trigger other writes before the first write returns. to + // deal with this we queue write reentrant write operations + // and finish one write before we proceed to the next one. + // when there are no more writes to process we handle + // any pending subscriptions and call commit + public void write(object t, object v) { + //myCheckWriteIsAllowed(); + + if (myVirtualTags.Contains(t)) { + t = myVirtualTags[t]; + if (t == null) + throw new BlackboardException("Attempting to write to an unmapped virtual tag"); + } + myFindOrCreateRealTag(t).currentValue = v; + myPendingWrites.Enqueue(new object[] { t, v }); + + if (!myState.Equals(BlackboardState.inWrite)) { + myState = BlackboardState.inBegin; + myChangedTags.Clear(); + myBeginAllAgents(); + myState = BlackboardState.inWrite; + + + while (myPendingWrites.Count > 0) { + object[] write = (object[])myPendingWrites.Dequeue(); + object tag = write[0]; + object value = write[1]; + + IDictionary totalChangedTags = + myMergeCollection( + myMergeCollection( + myMergeCollection( + new Hashtable(), + myUpdateVirtualTagMap(tag)), + ((MyRealTagInfo)myRealTags[tag]).virtualTags), + new object[] { tag }); + + + myMergeCollection(myChangedTags, totalChangedTags.Keys); + myNotifyAllAgents(totalChangedTags.Keys); + } + + myState = BlackboardState.inCommit; + myCommitAllAgents(); + myChangedTags.Clear(); + myState = BlackboardState.idle; + } + + } + + private HighPerformanceTimer _timer = new HighPerformanceTimer(); + private void myNotifyAllAgents(ICollection tags) { + IDictionary nowAgents = new Hashtable(myAgents); + + foreach (object tag in tags) + foreach (IAgent ag in nowAgents.Values) { + _timer.start(); + ag.change(tag); + _timer.stop(); + + if (_timer.lastIntervalTime > 500) { } + //mbts.Logger.log(bts.log.Level.Warn, bts.log.Subsystem.gen, String.Format("Tag: {0} for agent: {1} took: {2}", tag, ag, _timer.lastIntervalTime)); + } + } + + private void myCommitAllAgents() { + IDictionary nowAgents = new Hashtable(myAgents); + + foreach (IAgent ag in nowAgents.Values) + ag.commit(myChangedTags); + } + + public void DisposeAllAgents() { + IDictionary nowAgents = new Hashtable(myAgents); + + foreach (IAgent ag in nowAgents.Values) + if (ag is IDisposable) + ((IDisposable)ag).Dispose(); + } + + private void myBeginAllAgents() { + IDictionary nowAgents = new Hashtable(myAgents); + + foreach (IAgent ag in nowAgents.Values) + ag.begin(); + } + + private void myCheckWriteIsAllowed() { + bool assert = myState == BlackboardState.idle || myState == BlackboardState.inWrite; + if (!assert) + // BCG.Utilities.BlueEventLog.logEvent("Blackboard.myCheckWriteIsAllowed returned false", BCG.Utilities.BlueEventLevel.Error); + bts.Log.Ui.error("Blackboard.myCheckWriteIsAllowed returned false"); + // BlueEventLog.logAssert(false, "Illegal operation"); + } + + private MyRealTagInfo myFindOrCreateRealTag(object tag) { + MyRealTagInfo ti = + (MyRealTagInfo)myRealTags[tag]; + + if (ti == null) { + ti = new MyRealTagInfo(null); + myRealTags[tag] = ti; + } + return ti; + } + + ICollection myUpdateVirtualTagMap(object tagChange) { + Hashtable changedMappings = new Hashtable(); + + foreach (DictionaryEntry de in myVirtualTags) { + + IVirtualTag vt = (IVirtualTag)de.Key; + object oldRealTag = de.Value; + object newRealTag = vt.getRealTag(tagChange, oldRealTag, this); + + if (!((oldRealTag == null && newRealTag == null) + || + (oldRealTag != null && oldRealTag.Equals(newRealTag)))) { + if (oldRealTag != null) + myFindOrCreateRealTag(oldRealTag).virtualTags.Remove(vt); + + if (newRealTag != null) + myFindOrCreateRealTag(newRealTag).virtualTags.Add(vt); + + // can't change the dictionary we are iterating over... + // stupid, since the keys are not touched, bue true. + changedMappings.Add(vt, newRealTag); + } + } + + foreach (DictionaryEntry de in changedMappings) + myVirtualTags[de.Key] = de.Value; + + return changedMappings.Keys; + } + + private IDictionary myMergeCollection(IDictionary intoDictionary, ICollection collection) { + foreach (object o in collection) + if (!intoDictionary.Contains(o)) + intoDictionary.Add(o, true); + return intoDictionary; + } + + public static void safeWrite(Blackboard bb, IAgent agent, object tag, object value) { + bb.leave(agent); + bb.write(tag, value); + bb.join(agent); + } + + } +} diff --git a/src/client/spark/NMSheets/Outside/BlackboardException.cs b/src/client/spark/NMSheets/Outside/BlackboardException.cs new file mode 100644 index 000000000..d040b7e20 --- /dev/null +++ b/src/client/spark/NMSheets/Outside/BlackboardException.cs @@ -0,0 +1,14 @@ +using System; +using BCG; +using BCG.Utilities; + +namespace BCG +{ + public class BlackboardException : Exception + { + public BlackboardException(string msg) + : + base(msg) + {} + } +} diff --git a/src/client/spark/NMSheets/Outside/ClickTradeSettingsTag.cs b/src/client/spark/NMSheets/Outside/ClickTradeSettingsTag.cs new file mode 100644 index 000000000..b17f6a7e8 --- /dev/null +++ b/src/client/spark/NMSheets/Outside/ClickTradeSettingsTag.cs @@ -0,0 +1,5 @@ +using mbts.bb; + +namespace BCG { + class ClickTradeSettingsTag : EqualsHelper { } +} diff --git a/src/client/spark/NMSheets/Outside/ColorRetriever.cs b/src/client/spark/NMSheets/Outside/ColorRetriever.cs new file mode 100644 index 000000000..5931d9631 --- /dev/null +++ b/src/client/spark/NMSheets/Outside/ColorRetriever.cs @@ -0,0 +1,70 @@ +using System; +using System.Windows.Data; +using System.Reflection; +using System.Windows; +using System.Windows.Controls; +using System.Collections.Generic; +using System.Windows.Media; + +using mbts.ui; + +namespace BCG +{ + static class ColorRetriever + { + private static Dictionary _get_static_property_bag(Type t) + { + const BindingFlags flags = BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic; + var map = new Dictionary(); + foreach (var prop in t.GetProperties(flags)) + map[prop.Name] = prop.GetValue(null, null); + return map; + } + + public static Color convert_color(System.Drawing.Color o_color) + { + return Color.FromArgb(o_color.A, o_color.R, o_color.G, o_color.B); + } + + public static System.Drawing.Color convert_color(Color o_color) + { + return System.Drawing.Color.FromArgb(o_color.A, o_color.R, o_color.G, o_color.B); + } + + public static System.Drawing.Color convert_color(BTSColor o_color) + { + return (System.Drawing.Color) o_color; + } + + public static Color clone_color(Color color) + { + return new Color() { A = color.A, B = color.B, G = color.G, R = color.R }; + } + + public static System.Drawing.Color clone_color(System.Drawing.Color color) + { + if (color.IsNamedColor) + return System.Drawing.Color.FromName(color.Name); + else + return System.Drawing.Color.FromArgb(color.A, color.R, color.G, color.B); + } + private static List> all_colors; + + public static List> get_all_colors() + { + if (all_colors == null) + { + all_colors = new List>(); + var colors = _get_static_property_bag(typeof(Colors)); + + foreach (KeyValuePair colorPair in colors) + { + Color color = (Color)colorPair.Value; + all_colors.Add(new Pair(color, colorPair.Key)); + } + } + return all_colors; + } + + } +} diff --git a/src/client/spark/NMSheets/Outside/CommonGUIUtilities.cs b/src/client/spark/NMSheets/Outside/CommonGUIUtilities.cs new file mode 100644 index 000000000..2e14e2965 --- /dev/null +++ b/src/client/spark/NMSheets/Outside/CommonGUIUtilities.cs @@ -0,0 +1,382 @@ +using System; +using System.IO; +using System.Text.Json; + + +namespace BCG { + public class CommonGUIUtilities { + public const string delta_str = "\x394", gamma_str = "\x393", vega_str = "V", theta_str = "\x398"; + + public static bool ctrl_is_pressed { get { return System.Windows.Input.Keyboard.IsKeyDown(System.Windows.Input.Key.RightCtrl) || System.Windows.Input.Keyboard.IsKeyDown(System.Windows.Input.Key.LeftCtrl); } } + public static bool shift_is_pressed { get { return System.Windows.Input.Keyboard.IsKeyDown(System.Windows.Input.Key.RightShift) || System.Windows.Input.Keyboard.IsKeyDown(System.Windows.Input.Key.LeftShift); } } + + // public static bts.o2.msgs.Exchange.type get_exchange(IBlueRow row, string exchange_col) { + // return get_exchange(BlueDataUtility.get_row_value(row, exchange_col, string.Empty)); + // } + + // public static bts.o2.msgs.Exchange.type get_exchange(string exchange_str) { + // bts.o2.msgs.Exchange.type exch; + // if (Enum.TryParse(exchange_str, out exch)) + // return exch; + // return O2ExchangeTranslator.db_to_o2_name(exchange_str, bts.o2.msgs.Exchange.type.UNSET); + // } + + // public static mbts.SecurityTuple get_security(IBlueRow row, string type_col, string sym_col, string exch_col) { + // string sym = BlueDataUtility.get_row_value(row, sym_col, string.Empty); + // bts.o2.msgs.SecurityType.type type = BlueDataUtility.get_row_enum_value(row, type_col, bts.o2.msgs.SecurityType.type.UNSET); + // bts.o2.msgs.Exchange.type exch = get_exchange(row, exch_col); + // return new mbts.SecurityTuple(type, sym, exch); + // } + + // public static mbts.SecurityTuple get_security(IBlueRow row, bts.o2.msgs.SecurityType.type type, string sym_col, string exch_col) { + // string sym = BlueDataUtility.get_row_value(row, sym_col, string.Empty); + // bts.o2.msgs.Exchange.type exch = get_exchange(row, exch_col); + // return new mbts.SecurityTuple(type, sym, exch); + // } + + // public static T deserialize_from_bytes(byte[] byte_arr) + // { + // MemoryStream str = new MemoryStream(byte_arr); + // str.Position = 0; + // return deserialize_from_stream(str); + // } + + // public static T deserialize_from_file(string full_file_name) { + // return deserialize_from_stream(new FileStream(full_file_name, FileMode.Open, FileAccess.Read)); + // } + + // public static T deserialize_from_stream(Stream stream) { + // T result; + // if (!try_deserialize_from_stream(stream, out result)) { + // Logger.log(Level.Error, Subsystem.ui, "Failed to deserialize {0} data from stream, attempted to deserialize as bin and proto".fmt(typeof(T).FullName)); + // System.Reflection.ConstructorInfo ci = typeof(T).GetConstructor(new Type[] { }); + // if (ci != null) + // result = (T)ci.Invoke(null); + // else + // result = default(T); + // } + // return result; + // } + + // public static bool try_deserialize_from_stream(Stream stream, out T result) { + // try { + // BinaryFormatter bf = new BinaryFormatter(); + // result = (T)bf.Deserialize(stream); + // stream.Close(); + // return true; + // } + // catch { } + // stream.Position = 0; + // if (ProtoBufSerializationHelper.try_deserialize(stream, out result)) + // return true; + // System.Reflection.ConstructorInfo ci = typeof(T).GetConstructor(new Type[] { }); + // if (ci != null) + // result = (T)ci.Invoke(null); + // else + // result = default(T); + // return false; + // } + + // //to be called from shellWindow's get_state fn + // public static bool serialize_to_stream(Stream save_here, object obj) + // { + // if (obj != null) + // { + // try + // { + // System.Runtime.Serialization.Formatters.Binary.BinaryFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); + // formatter.Serialize(save_here, obj); + // return true; + // } + // catch (Exception ex) { mbts.Logger.log(bts.log.Level.Warn, bts.log.Subsystem.gen, String.Format("Failed to serialize {0} to stream: {1}", obj.GetType().ToString(), ex.Message)); } + // } + // return false; + // } + + // public static IEnumerable get_selection(MultiSelectDropDown dropdown_box, out bool all_selected, Func convert = null) + // { + // all_selected = dropdown_box.IsAllSelected; + // List rv = new List(); + // if (convert != null) + // { + // foreach (object o in dropdown_box.SelectedItems) { + // rv.Add(convert(o)); + // } + // } + // else + // { + // // strings and enums + // foreach (object o in dropdown_box.SelectedItems) + // { + // if (typeof(T).IsEnum && o is string) + // { + // rv.Add((T)Enum.Parse(typeof(T), (string)o)); + // } + // else + // { + // rv.Add((T)Convert.ChangeType(o, typeof(T))); + // } + // } + // } + // return rv; + // } + + // public static T[] get_selection(MultiSelectDropDown dropdown_box, out bool all_selected) + // { + // return get_selection(dropdown_box, out all_selected, null).ToArray(); + // } + + // public static T[] get_selection(MultiSelectDropDown dropdown_box) + // { + // bool all_selected; + // return get_selection(dropdown_box, out all_selected); + // } + + // public static IEnumerable get_empty_selection_if_all_selected(MultiSelectDropDown dropdown_box, Func convert = null) + // { + // bool all_selected = false; + // IEnumerable selected_multiselect_items = get_selection(dropdown_box, out all_selected, convert); + // return all_selected ? new List() { } : selected_multiselect_items; + // } + + // public static List get_selected_security_expirations_from_display_expiration(MultiSelectDropDown dropdown_box, IDictionary display_to_real_exp_map) + // { + // List rv = new List(); + // foreach (string display_exp in get_selection(dropdown_box)) + // { + // mbts.SecurityExpiration sec_exp; + // if (display_to_real_exp_map.TryGetValue(display_exp, out sec_exp)) + // rv.Add(sec_exp); + // } + // return rv; + // } + + // public static DateTime[] get_datetimes_from_selected_exps(MultiSelectDropDown dropdown_box, IDictionary display_to_real_exp_map) + // { + // return get_selected_security_expirations_from_display_expiration(dropdown_box, display_to_real_exp_map).Select(d => d.expiration).ToArray(); + // } + + public static T basic_deep_clone(T obj) { + try { + string json_txt = JsonSerializer.Serialize(obj); + var rv = JsonSerializer.Deserialize(json_txt); + return rv; + } catch { + return default(T); + } + } + + public static T clone_protobuf(T protobuf_obj) { + try { + MemoryStream ms = new MemoryStream(); + ProtoBuf.Serializer.SerializeWithLengthPrefix(ms, protobuf_obj, ProtoBuf.PrefixStyle.Fixed32); + ms.Position = 0; + T rv = ProtoBuf.Serializer.DeserializeWithLengthPrefix(ms, ProtoBuf.PrefixStyle.Fixed32); + return rv; + } catch { + return default(T); + } + } + + // /// Populates multi_selection_dropdown with all_item_list, + // /// and sets selected_item_list as selected items. + // /// If selected_item_list is null, then all items + // /// are selected. + // public static void set_multi_selection_control_items(MultiSelectDropDown multi_selection_dropdown, IEnumerable all_item_list, IEnumerable selected_item_list, bool sort_items = true) + // { + // multi_selection_dropdown.IsAllSelected = false; + // List all_item_sorted_list = all_item_list == null ? new List() : new List(all_item_list); + // if (sort_items) + // all_item_sorted_list.Sort(); + // HashSet selected_item_map = new HashSet(selected_item_list == null ? all_item_sorted_list : selected_item_list); + // multi_selection_dropdown.Items.Clear(); + // multi_selection_dropdown.SelectedItems.Clear(); + // foreach (T t in all_item_sorted_list) + // multi_selection_dropdown.Items.Add(t); + // foreach (T t in all_item_sorted_list) + // if (selected_item_map.Contains(t)) + // multi_selection_dropdown.SelectedItems.Add(t); + // } + + // public static void set_multi_selection_control_items(MultiSelectDropDown multi_selection_dropdown, IEnumerable items) + // { + // System.Collections.Generic.HashSet curr_item_map = new HashSet(); + // foreach (object o in multi_selection_dropdown.Items) + // curr_item_map.Add(o); + // System.Collections.Generic.HashSet new_item_map = new HashSet(items.Select(t => (object)t)); + // if (!CollectionHelpers.hashset_equals(curr_item_map, new_item_map)) + // { + // /// finds out the unselected items + // Dictionary unselected_items_map = new Dictionary(); + // foreach (object o in multi_selection_dropdown.Items) + // if (!multi_selection_dropdown.SelectedItems.Contains(o)) + // unselected_items_map[o] = true; + // /// adds only the non unselected items to the + // /// list of selected items. new items, hence + // /// are selected by default + // multi_selection_dropdown.Items.Clear(); + // multi_selection_dropdown.SelectedItems.Clear(); + // List items_list = new List(items); + // items_list.Sort(); + // foreach (T t in items_list) + // { + // multi_selection_dropdown.Items.Add(t); + // if (!unselected_items_map.ContainsKey(t)) + // multi_selection_dropdown.SelectedItems.Add(t); + // } + // } + // } + + // public static string append_multiple_filters(bool is_or, params string[] filter_expressions) + // { + // string rv = String.Empty; + // foreach (string f in filter_expressions) + // { + // if (!String.IsNullOrEmpty(f)) + // { + // string prepend = String.IsNullOrEmpty(rv) ? String.Empty : (is_or ? " or " : " and "); + // rv += prepend + String.Format("{0}{1}{2}", "(", f, ")"); + // } + // } + // return rv; + // } + + // public static string get_stream_column_filter(string col_name, System.Collections.ICollection values, string comparison_op = "=") + // { + // if (values == null || values.Count == 0) + // return String.Empty; + // else + // { + // string rv = String.Empty; + // foreach (object v in values) + // { + // if (v != null) + // { + // string prepend = String.IsNullOrEmpty(rv) ? String.Empty : (" or "); + // string value_wrapper = v is String ? "'" : String.Empty; + // rv += prepend + String.Format("{0}{1}{2}{3}{4}", col_name, comparison_op, value_wrapper, v, value_wrapper); + // } + // } + // return rv; + // } + // } + + // public static string[] get_exp_strings(DateTime[] exps) + // { + // if (exps == null) + // return new string[] { }; + // else + // { + // string[] rv = new string[exps.Length]; + // for (int i = 0; i < exps.Length; i++) + // rv[i] = exps[i].ToShortDateString(); + // return rv; + // } + // } + + // public static bool parse_textbox_regularexp(System.Windows.Forms.TextBox tb, System.Drawing.Color normal_color, System.Drawing.Color error_color, string error_value, out string out_value) + // { + // out_value = tb.Text; + // tb.ForeColor = normal_color; + // try { System.Text.RegularExpressions.Regex r = new System.Text.RegularExpressions.Regex(out_value); } + // catch (Exception) + // { + // mbts.Logger.log(bts.log.Level.Warn, bts.log.Subsystem.ui, String.Format("Illegal regular expression {0} in security filter", out_value)); + // tb.ForeColor = error_color; + // out_value = String.Empty; + // return false; + // } + // return true; + // } + + // public static bool parse_textbox_text(System.Windows.Forms.TextBox tb, System.Drawing.Color normal_color, System.Drawing.Color error_color, T error_value, out T out_t) + // { + // try + // { + // if (!String.IsNullOrEmpty(tb.Text)) + // { + // out_t = (T)Convert.ChangeType(tb.Text, typeof(T)); + // tb.ForeColor = normal_color; + // return true; + // } + // else + // { + // out_t = error_value; + // tb.ForeColor = normal_color; + // return false; + // } + // } + // catch (Exception) + // { + // out_t = error_value; + // tb.ForeColor = error_color; + // return false; + // } + // } + + public static System.Drawing.Font change_font_size(System.Drawing.Font orig_font, float size_change, float floor, float ceil) { + float new_size = Math.Min(Math.Max(orig_font.Size + size_change, floor), ceil); + return new System.Drawing.Font(orig_font.FontFamily, new_size, orig_font.Style); + } + + // public static void remove_items_from_menu_dropdown(ToolStripMenuItem menu_item, Func remove_func) + // { + // List to_be_rem = new List (); + // foreach (ToolStripItem i in menu_item.DropDownItems) + // if (remove_func(i)) + // to_be_rem.Add(i); + // foreach (ToolStripItem i in to_be_rem) + // menu_item.DropDownItems.Remove(i); + // } + + // /// If a mouse is clicked at a point and + // /// dragged, this adjusts the rectangle + // /// for negative movements + // public static Rectangle get_selected_rectangle(Point start_pos, Size dp) + // { + // int left = start_pos.X, width = dp.Width; + // if (dp.Width < 0) + // { + // left = Math.Max(0, start_pos.X + dp.Width); + // width = start_pos.X - left; + // } + // int top = start_pos.Y, height = dp.Height; + // if (dp.Height < 0) + // { + // top = Math.Max(0, top + dp.Height); + // } + // return new Rectangle(new Point(left, top), new Size(width, Math.Abs(dp.Height))); + // } + + // /// Returns the real expirations from a dropdown + // /// showing mapped expiration + // public static DateTime[] get_selected_exps_from_mapped_control(MultiSelectDropDown dropdown_control, IDictionary display_to_real_exp_map) + // { + // bool all_selected; + // DateTime[] selected_display_exps = CommonGUIUtilities.get_selection(dropdown_control, out all_selected); + // selected_display_exps = all_selected ? new DateTime[] { } : selected_display_exps; + // List rv = new List(); + // foreach (DateTime display_exp in selected_display_exps) + // { + // DateTime real_exp; + // if (display_to_real_exp_map.TryGetValue(display_exp, out real_exp)) + // rv.Add(real_exp); + // } + // return rv.ToArray(); + // } + + // public static SymbolExchange convert_security_tuple(SecurityTuple security) { + // InstrumentType type; + // if (Enum.TryParse(security.security_type.ToString(), true, out type)) + // return new SymbolExchange(security.security_name, type, security.security_exchange.ToString()); + // return null; + // } + + + // public static bool min_max_filter(double v, double min, double max, bool pass_nan_for_value = false) + // { + // return (Double.IsNaN(min) ? true : (Double.IsNaN(v) ? pass_nan_for_value : v >= min)) && + // (Double.IsNaN(max) ? true : (Double.IsNaN(v) ? pass_nan_for_value : v <= max)); + // } + } +} diff --git a/src/client/spark/NMSheets/Outside/ContractTags.cs b/src/client/spark/NMSheets/Outside/ContractTags.cs new file mode 100644 index 000000000..be880cc8c --- /dev/null +++ b/src/client/spark/NMSheets/Outside/ContractTags.cs @@ -0,0 +1,13 @@ +using bts.api; + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace BCG { + public class ContractTags { + public class SystemContractsTag : mbts.bb.EqualsHelper { } + } +} diff --git a/src/client/spark/NMSheets/Outside/ElectronicTradingTask.cs b/src/client/spark/NMSheets/Outside/ElectronicTradingTask.cs new file mode 100644 index 000000000..87cbdb415 --- /dev/null +++ b/src/client/spark/NMSheets/Outside/ElectronicTradingTask.cs @@ -0,0 +1,58 @@ +using ProtoBuf; + +using System; + +namespace mbts.tasks { + [ProtoContract(Name = "ElectronicTradingTask")] + [Serializable] + public class ElectronicTradingTask { + [ProtoBuf.ProtoMember(10)] + public readonly TaskCommon common = null; + [ProtoBuf.ProtoMember(20)] + public readonly ExplicitTask explicit_task = null; + [ProtoBuf.ProtoMember(30)] + public readonly ImplicitTask implicit_task = null; + + private ElectronicTradingTask() { } + + public ElectronicTradingTask(TaskCommon common, ExplicitTask task) { + // Logger.assert(common != null); + // Logger.assert(task != null); + this.common = common; + this.explicit_task = task; + this.implicit_task = null; + } + public ElectronicTradingTask(TaskCommon common, ImplicitTask task) { + // Logger.assert(common != null); + // Logger.assert(task != null); + this.common = common; + this.explicit_task = null; + this.implicit_task = task; + } + + public ElectronicTradingTask with(TaskCommon common) { + return explicit_task == null ? + new ElectronicTradingTask(common, implicit_task) : + new ElectronicTradingTask(common, explicit_task); + } + public ElectronicTradingTask with(TaskCommon common = null, ExplicitTask explicit_task = null) { + return new ElectronicTradingTask(common ?? this.common, explicit_task ?? this.explicit_task); + } + public ElectronicTradingTask with(TaskCommon common = null, ImplicitTask implicit_task = null) { + return new ElectronicTradingTask(common ?? this.common, explicit_task ?? this.explicit_task); + } + public override string ToString() { + return common.id; + } + } + + public class QuickStartElectronicTradingTask { + private readonly ElectronicTradingTask _task; + public QuickStartElectronicTradingTask(TaskCommon common, ExplicitTask task) { + _task = new ElectronicTradingTask(common, task); + } + public static implicit operator ElectronicTradingTask(QuickStartElectronicTradingTask task) { + return task._task; + } + } +} diff --git a/src/client/spark/NMSheets/Outside/EqualsHelper.cs b/src/client/spark/NMSheets/Outside/EqualsHelper.cs new file mode 100644 index 000000000..83a628006 --- /dev/null +++ b/src/client/spark/NMSheets/Outside/EqualsHelper.cs @@ -0,0 +1,29 @@ +using bts.api; + +using System; + +namespace mbts.bb { + public interface ITag { } + [Serializable] + public class EqualsHelper : ITag { + public override bool Equals(object obj) { return obj != null && obj.GetType().Equals(this.GetType()); } + + public override int GetHashCode() { return this.GetType().GetHashCode(); } + } + + public class IDBaseTag : EqualsHelper { + public IDBaseTag() { + id = Guid.NewGuid(); + } + + public IDBaseTag(Guid id) { + this.id = id; + } + + public readonly Guid id; + + public override bool Equals(object obj) { return base.Equals(obj) && ((IDBaseTag)obj).id.Equals(id); } + + public override int GetHashCode() { return id.GetHashCode(); } + } +} diff --git a/src/client/spark/NMSheets/Outside/ExchangeSecurityMap.cs b/src/client/spark/NMSheets/Outside/ExchangeSecurityMap.cs new file mode 100644 index 000000000..7cb2d9973 --- /dev/null +++ b/src/client/spark/NMSheets/Outside/ExchangeSecurityMap.cs @@ -0,0 +1,108 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +using bts.api; + +namespace BCG { + /// + /// This is the list of all exchange listed securities + /// in the system. It provides : + /// 1. Direct list of securities + /// 2. Reverse look up from options to their security keys + /// + // TODO: SystemSecurityData will replace this + public class ExchangeSecurityMap/* : mbts.bb.IExchangeSecurityMap */{ + public const uint error_key = 0; + private readonly IDictionary _key_sec_map; + private readonly IDictionary _option_map; + private readonly IDictionary _fut_map; + private readonly IDictionary> _spread_map; + + public ExchangeSecurityMap(IDictionary key_sec_map, + IDictionary option_map, + IDictionary fut_map, + IDictionary> spread_map) { + _key_sec_map = key_sec_map; + _option_map = option_map; + _fut_map = fut_map; + _spread_map = spread_map; + } + + #region IExchangeSecurityMap + public Security get_option_security(Venue exchange, string symbol, DateTime exp, + double strike, PutOrCall cp) { + mbts.SecurityStrike k = new mbts.SecurityStrike(new mbts.SecurityExpiration(exchange, SecurityType.Option, symbol, exp), strike); + Security[] rv = _option_map.TryGetValue(k, out rv) ? rv : null; + return rv != null ? rv[cp == PutOrCall.Call ? 0 : 1] : null; + } + + public Security get_future_security(Venue exchange, string symbol, DateTime exp) { + mbts.SecurityExpiration sec_exp = new mbts.SecurityExpiration(exchange, SecurityType.Future, symbol, exp); + Security rv = _fut_map.TryGetValue(sec_exp, out rv) ? rv : null; + return rv; + } + + public Security get_spread_security(Venue exchange, string spread_def) { + IDictionary exch_spread_map; + Security rv = null; + if (_spread_map.TryGetValue(exchange, out exch_spread_map)) + if (exch_spread_map.TryGetValue(spread_def, out rv)) + return rv; + return null; + } + + // public IEnumerable> get_future_expirations() { + // return _fut_map.Select(e => Tuple.Create(e.Key.exchange, e.Key.symbol, e.Key.expiration, e.Key)); + // } + + public IEnumerable> get_stocks() { return new List>(); } + + public Security get_o2_security(uint sec_key) { + Security rv = _key_sec_map.TryGetValue(sec_key, out rv) ? rv : null; + return rv; + } + + #endregion + + /// Given an ExpStrikeKeyedData it attaches + /// the call and put security keys + public ExpStrikeKeyedData> attach_sec_keys(ExpStrikeKeyedData data, string option_name, Venue exchange) { + ExpStrikeKeyedData> rv = new ExpStrikeKeyedData>(); + uint[] uninit_keys = new uint[] { 0, 0 }; + foreach (Triplet t in data.get_data_linearly()) { + mbts.SecurityStrike k = new mbts.SecurityStrike(new mbts.SecurityExpiration(exchange, SecurityType.Option, option_name, t.first), t.second); + Security[] cp_keys = _option_map.TryGetValue(k, out cp_keys) ? cp_keys : null; + uint c_key = cp_keys != null && cp_keys[0] != null ? cp_keys[0].Id : 0, + p_key = cp_keys != null && cp_keys[1] != null ? cp_keys[1].Id : 0; + rv.set_data(t.first, t.second, new Triplet(t.third, c_key, p_key)); + } + return rv; + } + + // private static DateTime _exp(T t) { + // return new DateTime((int)t.ExpirationYear, (int)t.ExpirationMonth, (int)t.ExpirationDay); + // } + + public Security fill_partial_security(Security s) { + if (s.security_type() == SecurityType.Option && s.Option != null) + return get_option_security(s.Exchange, s.Symbol, new DateTime((int)s.Option.ExpirationYear, (int)s.Option.ExpirationMonth, (int)s.Option.ExpirationDay), s.Option.Strike, s.Option.CallPut); + else if (s.security_type() == SecurityType.Future && s.Future != null) + return get_future_security(s.Exchange, s.Symbol, new DateTime((int)s.Future.ExpirationYear, (int)s.Future.ExpirationMonth, (int)s.Future.ExpirationDay)); + else if (s.security_type() == SecurityType.Spread && s.Spread != null) + return get_spread_security(s.Exchange, s.SecurityName()); + return null; + } + + public IEnumerable get_matching_option_securities(string symbol, Venue exchange) { + List rv = new List(); + foreach (var v in _option_map.Where(kv => String.Compare(kv.Key.expiration.symbol, symbol, true) == 0).Select(kv => kv.Value)) { + rv.Add(v[0]); + rv.Add(v[1]); + } + return rv; + } + } +} \ No newline at end of file diff --git a/src/client/spark/NMSheets/Outside/ExpStrikeKeyedData.cs b/src/client/spark/NMSheets/Outside/ExpStrikeKeyedData.cs new file mode 100644 index 000000000..7f6017cc0 --- /dev/null +++ b/src/client/spark/NMSheets/Outside/ExpStrikeKeyedData.cs @@ -0,0 +1,186 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace BCG +{ + /// + /// just a conveniant way to store exp,K based data + /// + /// + public class ExpStrikeKeyedData + { + public delegate T CreateT(DateTime exp, double strike); + + private IDictionary> _map = new Dictionary>(); + + public ExpStrikeKeyedData() { } + + public ExpStrikeKeyedData(ExpStrikeKeyedData data) + { + foreach (KeyValuePair> p in data._map) + _map[p.Key] = new Dictionary(p.Value); + } + + public ExpStrikeKeyedData(ICollection> exp_strikes, CreateT del) + { + foreach (Pair p in exp_strikes) + set_data(p.first, p.second, del(p.first, p.second)); + } + + #region Mutators + public void set_data(DateTime exp, double strike, T t) + { + IDictionary strike_vs_t_map = null; + if (!_map.TryGetValue(exp, out strike_vs_t_map)) + { + strike_vs_t_map = new Dictionary(); + _map.Add(exp, strike_vs_t_map); + } + strike_vs_t_map[strike] = t; + } + + public void set_data_for_expiration(DateTime expiration, IDictionary strike_data) + { + _map[expiration] = strike_data; + } + + public void clear() { _map.Clear(); } + + public bool delete_data(DateTime exp, double strike) + { + IDictionary strike_vs_t_map = null; + if (_map.TryGetValue(exp, out strike_vs_t_map)) + return strike_vs_t_map.Remove(strike); + return false; + } + #endregion + + #region Accessors + public T get_data(DateTime exp, double strike) + { + IDictionary strike_vs_t_map = null; + if (_map.TryGetValue(exp, out strike_vs_t_map)) + { + T rv; + if (strike_vs_t_map.TryGetValue(strike, out rv)) + return rv; + } + return default(T); + } + + public bool contains(DateTime exp, double strike) + { + IDictionary strike_vs_t_map = null; + return _map.TryGetValue(exp, out strike_vs_t_map) && strike_vs_t_map.ContainsKey(strike); + } + + public List get_strike_list_for_expiration(DateTime expiration) + { + List rv = new List(); + IDictionary exp_map = null; + if (_map.TryGetValue(expiration, out exp_map)) + rv = new List(exp_map.Keys); + return rv; + } + + public T get_random_data_for_exp(DateTime option_expiration) + { + IDictionary exp_data = null; + if (_map.TryGetValue(option_expiration, out exp_data)) + foreach (T t in exp_data.Values) + return t; + return default(T); + } + + public DateTime[] get_expirations() + { + return new List(_map.Keys).ToArray(); + } + + public double[] get_strikes() + { + Dictionary strikes = new Dictionary(); + foreach (Pair p in get_expstrike_pairs()) + if (!strikes.ContainsKey(p.second)) + strikes.Add(p.second, true); + double[] rv = new double[strikes.Count]; + strikes.Keys.CopyTo(rv, 0); + return rv; + } + + public ICollection> get_expstrike_pairs() + { + List> rv = new List>(); + foreach (KeyValuePair> kv1 in _map) + { + DateTime exp = kv1.Key; + foreach (KeyValuePair kv2 in kv1.Value) + rv.Add(new Pair(exp, kv2.Key)); + } + return rv; + } + + public ICollection> get_data_linearly () + { + List> rv = new List>(); + foreach (KeyValuePair> kv1 in _map) + { + DateTime exp = kv1.Key; + foreach (KeyValuePair kv2 in kv1.Value) + rv.Add(new Triplet(exp, kv2.Key, kv2.Value)); + } + return rv; + } + + public ExpStrikeKeyedData clone_filtered_set(HashSet filtered_expirations, bool is_exp_inclusive, + HashSet filtered_strikes, bool is_strike_inclusive) + { + ExpStrikeKeyedData rv = new ExpStrikeKeyedData(); + foreach (KeyValuePair> ep in _map) + if ((is_exp_inclusive && filtered_expirations.Contains(ep.Key)) || (!is_exp_inclusive && !filtered_expirations.Contains(ep.Key))) + foreach (KeyValuePair kp in ep.Value) + if ((is_strike_inclusive && filtered_strikes.Contains(kp.Key)) || (!is_strike_inclusive && !filtered_strikes.Contains(kp.Key))) + rv.set_data(ep.Key, kp.Key, kp.Value); + return rv; + } + + public IDictionary get_data_for_single_exp(DateTime exp) + { + IDictionary rv = null; + _map.TryGetValue(exp, out rv); + return rv; + } + + public IReadOnlyDictionary> get_full_data() + { + IDictionary> rv = _map.ToDictionary(kv => kv.Key, kv => (IReadOnlyDictionary)kv.Value); + return (IReadOnlyDictionary>)rv; + } + + public int count + { + get + { + int count = 0; + foreach (Dictionary exp_map in _map.Values) + count += exp_map.Count; + return count; + } + } + #endregion + + #region Cloning + + public ExpStrikeKeyedData clone_conversion(Func convert) + { + ExpStrikeKeyedData rv = new ExpStrikeKeyedData(); + foreach (var t in get_data_linearly()) + rv.set_data(t.first, t.second, convert(t.first, t.second, t.third)); + return rv; + } + + #endregion + } +} diff --git a/src/client/spark/NMSheets/Outside/ExpirationFormatter.cs b/src/client/spark/NMSheets/Outside/ExpirationFormatter.cs new file mode 100644 index 000000000..0461b45e8 --- /dev/null +++ b/src/client/spark/NMSheets/Outside/ExpirationFormatter.cs @@ -0,0 +1,140 @@ +using System; +using System.Collections.Generic; + +using bts.api; + +namespace mbts.ui.utility { + public class ExpirationFormatter { + private static class DateFormatter { + private static string[] month_codes = new string[] { "F", "G", "H", "J", "K", "M", "N", "Q", "U", "V", "X", "Z" }; + private static string[] month_three_letters = new string[] { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }; + + public static string format_condensed(DateTime date, bool use_month_code, bool show_year) { + return String.Format("{0}{1}{2}", date.Day, month_codes[date.Month - 1], show_year ? (date.Year - 2000).ToString() : String.Empty); + } + + public static string format(DateTime date, bool use_month_code, bool show_day) { + string month_text = use_month_code ? "{0}{1:00}".fmt(month_codes[date.Month - 1], date.Year - 2000) : "{0} {1:00}".fmt(month_three_letters[date.Month - 1], date.Year - 2000); + return show_day ? "{0} {1}".fmt(date.Day, month_text) : month_text; + } + + public static string format_standard(DateTime date) { return "{0} {1} {2:00}".fmt(date.Day, month_three_letters[date.Month - 1], date.Year - 2000); } + public static string format_coded(DateTime date) { return "{0} {1}{2:00}".fmt(date.Day, month_codes[date.Month - 1], date.Year - 2000); } + public static string format_coded_hide_day(DateTime date) { return "{0}{1}".fmt(month_codes[date.Month - 1], date.Year - 2000); } + + public static DateTime parse_standard(string date_text) { + string[] split = date_text.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); + int year = 0; + int month = Array.IndexOf(month_three_letters, split[1]) + 1; + int day = 0; + int.TryParse(split[2], out year); + int.TryParse(split[0], out day); + return new DateTime(year + 2000, month, day); + } + + public static DateTime parse_coded(string date_text) { + string[] split = date_text.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); + string year_text = split[1].Substring(1); + string month_text = split[1].Substring(0, 1); + string day_text = split[0]; + int month = Array.IndexOf(month_codes, month_text) + 1; + int day, year; + int.TryParse(year_text, out year); + int.TryParse(day_text, out day); + return new DateTime(year + 2000, month, day); + } + + public static DateTime parse_coded_hide_day(string date_text) { + string year_text = date_text.Substring(1); + string month_text = date_text.Substring(0, 1); + int month = Array.IndexOf(month_codes, month_text) + 1; + int year; + int.TryParse(year_text, out year); + return new DateTime(year + 2000, month, 0); + } + } + + //private static IDictionary> _offset_map; + + static ExpirationFormatter() { + // try { + // _offset_map = new Dictionary>(); + // _offset_map[SecurityType.OPTION] = new Dictionary(); + // _offset_map[SecurityType.FUTURE] = new Dictionary(); + + // bts.config.ExpirationDisplayOffset offset_list = mbts.config.Configuration.get(); + // foreach (bts.config.ExpirationDisplayOffsetEntry e in offset_list.entries) { + // string security_name = e.security_name; + // string security_type_text = e.security_type; + // bts.o2.msgs.SecurityType security_type = bts.o2.msgs.SecurityType.UNSET; + // Enum.TryParse(security_type_text, true, out security_type); + // if (security_type == bts.o2.msgs.SecurityType.OPTION || security_type == bts.o2.msgs.SecurityType.FUTURE) + // _offset_map[security_type][security_name] = e; + // } + // } catch (Exception ex) { + // mbts.Logger.log(bts.log.Level.Error, bts.log.Subsystem.ui, String.Format("Exception message = {0}", ex.Message)); + // } + } + + // private static bts.config.ExpirationDisplayOffsetEntry _get_offset_entry(bts.o2.msgs.SecurityType security_type, string security_name) { + // bts.config.ExpirationDisplayOffsetEntry rv = null; + // IDictionary this_security_type_map = null; + // if (_offset_map.TryGetValue(security_type, out this_security_type_map)) + // if (this_security_type_map.TryGetValue(security_name, out rv)) + // return rv; + // return rv; + // } + + public static DateTime convert_real_to_mapped(SecurityType security_type, string security_name, DateTime security_expiration) { + return security_expiration; + // bts.config.ExpirationDisplayOffsetEntry offset_entry = _get_offset_entry(security_type, security_name); + // DateTime rv = security_expiration; + // if (offset_entry != null) { + // if (offset_entry.addition_type == bts.config.ExpirationOffsetType.type.Month) + // rv = security_expiration.AddMonths(offset_entry.addition_count); + // else if (offset_entry.addition_type == bts.config.ExpirationOffsetType.type.MonthMoveToStart) { + // rv = security_expiration.AddMonths(offset_entry.addition_count); + // rv = new DateTime(rv.Year, rv.Month, 1); + // } + // } + // return rv; + } + + public static string format_expiration_standard(SecurityType security_type, string security_name, DateTime security_expiration, bool map_expiration) { + return format_expiration_standard(security_type, security_name, security_expiration, map_expiration, false); + } + + public static string format_expiration_standard(SecurityType security_type, string security_name, DateTime security_expiration, bool map_expiration, bool use_month_code) { + return format_expiration_standard(security_type, security_name, security_expiration, map_expiration, use_month_code, true); + } + + public static string format_expiration_standard(SecurityType security_type, string security_name, DateTime security_expiration, bool map_expiration, bool use_month_code, bool show_day) { + DateTime mapped_expiration = map_expiration ? convert_real_to_mapped(security_type, security_name, security_expiration) : security_expiration; + return DateFormatter.format(mapped_expiration, use_month_code, show_day); + } + + public static string format_symbol_expiration_standard(SecurityType security_type, string security_name, DateTime security_expiration, bool map_expiration) { + return format_symbol_expiration_standard(security_type, security_name, security_expiration, map_expiration, false, false, true); + } + + public static string format_symbol_expiration_standard(SecurityType security_type, string security_name, DateTime security_expiration, bool map_expiration, bool show_security_type) { + return format_symbol_expiration_standard(security_type, security_name, security_expiration, map_expiration, show_security_type, false, true); + } + + public static string format_symbol_expiration_standard(SecurityType security_type, string security_name, DateTime security_expiration, bool map_expiration, bool show_security_type, bool use_month_code) { + return format_symbol_expiration_standard(security_type, security_name, security_expiration, map_expiration, show_security_type, use_month_code, true); + } + + public static string format_symbol_expiration_standard(SecurityType security_type, string security_name, DateTime security_expiration, bool map_expiration, bool show_security_type, bool use_month_code, bool show_day) { + string exp_text = format_expiration_standard(security_type, security_name, security_expiration, map_expiration, use_month_code, show_day); + return !show_security_type ? String.Format("{0} {1}", security_name, exp_text) : String.Format("{0} {1} {2}", security_type.ToString().ToUpper(), security_name, exp_text); + } + + public static string format_option_expiration_condensed(string option_name, DateTime option_expiration, bool map_expiration, bool show_symbol_name, bool show_year) { + DateTime mapped_expiration = map_expiration ? convert_real_to_mapped(SecurityType.Option, option_name, option_expiration) : option_expiration; + return String.Format("{0}{1}", show_symbol_name ? option_name : String.Empty, DateFormatter.format_condensed(mapped_expiration, true, show_year)); + } + + public static DateTime parse_standard_formatted_expiration(SecurityType security_type, string security_name, string security_expiration) { return DateFormatter.parse_standard(security_expiration); } + } +} diff --git a/src/client/spark/NMSheets/Outside/ExplicitTask.cs b/src/client/spark/NMSheets/Outside/ExplicitTask.cs new file mode 100644 index 000000000..d95b47dbc --- /dev/null +++ b/src/client/spark/NMSheets/Outside/ExplicitTask.cs @@ -0,0 +1,33 @@ +using ProtoBuf; + +using System; +using System.Collections.Generic; +using System.Linq; + +using security_key = System.UInt32; + +namespace mbts.tasks { + [Serializable] + [ProtoContract(Name = "ExplicitTask")] + //[RecordType] + public class ExplicitTask { + private ExplicitTask() { /*for protobuf*/ } + + [ProtoMember(20)] + public readonly List securities; + [ProtoMember(30)] + public readonly List security_descriptions; + + public ExplicitTask(IEnumerable secs, IEnumerable security_desc) { + securities = secs.ToList(); + security_descriptions = security_desc.ToList(); + //Logger.assert(securities.Count() == security_descriptions.Count()); + } + + public static ExplicitTask Default { get { return new ExplicitTask(new uint[0], new string[0]); } } + + public ExplicitTask with(IEnumerable securities = null, IEnumerable security_descriptions = null) { + return new ExplicitTask(securities ?? this.securities, security_descriptions ?? this.security_descriptions); + } + } +} diff --git a/src/client/spark/NMSheets/Outside/HighPerformanceTimer.cs b/src/client/spark/NMSheets/Outside/HighPerformanceTimer.cs new file mode 100644 index 000000000..5e731ac53 --- /dev/null +++ b/src/client/spark/NMSheets/Outside/HighPerformanceTimer.cs @@ -0,0 +1,119 @@ +using System; +using System.Runtime.InteropServices; + +namespace BCG.Utilities.General +{ + /// + /// Provides a timer, much more accurate than using timers based on System.DateTime. It does not accumulate time, as the + /// stress was on small time intervals. + /// + public class HighPerformanceTimer + { + [DllImport("kernel32.dll")] + public extern static short QueryPerformanceCounter(ref long x); + [DllImport("kernel32.dll")] + public extern static short QueryPerformanceFrequency(ref long x); + + private long myStartCount = 0, myEndCount = 0, myFreq = 0, myTotalCount = 0; + private long myZeroTime; + /// + /// This a static instance that can be shared across a running process. + /// The only member function that is thread-safe right now + /// is 'runningMilliseconds' + /// + public readonly static HighPerformanceTimer sharedTimer = new HighPerformanceTimer (); + + + public HighPerformanceTimer() + { + QueryPerformanceFrequency(ref myFreq); + if (myFreq == 0) + throw new ApplicationException ("High resolution timers not supported by this machine's hardware"); + QueryPerformanceCounter(ref myZeroTime); + } + /// + /// starts measuring the time + /// + public void start() + { + QueryPerformanceCounter (ref myStartCount); + } + + public double runningMilliseconds() + { + double rv = 0; + lock (this) + { + long t = 0; + QueryPerformanceCounter (ref t); + rv = (t - myZeroTime) * 1000.0 / myFreq; + } + return rv; + } + + public double toMilliseconds(long count) + { + lock (this) + return count * 1000.0 / myFreq; + } + public double getRunningMilliseconds (long count) + { + double rv = 0; + lock (this) + { + rv = (count - myZeroTime) * 1000.0 / myFreq; + } + return rv; + } + + public long nowCount + { + get + { + long t = 0; + QueryPerformanceCounter (ref t); + return t; + } + } + + /// + /// stops recording time + /// + public void stop() + { + QueryPerformanceCounter (ref myEndCount); + myTotalCount += myEndCount - myStartCount; + } + + /// + /// total milliseconds, ie aggregated time of all intervals + /// + public double totalMilliseconds {get{return myTotalCount * 1000.0 / myFreq ; }} + + public double getMilliseconds (long count) + { + return count * 1000.0 / myFreq; + } + + public long ticks {get{return myEndCount - myStartCount;}} + + /// + /// time between the last start-stop + /// + public double lastIntervalTime {get{return (myEndCount - myStartCount) * 1000.0 / myFreq ; }} + + /// + /// Resets the running time + /// + public void reset () + { + QueryPerformanceCounter(ref myZeroTime); + myTotalCount = 0; + } + + public long freq + { + get { return myFreq; } + } + } +} diff --git a/src/client/spark/NMSheets/Outside/IAgent.cs b/src/client/spark/NMSheets/Outside/IAgent.cs new file mode 100644 index 000000000..83bfbd872 --- /dev/null +++ b/src/client/spark/NMSheets/Outside/IAgent.cs @@ -0,0 +1,14 @@ +using System; +using System.Collections; + +using BCG; + +namespace BCG +{ + public interface IAgent + { + void begin(); + void change(object tag); + void commit(IDictionary changedTags); + } +} \ No newline at end of file diff --git a/src/client/spark/NMSheets/Outside/IBlackboard.cs b/src/client/spark/NMSheets/Outside/IBlackboard.cs new file mode 100644 index 000000000..5c86bf6d3 --- /dev/null +++ b/src/client/spark/NMSheets/Outside/IBlackboard.cs @@ -0,0 +1,260 @@ +using mbts; + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using System.Windows.Threading; + +namespace BCG { + public interface IBlackboard { + void join(IAgent agent); + void leave(IAgent agent); + + object read(object tag); + void write(object tag, object data); + } + + // public interface IThreadedBlackboard : IBlackboard, IDisposable { + // void sec_thread_dowork(); + // void safe_write(object tag, object data); + // } + + // public class ThreadedBBWrapper : IThreadedBlackboard { + // private readonly ThreadedBlackboard _bb; + // private readonly HashSet _agent_map = new HashSet(), _agents_awaiting_join = new HashSet(), _agents_awaiting_leave = new HashSet(); + + // public ThreadedBBWrapper(ThreadedBlackboard bb) { + // _bb = bb; + // _bb.add_to_subscription_list(t => true); + // _bb.data_callback += _on_data; + // } + + // private readonly int _thread_id = Thread.CurrentThread.ManagedThreadId; + // //private readonly SynchronizationContext _context = Thread.CurrentContext; + + // private bool _suspend_agents = false; + + // private void _assert_sec_thread_consistency() { Logger.assert(Thread.CurrentThread.ManagedThreadId == _thread_id); } + + // private void _on_data(object t, object d) { + // //unless someone has broken ThreadedBlackboard, it is guarenteed that this is the appropriate thread + // _suspend_agents = true; + // foreach (IAgent a in _agent_map) + // a.change(t); + // _agent_map.removeRange(_agents_awaiting_leave); + // _agents_awaiting_leave.Clear(); + // _agent_map.AddRange(_agents_awaiting_join); + // _agents_awaiting_join.Clear(); + // _suspend_agents = false; + // } + + // #region IBlackboard + // public void join(IAgent agent) { + // _assert_sec_thread_consistency(); + // if (_suspend_agents) + // _agents_awaiting_join.Add(agent); + // else + // _agent_map.Add(agent); + // } + + // public void leave(IAgent agent) { + // _assert_sec_thread_consistency(); + // if (_suspend_agents) + // _agents_awaiting_leave.Add(agent); + // else + // _agent_map.Remove(agent); + // } + + // public object read(object tag) { return _bb.sec_thread_retrieve_from_cache(tag); } + + // public void write(object tag, object data) { _bb.sec_thread_write(tag, data); } + + // private delegate void Write(object tag, object data); + + // private IList> _safe_write_queue = new List>(); + + // public void safe_write(object tag, object data) { + // lock (_safe_write_queue) + // _safe_write_queue.Add(Tuple.Create(tag, data)); + // } + // #endregion + + // public void sec_thread_dowork() { + // IList> temp = null; + // lock (_safe_write_queue) { + // temp = _safe_write_queue.ToList(); + // _safe_write_queue.Clear(); + // } + // temp.ForEach(tup => write(tup.Item1, tup.Item2)); + // _bb.sec_thread_dowork(); + // } + + // public void Dispose() { + // _bb.data_callback -= _on_data; + // _bb.sec_thread_dispose(); + // } + // } + + // public class BBSub { + // public BBSub(object tag, Action callback) { + // this.tag = tag; + // this.callback = callback; + // } + // public object tag { get; private set; } + // public Action callback { get; private set; } + // } + + // public static class IBlackboardExtensions { + // public static T read(this IBlackboard b, object tag) { + // var result = b.read(tag); + // return result != null ? (T)result : default(T); + // } + + // public static T read(this bts.api.IBus b, bts.api.ITag tag) { + // var sub = b.subscribe(tag); + // var subprime = sub as bts.api.Subscription; + // if (subprime != null && subprime.has_value) { + // return subprime.value; + // } + // return default(T); + // } + + // private class BlackboardAwaiter : IAgent { + // private readonly object _tag; + // private readonly IBlackboard _bb; + // private readonly TaskCompletionSource _completion_source; + + // public BlackboardAwaiter(IBlackboard bb, object tag) { + // _completion_source = new TaskCompletionSource(); + // var result = bb.read(tag); + // if (result != null) + // _completion_source.TrySetResult((T)result); + // else { + // _bb = bb; + // _tag = tag; + // bb.join(this); + // } + // } + + // public void begin() { } + // public void change(object tag) { + // if (tag.Equals(_tag)) { + // _bb.leave(this); + // _completion_source.TrySetResult((T)_bb.read(tag)); + // } + // } + // public void commit(IDictionary changedTags) { } + + // public Task task { get { return _completion_source.Task; } } + // } + + // public static Task read_next(this IBlackboard bb, object tag) { + // var temp = new BlackboardAwaiter(bb, tag); + // return temp.task; + // } + + // private class BlackboardProxyAgent : IAgent, IDisposable { + // private readonly IBlackboard _bb; + // private readonly IDictionary> _callback; + // public BlackboardProxyAgent(IBlackboard bb, params BBSub[] subs) { + // _bb = bb; + // _callback = subs.ToDictionary(s => s.tag, s => s.callback); + // subs.ForEach(s => { + // object o = _bb.read(s.tag); + // if (o != null) + // s.callback(o); + // }); + // _bb.join(this); + // } + + // public void Dispose() { + // _bb.leave(this); + // } + + // public void begin() { } + // public void commit(IDictionary changedTags) { } + + // public void change(object tag) { + // Action cb; + // if (_callback.TryGetValue(tag, out cb)) + // cb(_bb.read(tag)); + // } + // } + + // private class BlackboardProxyAgent : IAgent, IDisposable { + // public BlackboardProxyAgent(IBlackboard bb, object tag, Action callback) { + // _tag = tag; + // _callback = callback; + // _bb = bb; + // change(tag); + // _bb.join(this); + // } + + // private readonly IBlackboard _bb; + // private readonly object _tag; + // private readonly Action _callback; + + // public void begin() { } + // public void change(object tag) { + // if (tag.Equals(_tag)) { + // object data = _bb.read(tag); + // if (data is TData) + // _callback((TData)data); + // } + // } + // public void commit(IDictionary changedTags) { } + + // public void Dispose() { + // if (_bb != null) + // _bb.leave(this); + // } + // } + + // private class BlackbaordProxyAgent : IAgent, IDisposable { + // public BlackbaordProxyAgent(IBlackboard bb, Action callback) { + // _callback = callback; + // _bb = bb; + // _bb.join(this); + // } + + // private readonly IBlackboard _bb; + // private readonly Action _callback; + + // public void begin() { } + // public void change(object tag) { + // if (tag is TTag) { + // object data = _bb.read(tag); + // if (data is TData) + // _callback((TTag)tag, (TData)data); + // } + // } + // public void commit(IDictionary changedTags) { } + + // public void Dispose() { + // if (_bb != null) + // _bb.leave(this); + // } + // } + + // public static IDisposable subscribe(this IBlackboard bb, object tag, Action callback) { + // return new BlackboardProxyAgent(bb, tag, callback); + // } + + // [Obsolete] + // public static IDisposable subscribe(this IBlackboard bb, Action callback) { + // return new BlackbaordProxyAgent(bb, callback); + // } + + // [Obsolete] + // public static IDisposable subscribe(this IBlackboard bb, Action callback) { + // return bb.subscribe(new Action((t, d) => callback(d))); + // } + + // public static IDisposable subscribe(this IBlackboard bb, params BBSub[] subscriptions) { + // return new BlackboardProxyAgent(bb, subscriptions); + // } + // } +} diff --git a/src/client/spark/NMSheets/Outside/IVirtualTag.cs b/src/client/spark/NMSheets/Outside/IVirtualTag.cs new file mode 100644 index 000000000..207afe6f2 --- /dev/null +++ b/src/client/spark/NMSheets/Outside/IVirtualTag.cs @@ -0,0 +1,11 @@ +using System; +using BCG; +using BCG.Utilities; + +namespace BCG +{ + public interface IVirtualTag + { + object getRealTag(object changedTagHint, object oldValue, Blackboard bb); + } +} diff --git a/src/client/spark/NMSheets/Outside/IWorker.cs b/src/client/spark/NMSheets/Outside/IWorker.cs new file mode 100644 index 000000000..10f46dc30 --- /dev/null +++ b/src/client/spark/NMSheets/Outside/IWorker.cs @@ -0,0 +1,9 @@ +using System; + +namespace BCG.Utilities.General +{ + public interface IWorker + { + void doWork(); + } +} diff --git a/src/client/spark/NMSheets/Outside/ImplicitTask.cs b/src/client/spark/NMSheets/Outside/ImplicitTask.cs new file mode 100644 index 000000000..a91fce1e4 --- /dev/null +++ b/src/client/spark/NMSheets/Outside/ImplicitTask.cs @@ -0,0 +1,79 @@ +using ProtoBuf; + +using System; +using System.Collections.Generic; +using System.Linq; +using bts.api; + +using security_key = System.UInt32; + +namespace mbts.tasks { + [Serializable] + //[RecordType] + [ProtoContract(ImplicitFields = ImplicitFields.AllPublic)] + public class ImplicitTask { + public ImplicitTask( + SecurityType security_type, + Venue exchange, + IEnumerable selected_symbols, + IEnumerable selected_expirations, + IEnumerable filters, + PutOrCall call_put) { + this.security_type = security_type; + this.exchange = exchange; + this.selected_symbols = (selected_symbols ?? new string[0]).ToList(); + this.selected_expirations = (selected_expirations ?? new DateTime[0]).ToList(); + this.filters = (filters ?? new SavedTaskFilter[0]).ToList(); + this.call_put = call_put; + } + private ImplicitTask() { /*for protobuf*/ } + + public static ImplicitTask Default { + get { + return new ImplicitTask( + SecurityType.Option, Venue.Glbx, new string[0], new DateTime[0], new SavedTaskFilter[0], PutOrCall.Call); + } + } + public ImplicitTask with( + SecurityType? security_type = null, + Venue? exchange = null, + IEnumerable selected_symbols = null, + IEnumerable selected_expirations = null, + IEnumerable filters = null, + PutOrCall? call_put = null) { + return new ImplicitTask( + security_type ?? this.security_type, + exchange ?? this.exchange, + selected_symbols ?? this.selected_symbols, + selected_expirations ?? this.selected_expirations, + filters ?? this.filters, + call_put ?? this.call_put); + } + + public readonly SecurityType security_type; + public readonly Venue exchange; + public readonly List selected_symbols; + public readonly List selected_expirations; + public readonly List filters; + public readonly PutOrCall call_put; + } + + [ProtoContract] + //[RecordType] + public class SavedTaskFilter { + [ProtoMember(10)] + public readonly TaskSecurityFilterType type; + [ProtoMember(20)] + public readonly double min; + [ProtoMember(30)] + public readonly double max; + + private SavedTaskFilter() { /*for protobuf*/ } + + public SavedTaskFilter(TaskSecurityFilterType type, double min, double max) { + this.type = type; + this.min = min; + this.max = max; + } + } +} \ No newline at end of file diff --git a/src/client/spark/NMSheets/Outside/InternalTags.cs b/src/client/spark/NMSheets/Outside/InternalTags.cs new file mode 100644 index 000000000..b706168af --- /dev/null +++ b/src/client/spark/NMSheets/Outside/InternalTags.cs @@ -0,0 +1,20 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace BCG +{ + public class InternalTags + { + public class PNLOperationTags + { + public class PNLRollOverTag : mbts.bb.EqualsHelper { } + + public class PNLRollBackTag : mbts.bb.EqualsHelper { } + + public class PNLRequestCompletionTag : mbts.bb.EqualsHelper { } + } + } +} diff --git a/src/client/spark/NMSheets/Outside/MarketDataTags.cs b/src/client/spark/NMSheets/Outside/MarketDataTags.cs new file mode 100644 index 000000000..c8f53c98d --- /dev/null +++ b/src/client/spark/NMSheets/Outside/MarketDataTags.cs @@ -0,0 +1,19 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace BCG +{ + public class MarketDataTags + { + public class OptionDriverBBOTag : KeyedTag { public OptionDriverBBOTag(string option_name) : base(option_name) { } } + + public class OptionDriverDetailedBBOTag : KeyedTag { public OptionDriverDetailedBBOTag(string option_name) : base(option_name) { } } + + public class OptionDriverSymbolBBOTag : KeyedTag { public OptionDriverSymbolBBOTag(string option_name) : base(option_name) { } } + + public class DriverDailySettlementPriceTag : mbts.bb.EqualsHelper { public DriverDailySettlementPriceTag() { } } + } +} \ No newline at end of file diff --git a/src/client/spark/NMSheets/Outside/MasterWorker.cs b/src/client/spark/NMSheets/Outside/MasterWorker.cs new file mode 100644 index 000000000..3f70d8532 --- /dev/null +++ b/src/client/spark/NMSheets/Outside/MasterWorker.cs @@ -0,0 +1,147 @@ +using System; +using System.Collections.Generic; +using System.Text; +using BCG.Utilities.General; +using System.Threading; +using BCG.Utilities; + +namespace BCG { + public class MasterWorker : IWorker { + + private DateTime myLastDoWorkTime = DateTime.MinValue, + myLastLogTime = DateTime.MinValue; + protected TimeSpan myPeriod = new TimeSpan(0, 0, 0, 0, 100), + myLogPeriod = new TimeSpan(0, 1, 0); + protected Dictionary> myWorkers = new Dictionary>(), + myJustAdded = new Dictionary>(), + myJustRemoved = new Dictionary>(); + private HighPerformanceTimer myTimer = new HighPerformanceTimer(); + private static MasterWorker //myThreadDriven = null, + myDoWorkDriven = null; + internal MasterWorker() { + myInit(); + } + + protected virtual void myInit() { } + + public static MasterWorker getInstance(bool threadDriven) { + lock (typeof(MasterWorker)) { + // if (threadDriven) { + // myThreadDriven = myThreadDriven ?? new ThreadDrivenMasterWorker(); + // return myThreadDriven; + // } else { + // TODO + myDoWorkDriven = myDoWorkDriven ?? new MasterWorker(); + return myDoWorkDriven; + //} + } + } + + public virtual void addWorker(IWorker worker, TimeSpan period) { + // BlueEventLog.logEvent(String.Format("MasterWorker : adding worker {0} with period {1} , worker count before adding this = {2}", + // worker.ToString(), period.ToString(), myWorkers.Count), + // PS3LogLevels.connection); + + myJustAdded.Add(worker, new Pair(period, DateTime.UtcNow)); + } + + public virtual void removeWorker(IWorker worker) { + // BlueEventLog.logEvent(String.Format("MasterWorker : removing worker {0} , worker count before removing this = {1}", + // worker.ToString(), myWorkers.Count), + // PS3LogLevels.disconnection); + + myJustRemoved.Add(worker, null); + } + + public virtual void doWork() { + + foreach (KeyValuePair> p in myJustAdded) { + myWorkers.Add(p.Key, p.Value); + } + foreach (KeyValuePair> p in myJustRemoved) { + myWorkers.Remove(p.Key); + } + myJustAdded.Clear(); + myJustRemoved.Clear(); + if (DateTime.UtcNow - myLastDoWorkTime >= myPeriod) { + myTimer.start(); + //myLogEntries(); + myLastDoWorkTime = DateTime.UtcNow; + foreach (KeyValuePair> p in myWorkers) { + if (DateTime.UtcNow - p.Value.second >= p.Value.first) { + p.Key.doWork(); + p.Value.second = DateTime.UtcNow; + } + } + myTimer.stop(); + if (myTimer.lastIntervalTime > 100) { + //BlueEventLog.logEvent(String.Format("{0} : took {1} msecs", GetType().ToString(), myTimer.lastIntervalTime), PS3LogLevels.performance); + } + } + + } + + protected virtual void myLogEntries() { + if (DateTime.UtcNow - myLastLogTime > myLogPeriod) { + myLastLogTime = DateTime.UtcNow; + } + } + + } + + //class ThreadDrivenMasterWorker : MasterWorker + //{ + // private Timer myTimer; + // internal ThreadDrivenMasterWorker() + // : base() + // { } + + // protected override void myInit() + // { + // myTimer = new Timer(new TimerCallback(myDoWork), null, myPeriod, myPeriod); + // } + + // public override void addWorker(IWorker worker, TimeSpan period) + // { + // ///to avoid re-entrance, its added to a temporay dictionary, + // ///and will be moved over to the main one, in the doWork + // lock (this) + // { + // myJustAdded.Add(worker, new Pair(period, DateTime.UtcNow)); + // } + // } + + // public override void removeWorker(IWorker worker) + // { + // ///same as addWorker, added to a temporary store, before moving + // ///it to the main one, in the next doWork + // lock (this) + // { + // myJustRemoved.Add(worker, null); + // } + // } + + // private void myDoWork(object args) + // { + // lock (this) + // { + // foreach (IWorker w in myJustRemoved.Keys) + // { + // BlueEventLog.logEvent(String.Format("ThreadDrivenMasterWorker : removing worker {0} , worker count before removing this = {1}", + // w.ToString(), myWorkers.Count), PS3LogLevels.connection); + // myWorkers.Remove(w); + // } + // foreach (KeyValuePair> p in myJustAdded) + // { + // BlueEventLog.logEvent(String.Format("ThreadDrivenMasterWorker : adding worker {0} , worker count before adding this = {1}", + // p.Key.ToString(), myWorkers.Count), PS3LogLevels.connection); + // myWorkers.Add(p.Key, p.Value); + // } + // myJustRemoved.Clear(); + // myJustAdded.Clear(); + // } + // doWork(); + // } + + //} +} \ No newline at end of file diff --git a/src/client/spark/NMSheets/Outside/OptionContract.cs b/src/client/spark/NMSheets/Outside/OptionContract.cs new file mode 100644 index 000000000..e85b96673 --- /dev/null +++ b/src/client/spark/NMSheets/Outside/OptionContract.cs @@ -0,0 +1,53 @@ +using System; + +using BCG; +using BCG.Utilities; + +using bts.api; + +namespace BCG { + /// + /// Serves as the contract information (ie no calculated data, theos, deltas etc) for one leg of + /// the spread + /// + public class OptionContract { + public OptionContract(Venue this_exchange, + string this_symbol, + DateTime this_expiration, + double this_strike, + bool this_iscall) { + exchange = this_exchange; + product = this_symbol; + expiration = this_expiration; + strike = this_strike; + isCall = this_iscall; + } + + public override bool Equals(object obj) { + if (obj == null || !(obj is OptionContract)) + return false; + + OptionContract oc = (OptionContract)obj; + return + oc.product.Equals(product) && + oc.expiration.Equals(expiration) && + oc.strike.Equals(strike) && + oc.isCall.Equals(isCall); + } + + public override int GetHashCode() { + return ToString().GetHashCode(); + } + + public readonly Venue exchange; + public readonly string product; + public readonly DateTime expiration; + public readonly double strike; + public readonly bool isCall; + + public override string ToString() { + return String.Format("{0},{1},{2},{3}", product, expiration.ToLongDateString(), strike, isCall ? "C" : "P"); + } + + } +} diff --git a/src/client/spark/NMSheets/Outside/OptionContractKeyedData.cs b/src/client/spark/NMSheets/Outside/OptionContractKeyedData.cs new file mode 100644 index 000000000..105bae844 --- /dev/null +++ b/src/client/spark/NMSheets/Outside/OptionContractKeyedData.cs @@ -0,0 +1,149 @@ + +using System; +using System.Collections.Generic; +using System.Text; + +namespace BCG +{ + public class CallPutValue + { + public T call_value; + public T put_value; + public void set_value(bool is_call, T t) + { + if (is_call) call_value = t; + else put_value = t; + } + public T get_value(bool is_call) {return is_call ? call_value : put_value;} + public bool value_exists(bool is_call) + { + T v = get_value(is_call); + return v != null && !v.Equals(default(T)); + } + public void remove_value (bool is_call) {set_value (is_call, default(T));} + + public CallPutValue shallow_copy () + { + return new CallPutValue() { call_value = call_value, put_value = put_value }; + } + } + + public class OptionContractKeyedData + { + private Dictionary>> _map = new Dictionary>>(); + public OptionContractKeyedData() {} + + public IReadOnlyDictionary>> get_data() + { + Dictionary>> rv = new Dictionary>>(); + foreach (DateTime exp in _map.Keys) + rv[exp] = get_exp_data(exp); + return rv; + } + + public void setValue(DateTime e, double k, bool is_call, T data) + { + Dictionary> k_map = null; + if (!_map.TryGetValue(e, out k_map)) + _map.Add(e, k_map = new Dictionary>()); + CallPutValue k_val = null; + if (!k_map.TryGetValue(k, out k_val)) + k_map.Add(k, k_val = new CallPutValue()); + k_val.set_value(is_call, data); + } + + public T getValue(DateTime e, double k, bool is_call) + { + Dictionary> k_map = null; + CallPutValue k_val = null; + if (_map.TryGetValue(e, out k_map)) + if (k_map.TryGetValue(k, out k_val)) + return k_val.get_value(is_call); + return default(T); + } + + public T get_value(DateTime e, double k, bool is_call, T not_found_val) + { + Dictionary> k_map = null; + CallPutValue k_val = null; + if (_map.TryGetValue(e, out k_map)) + if (k_map.TryGetValue(k, out k_val)) + return k_val.get_value(is_call); + return not_found_val; + } + + public void remove(DateTime e, double k, bool is_call) + { + Dictionary> k_map = null; + CallPutValue k_val = null; + if (_map.TryGetValue(e, out k_map)) + if (k_map.TryGetValue(k, out k_val)) + k_val.remove_value(is_call); + } + + public bool contains (DateTime e, double k, bool is_call) + { + Dictionary> k_map = null; + CallPutValue k_val = null; + if (_map.TryGetValue(e, out k_map)) + if (k_map.TryGetValue(k, out k_val)) + return k_val.value_exists(is_call); + return false; + } + + public bool contain_exp(DateTime e) + { + Dictionary> k_map; + return _map.TryGetValue(e, out k_map) && k_map != null && k_map.Count > 0; + } + + public List>> get_linear_data () + { + List>> rv = new List>>(); + foreach (KeyValuePair>> kv1 in _map) + { + DateTime e = kv1.Key; + foreach (KeyValuePair> kv2 in kv1.Value) + rv.Add(new Triplet>(e, kv2.Key, kv2.Value)); + } + return rv; + } + + public IReadOnlyDictionary> get_exp_data(DateTime exp) + { + Dictionary> exp_map = null; + return _map.TryGetValue(exp, out exp_map) ? exp_map : new Dictionary>(); + } + + public OptionContractKeyedData shallow_copy () + { + Dictionary>> rv = new Dictionary>> (); + foreach (KeyValuePair>> kv1 in _map) + { + Dictionary> k_map = new Dictionary>(); + foreach (KeyValuePair> kv2 in kv1.Value) + k_map.Add(kv2.Key, kv2.Value.shallow_copy()); + rv.Add(kv1.Key, k_map); + } + return new OptionContractKeyedData() { _map = rv }; + } + + public void mutate_data(Action mutate_func) + { + foreach (Dictionary> k_map in _map.Values) + foreach (CallPutValue kp_val in k_map.Values) + { + mutate_func(kp_val.call_value); + mutate_func(kp_val.put_value); + } + } + + public IDictionary> get_contracts() + { + Dictionary> rv = new Dictionary>(); + foreach (KeyValuePair>> k in _map) + rv.Add(k.Key, k.Value.Keys); + return rv; + } + } +} diff --git a/src/client/spark/NMSheets/Outside/PNLRollOverDataUnit.cs b/src/client/spark/NMSheets/Outside/PNLRollOverDataUnit.cs new file mode 100644 index 000000000..61ee56ccd --- /dev/null +++ b/src/client/spark/NMSheets/Outside/PNLRollOverDataUnit.cs @@ -0,0 +1,19 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace BCG +{ + public class PNLRollOverDataUnit + { + public readonly double vol, driver, theo; + + public PNLRollOverDataUnit(double vol, double driver, double theo) + { + this.vol = vol; + this.driver = driver; + this.theo = theo; + } + } +} diff --git a/src/client/spark/NMSheets/Outside/Pair.cs b/src/client/spark/NMSheets/Outside/Pair.cs new file mode 100644 index 000000000..1552333d2 --- /dev/null +++ b/src/client/spark/NMSheets/Outside/Pair.cs @@ -0,0 +1,89 @@ +using System; +using System.Collections.Generic; +using System.IO; + +namespace BCG +{ + /// + /// Just like the C++ pair template + /// + /// + /// + [Serializable] + public class Pair + { + public F first; + public S second; + + public Pair() { } + public Pair(F f, S s) + { + first = f; + second = s; + } + + public Pair(KeyValuePair kvp) + : this (kvp.Key, kvp.Value) + {} + + public override string ToString() + { + return String.Format("{0},{1}", first != null ? first.ToString() : "NULL", + second != null ? second.ToString() : "NULL"); + } + + public override int GetHashCode() + { + return ToString().GetHashCode(); + } + + public override bool Equals(object obj) + { + return obj != null && obj is Pair && ToString() == obj.ToString(); + } + + } + + public static class Pair + { + public static Pair Create(F a, S b) { + return new Pair(a, b); + } + } + + [Serializable] + public class Triplet + { + public F first; + public S second; + public T third; + + public Triplet() { } + + public Triplet(F f, S s, T t) + { + first = f; + second = s; + third = t; + } + + public static Triplet from_tuple(Tuple t) { return new Triplet(t.Item1, t.Item2, t.Item3); } + + public override string ToString() + { + return String.Format("{0},{1},{2}", first != null ? first.ToString() : "NULL", + second != null ? second.ToString() : "NULL", + third != null ? third.ToString() : "NULL"); + } + + public override bool Equals(object obj) + { + return obj != null && obj is Triplet && ToString() == obj.ToString(); + } + + public override int GetHashCode() + { + return ToString().GetHashCode(); + } + } +} \ No newline at end of file diff --git a/src/client/spark/NMSheets/Outside/PintoValueRounder.cs b/src/client/spark/NMSheets/Outside/PintoValueRounder.cs new file mode 100644 index 000000000..111a5aa83 --- /dev/null +++ b/src/client/spark/NMSheets/Outside/PintoValueRounder.cs @@ -0,0 +1,77 @@ +using System; +using System.Diagnostics; +using System.Collections; +using BCG.Utilities; +using BCG.Utilities.General; + +namespace BCG +{ + /// + /// Proprietary Rounding Algorithm by Pedro Pinto, Blue Capital Group, LLC. + /// + public class PintoValueRounder + { + private double myValue; + private int myDecimalPlaces; + public PintoValueRounder(double value, int decimalPlaces) + { + myValue = value; + myDecimalPlaces = decimalPlaces; + } + public double up(double byValue) + { + return calculateToNearestInterval (myValue, + byValue, + true, + myDecimalPlaces); + } + public double down(double byValue) + { + return calculateToNearestInterval (myValue, + byValue, + false, + myDecimalPlaces); + } + public static double calculateToNearestInterval(double inPrice, double interval, + bool up, int numbDigitsAfterDecimalPoint) + { + double calculatedPrice = 0.0; + if (interval == 0.0) + return inPrice; + + long powerVal = (long)Math.Pow(10, numbDigitsAfterDecimalPoint); + double tempPrice = inPrice * powerVal; + long iPrice = (long)Math.Floor(tempPrice + 0.5); + + long iInterval = (long)Math.Floor(interval * powerVal + 0.5); + if (iInterval == 0) + return inPrice; + long newPrice = 0; + + if (up) + { + if ((iPrice % iInterval) == 0) + newPrice = iPrice + iInterval; + else + { + long mod = (iPrice % iInterval); + newPrice = iPrice - mod + iInterval; + } + } + else + { + if ((iPrice % iInterval) == 0) + newPrice = iPrice - iInterval; + else + { + long mod = (iPrice % iInterval); + newPrice = iPrice - mod; + } + } + + calculatedPrice = (newPrice/Math.Pow(10, numbDigitsAfterDecimalPoint)); + return calculatedPrice; + } + } +} + diff --git a/src/client/spark/NMSheets/Outside/PriceSettingsTag.cs b/src/client/spark/NMSheets/Outside/PriceSettingsTag.cs new file mode 100644 index 000000000..e1dc6e41a --- /dev/null +++ b/src/client/spark/NMSheets/Outside/PriceSettingsTag.cs @@ -0,0 +1,8 @@ +using mbts.bb; + +namespace BCG +{ + public class PriceSettingsTag : EqualsHelper + { + } +} diff --git a/src/client/spark/NMSheets/Outside/ResourceManagementTags.cs b/src/client/spark/NMSheets/Outside/ResourceManagementTags.cs new file mode 100644 index 000000000..b5b6c5657 --- /dev/null +++ b/src/client/spark/NMSheets/Outside/ResourceManagementTags.cs @@ -0,0 +1,26 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace BCG +{ + public class ResourceManagementTags + { + public class AquireTag : KeyedTag + { + public AquireTag(object req_id) : base(req_id) { } + } + + public class DisposeTag : KeyedTag + { + public DisposeTag(object req_id) : base(req_id) { } + } + + public class ActiveOptionsTag : mbts.bb.EqualsHelper + { + public ActiveOptionsTag() { } + } + } +} diff --git a/src/client/spark/NMSheets/Outside/SpreadWindowSettingsTag.cs b/src/client/spark/NMSheets/Outside/SpreadWindowSettingsTag.cs new file mode 100644 index 000000000..a8f226b57 --- /dev/null +++ b/src/client/spark/NMSheets/Outside/SpreadWindowSettingsTag.cs @@ -0,0 +1,8 @@ +using mbts.bb; + +namespace BCG +{ + class SpreadWindowSettingsTag : EqualsHelper + { + } +} diff --git a/src/client/spark/NMSheets/Outside/SymbolResourceAllocationUnit.cs b/src/client/spark/NMSheets/Outside/SymbolResourceAllocationUnit.cs new file mode 100644 index 000000000..ce14f305a --- /dev/null +++ b/src/client/spark/NMSheets/Outside/SymbolResourceAllocationUnit.cs @@ -0,0 +1,24 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace BCG +{ + public class SymbolResourceAllocationUnit + { + public readonly IEnumerable sectups; + public readonly object user_id; + public readonly bool is_activate; + + public SymbolResourceAllocationUnit(IEnumerable this_sectups, + object this_user_id, + bool this_is_activate) + { + sectups = this_sectups; + user_id = this_user_id; + is_activate = this_is_activate; + } + } +} diff --git a/src/client/spark/NMSheets/Outside/TaskCommon.cs b/src/client/spark/NMSheets/Outside/TaskCommon.cs new file mode 100644 index 000000000..7123f288f --- /dev/null +++ b/src/client/spark/NMSheets/Outside/TaskCommon.cs @@ -0,0 +1,159 @@ + + +using ProtoBuf; + +using System; +using System.Collections.Generic; + +namespace mbts.tasks { + [Serializable] + //[RecordType] + [ProtoContract(Name = "TaskCommon")] + public class TaskCommon { + [ProtoMember(1)] + public readonly string session; + [ProtoMember(10)] + public readonly string id; + [ProtoMember(20)] + public readonly DateTime create_time; + [ProtoMember(30)] + public readonly TaskType task_type; + [ProtoMember(40)] + public readonly string name; + [ProtoMember(50)] + public readonly TaskEdgeType edge_type; + [ProtoMember(60)] + public readonly string edge_surface; + [ProtoMember(70)] + public readonly double bid_edge_param; + [ProtoMember(75)] + public readonly double ask_edge_param; + [ProtoMember(80)] + public readonly double bid_size_param; + [ProtoMember(85)] + public readonly double ask_size_param; + [ProtoMember(90)] + public readonly TaskExitCondition exit_condition; + [ProtoMember(100)] + public readonly double exit_condition_parameter; + [ProtoMember(110)] + public readonly bool rfq_only; + [ProtoMember(120)] + public readonly double rfq_quote_for_seconds; + [ProtoMember(130)] + public readonly TaskSide side; + [ProtoMember(140)] + public readonly DateTime last_modification_time; + [ProtoMember(150)] + public readonly bool auto_hedge; + //[ProtoMember(160)] + //public readonly bool auto_start; + [ProtoMember(200)] + public readonly List> overridden_edges; + [ProtoMember(210)] + public readonly List> overridden_sizes; + + private TaskCommon() { /*for protobuf*/ } + + public TaskCommon(string id, + string session, + DateTime create_time, + TaskType task_type, + string task_name, + TaskExitCondition exit_condition, + double exit_condition_param, + bool rfq_only, + double rfq_quote_for_seconds, + TaskEdgeType edge_type, + string edge_surface, + double bid_edge_param, + double ask_edge_param, + double bid_size_param, + double ask_size_param, + TaskSide side, + DateTime last_modification_time, + bool auto_hedge, + List> overridden_edges, + List> overridden_sizes) { + this.id = id; + this.session = session; + this.create_time = create_time; + this.task_type = task_type; + this.name = task_name; + this.exit_condition = exit_condition; + this.exit_condition_parameter = exit_condition_param; + this.rfq_only = rfq_only; + this.rfq_quote_for_seconds = rfq_quote_for_seconds; + this.edge_type = edge_type; + this.edge_surface = edge_surface; + this.bid_edge_param = bid_edge_param; + this.ask_edge_param = ask_edge_param; + this.bid_size_param = bid_size_param; + this.ask_size_param = ask_size_param; + this.side = side; + this.last_modification_time = last_modification_time; + this.auto_hedge = auto_hedge; + this.overridden_edges = overridden_edges; + this.overridden_sizes = overridden_sizes; + } + + public static TaskCommon Default { + get { + return new TaskCommon( + id: Guid.NewGuid().ToString(), + session: String.Empty, + create_time: DateTime.Now, + task_type: TaskType.Quoter, + task_name: "", + exit_condition: TaskExitCondition.Contracts, + exit_condition_param: 100, + rfq_only: false, + rfq_quote_for_seconds: 10, + edge_type: TaskEdgeType.Manual, + edge_surface: "", + bid_edge_param: double.NaN, + ask_edge_param: double.NaN, + bid_size_param: double.NaN, + ask_size_param: double.NaN, + side: TaskSide.Buy | TaskSide.Sell, + last_modification_time: DateTime.Now, + auto_hedge: true, + overridden_edges: new List>(), + overridden_sizes: new List>()); + } + } + + public TaskCommon with(string id = null, string session = null, DateTime? create_time = null, + TaskType? task_type = null, string name = null, TaskExitCondition? exit_condition = null, + double? exit_condition_parameter = null, bool? rfq_only = null, double? rfq_quote_for_seconds = null, TaskEdgeType? edge_type = null, + string edge_surface = null, + double? bid_edge_param = null, double? bid_size_param = null, + double? ask_edge_param = null, double? ask_size_param = null, + TaskSide? side = null, DateTime? last_modification_time = null, + bool? auto_hedge = null, + List> overridden_edges = null, + List> overridden_sizes = null) { + return new TaskCommon(id ?? this.id, + session ?? this.session, + create_time ?? this.create_time, + task_type ?? this.task_type, + name ?? this.name, + exit_condition ?? this.exit_condition, + exit_condition_parameter ?? this.exit_condition_parameter, + rfq_only ?? this.rfq_only, + rfq_quote_for_seconds ?? this.rfq_quote_for_seconds, + edge_type ?? this.edge_type, + edge_surface ?? this.edge_surface, + bid_edge_param ?? this.bid_edge_param, + ask_edge_param ?? this.ask_edge_param, + bid_size_param ?? this.bid_size_param, + ask_size_param ?? this.ask_size_param, + side ?? this.side, + last_modification_time ?? this.last_modification_time, + auto_hedge ?? this.auto_hedge, + overridden_edges ?? this.overridden_edges, + overridden_sizes ?? this.overridden_sizes); + } + } + +} \ No newline at end of file diff --git a/src/client/spark/NMSheets/Outside/TaskConstants.cs b/src/client/spark/NMSheets/Outside/TaskConstants.cs new file mode 100644 index 000000000..0f1b060e0 --- /dev/null +++ b/src/client/spark/NMSheets/Outside/TaskConstants.cs @@ -0,0 +1,24 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace mbts.tasks { + public static class TaskConstants { + public static TimeSpan task_ping_period = TimeSpan.MaxValue; + public static uint n_missing_pings_threshold = uint.MaxValue; + public static bool enable_tasking_for_GLBX = false, + enable_tasking_for_CBOE = false; + + static TaskConstants() { + // var engines = mbts.config.Configuration.get(); + // task_ping_period = TimeSpan.FromMilliseconds(engines.hb_period_ms); + // n_missing_pings_threshold = engines.max_missed_hbs; + // enable_tasking_for_GLBX = mbts.config.Configuration.get().enabled; + // enable_tasking_for_CBOE = mbts.config.Configuration.get().enabled; + } + + + } +} diff --git a/src/client/spark/NMSheets/Outside/TaskEnums.cs b/src/client/spark/NMSheets/Outside/TaskEnums.cs new file mode 100644 index 000000000..3444ef4f4 --- /dev/null +++ b/src/client/spark/NMSheets/Outside/TaskEnums.cs @@ -0,0 +1,71 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace mbts.tasks +{ + public enum TaskType + { + Eye, + Quoter, + RFQ, + Auction, + } + + public enum TaskSecurityFilterType + { + Filter, + Strike, + Delta, + Vega, + Gamma, + NumLegs, + AbsoluteContracts, + NetContracts + }; + + public enum TaskEdgeType + { + EdgeSurface, + Manual + } + + public enum TaskExitCondition + { + Contracts, + Delta, + Vega, + Gamma, + Time + } + + public enum TaskSwitchState + { + On, + Off + } + + public enum TaskHealthState + { + OK, + Suspended, + Disconnected, + } + + [Flags] + public enum TaskSide + { + None, + Buy, + Sell, + } + + public enum TaskLogLevel + { + Info, + Warning, + Error + } +} diff --git a/src/client/spark/NMSheets/Outside/TaskLiveData.cs b/src/client/spark/NMSheets/Outside/TaskLiveData.cs new file mode 100644 index 000000000..215cfbfe8 --- /dev/null +++ b/src/client/spark/NMSheets/Outside/TaskLiveData.cs @@ -0,0 +1,70 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace mbts.tasks +{ + /// Task persisted state combined with + /// the live running state + public class TaskLiveData : IEquatable + { + public readonly ElectronicTradingTask task; + public readonly TaskSwitchState switch_state; + public readonly TaskHealthState task_state; + public readonly double net_accumulation, abs_accumulation; + + public TaskLiveData(ElectronicTradingTask task, TaskSwitchState switch_state, TaskHealthState health_state, + double net_accumulation, double abs_accumulation) + { + this.task = task; + this.switch_state = switch_state; + this.task_state = health_state; + this.net_accumulation = net_accumulation; + this.abs_accumulation = abs_accumulation; + } + + public string task_id { get { return task.common.id; } } + + public TaskType task_type { get { return task.common.task_type; } } + + public string name { get { return task.common.name; } } + + public double completion_ratio { get { return abs_accumulation / task.common.exit_condition_parameter; } } + + public bool is_filled { get { return completion_ratio >= 1.0; } } + + public DateTime modification_time { get { return task.common.last_modification_time; } } + + public TaskLiveData with(ElectronicTradingTask task = null, TaskSwitchState? switch_state = null, TaskHealthState? task_state = null, + double? net_accumulation = null, double? abs_accumulation = null) + { + return new TaskLiveData(task ?? this.task, + switch_state ?? this.switch_state, + task_state ?? this.task_state, + net_accumulation ?? this.net_accumulation, + abs_accumulation ?? this.abs_accumulation); + } + + public int GetHashCode(TaskLiveData obj) { return obj.task_id.GetHashCode(); } + + public bool Equals(TaskLiveData other) + { + return ReferenceEquals(task, other.task) && + switch_state == other.switch_state && + task_state == other.task_state && + completion_ratio == other.completion_ratio; + } + public override string ToString() + { + return task.ToString(); + } + + public string get_summary_text() + { + string sign = task.common.side == TaskSide.Buy ? "+" : (task.common.side == TaskSide.Sell ? "-" : "+/-"); + return String.Format("{0}{1} ({2}/{3})", sign, task.common.name, abs_accumulation, task.common.exit_condition_parameter); + } + } +} diff --git a/src/client/spark/NMSheets/Outside/TaskSecurityEyeData.cs b/src/client/spark/NMSheets/Outside/TaskSecurityEyeData.cs new file mode 100644 index 000000000..ebc4eb122 --- /dev/null +++ b/src/client/spark/NMSheets/Outside/TaskSecurityEyeData.cs @@ -0,0 +1,50 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace mbts.tasks { + public class TaskSecurityEyeData { + + public TaskSecurityEyeData() { + } + + public bool is_output_present { + get { + return false; + } + } + + public bool is_on { + get { + return false; + } + } + + /// If the security is on, returns the edge as sent by the eye + /// otherwise returns the input edge + public double edge { + get { + return Double.NaN; + } + } + + /// If the security is on, returns the size as sent by the eye + /// otherwise returns the input size + public uint size { + get { + return 0; + } + } + + public double eye_published_price { + get { + // if (is_on && is_output_present) + // return input.secside_key.side == bts.o2.msgs.Side.type.BUY ? output.price - output.edge : output.price + output.edge; + // return Double.NaN; + return Double.NaN; + } + } + } +} diff --git a/src/client/spark/NMSheets/Outside/TaskSecurityQuoterData.cs b/src/client/spark/NMSheets/Outside/TaskSecurityQuoterData.cs new file mode 100644 index 000000000..968be363d --- /dev/null +++ b/src/client/spark/NMSheets/Outside/TaskSecurityQuoterData.cs @@ -0,0 +1,46 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace mbts.tasks { + public class TaskSecurityQuoterData { + + public TaskSecurityQuoterData() { + } + + public bool is_output_present { + get { + return false; + } + } + + public bool is_on { + get { return false; } + } + + /// If the security is on, returns the edge as sent by the quoter + /// otherwise returns the input edge + public double edge { + get { return Double.NaN; } + } + + /// If the security is on, returns the size as sent by the quoter + /// otherwise returns the input size + public uint size { + get { return 0; } + } + + public double quoter_published_working_price { + get { + return Double.NaN; + } + } + + public uint quoter_published_working_size { + get { return 0; } + //get { return (is_on && is_output_present) ? (output.size - output.fills) : 0; } + } + } +} diff --git a/src/client/spark/NMSheets/Outside/TheoPoint.cs b/src/client/spark/NMSheets/Outside/TheoPoint.cs new file mode 100644 index 000000000..67ac4eaaa --- /dev/null +++ b/src/client/spark/NMSheets/Outside/TheoPoint.cs @@ -0,0 +1,279 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace mbts { + public class TheoPoint : ICloneable { + //if true, SPX mode -- assumes you hedge the whole thing with combos at the tie price + //false, Merc mode -- assumes you get what you get + private static bool assume_tied_spreads_fully_hedged; + static TheoPoint() { + assume_tied_spreads_fully_hedged = true; + + //mbts.config.Configuration.get().enabled; + } + //Rationale + //If the market is at live_driver, and I pay for a spread tied to locked_driver that is not the current futures price + //and perfectly hedge it, I will receive gamma for that spread that, if in the event the market moves + //to the locked price, I will be able sell additional hedge units against that new delta. + //Thus, here we compute the value of those extra hedge units and incorporate them into the theo. + //Delta's and gammas here are as a percent, like 45 instead of .45 + + //9 Jan 2015 + //Randy / Kev conversation (spurred on by questions from Lorry) + //Let's say we consider a spread buying 2 35 delta options worth 10 bucks a piece at und == 1000 + //Now I do the spread tied to 1010, wherein those options are now worth 14 (delta gets us to 13.5, add .5 for gamma, approx) + //and the delta is now 50 (because of gamma). + //Hedging the delta up at 1010 (the essence of the locked trade), I sell 1 future at 1010 (because 2*50 delta = 1 future) + //BUT I get to sell that future 10 dollars higher than the current market of 1000. + + //I could now turn around and buy that future back at 1000 and yield a profit of 10 bucks on that 1 future, and then + //sell the spread back out at a price of 10 bucks per option (it's current theo at the live market), + //so I'd lose 4 bucks per option (bought at 14 sld at 10), or 8 bucks total on the options, but I made 10 on the future, + //netting me a 2 dollar profit for simply unwinding the trade I just did. + + //Therefore I can choose to reflect this windfall in what we call the gamma-adjusted theoretical value by + //adding that 2 bucks of profit back into the theoretical value of the package. + public static void compute_enhanced_spread(double live_driver, double locked_driver, + double spread_locked_price, double spread_locked_delta_no_futs, double spread_locked_gamma, + double spread_live_price, double spread_live_delta_no_futs, double spread_live_gamma, + double initial_hedge, + + ref double new_spread_price, + ref double spread_delta_difference, ref double unused) { + //travel from locked to live with the option + double spread_change = spread_live_price - spread_locked_price; + + //NEW 10/28/2015 KD travel from locked to live with initial hedge (if it's an exchange-listed covered) + double initial_hedge_change = (assume_tied_spreads_fully_hedged) ? 0.0 + : (initial_hedge * (live_driver - locked_driver)); + + //travel from locked to live with the sold hedge (note it's locked-live here to negate for hedge) + //NEW 11/24/2015 -- only hedge this spread if it's not a covered, hedging it twice doesn't make sense + double hedge_change = 0.0; + if (initial_hedge == 0.0 || assume_tied_spreads_fully_hedged) + hedge_change = (spread_locked_delta_no_futs + initial_hedge) * (locked_driver - live_driver); + + new_spread_price = spread_locked_price + spread_change + initial_hedge_change + hedge_change; + spread_delta_difference = 100.0 * (spread_locked_delta_no_futs - spread_live_delta_no_futs); + unused = 0.0; + } + + public enum InterpolationMethod { + TAYLOR = 0, LINEAR = 1, POLY = 2 + } + + public double call = Double.NaN, put = Double.NaN, + cdelta = Double.NaN, pdelta = Double.NaN, + c_interp_delta = Double.NaN, p_interp_delta = Double.NaN, + cgamma = Double.NaN, pgamma = Double.NaN, + c_interp_gamma = Double.NaN, p_interp_gamma = Double.NaN, + cvega = Double.NaN, pvega = Double.NaN, driver = Double.NaN, + vol = Double.NaN, + /// added 02/18/2014 + c_oev = Double.NaN, p_oev = Double.NaN, + c_slope_vega = Double.NaN, p_slope_vega = Double.NaN, + c_vanna = Double.NaN, p_vanna = Double.NaN, + veganovr = double.NaN, + c_adj_vega = Double.NaN, p_adj_vega = Double.NaN, + c_theta = Double.NaN, p_theta = Double.NaN, fwd = double.NaN, standard_strike = double.NaN, theo_time = Double.NaN, + /// added 7/30/2016 + driver_bid, driver_ask; + + private TheoPoint() { } + + public readonly static TheoPoint shared_null_tp = getNulledObject(); + + public static TheoPoint getNulledObject() { + return new TheoPoint(); + } + + public TheoPoint(double theCall, double thePut, double theCDelta, double thePDelta, double theCVega, double thePVega, double theDriver) { + call = theCall; + put = thePut; + cdelta = theCDelta; + pdelta = thePDelta; + cvega = theCVega; + pvega = thePVega; + driver = theDriver; + } + + public TheoPoint(double theCall, double thePut, double theCDelta, double thePDelta, double theCGamma, double thePGamma, double theCVega, double thePVega, double theVol, double theDriver) + : this(theCall, thePut, theCDelta, thePDelta, theCVega, thePVega, theDriver) { + cgamma = theCGamma; + pgamma = thePGamma; + vol = theVol; + } + + public void copy_from(TheoPoint other) { + call = other.call; + put = other.put; + cdelta = other.cdelta; + pdelta = other.pdelta; + cvega = other.cvega; + pvega = other.pvega; + driver = other.driver; + cgamma = other.cgamma; + pgamma = other.pgamma; + vol = other.vol; + c_oev = other.c_oev; + p_oev = other.p_oev; + c_slope_vega = other.c_slope_vega; + p_slope_vega = other.p_slope_vega; + c_vanna = other.c_vanna; + p_vanna = other.p_vanna; + veganovr = other.veganovr; + c_adj_vega = other.c_adj_vega; + p_adj_vega = other.p_adj_vega; + c_theta = other.c_theta; + p_theta = other.p_theta; + fwd = other.fwd; + standard_strike = other.standard_strike; + theo_time = other.theo_time; + } + + public void copy_view_delta_gamma_to_interp() { + c_interp_delta = cdelta; + p_interp_delta = pdelta; + c_interp_gamma = cgamma; + p_interp_gamma = pgamma; + } + + public void mult_interp_delta_gamma(double delta_mult, double gamma_mult) { + c_interp_delta *= delta_mult; + p_interp_delta *= delta_mult; + c_interp_gamma *= gamma_mult; + p_interp_gamma *= gamma_mult; + } + + public object Clone() { + return new TheoPoint(call, put, cdelta, pdelta, cgamma, pgamma, cvega, pvega, vol, driver) { c_interp_delta = this.c_interp_delta, p_interp_delta = this.p_interp_delta, c_interp_gamma = this.c_interp_gamma, p_interp_gamma = this.p_interp_gamma, standard_strike = this.standard_strike, theo_time = this.theo_time }; + } + + public static double _weighted_mean_taylor_interp(double x1, double f1, double df1, double d2f1, + double x2, double f2, double df2, double d2f2, double x) { + double t_f_x1 = _taylor_interp(x1, f1, df1, d2f1, x), + t_f_x2 = _taylor_interp(x2, f2, df2, d2f2, x); + return (t_f_x1 * Math.Abs(x2 - x) + t_f_x2 * Math.Abs(x1 - x)) / (Math.Abs(x2 - x1)); + } + + public static double _taylor_interp(double x1, double f1, double df1, double d2f1, double x) { + return f1 + df1 * (x - x1) + d2f1 * Math.Pow(x - x1, 2) * 0.5; + } + + private class point_info { + public double x, f, df, d2f; + }; + + public static double _poly_interp(double x1, double f1, double df1, double d2f1, + double x2, double f2, double df2, double d2f2, double x) { + if (x1 == x2) + return f1; + else { + point_info p1 = new point_info() { x = x1, f = f1, df = df1, d2f = d2f1 }, + p2 = new point_info() { x = x2, f = f2, df = df2, d2f = d2f2 }; + double dx = p2.x - p1.x; + double p1mult = (p2.d2f - p1.d2f) * dx * dx; + double p2mult = (p2.df - p1.df - p1.d2f * dx) * dx; + double p3mult = p2.f - p1.f - (p1.df + 0.5 * p1.d2f * dx) * dx; + x = (x - p1.x) / dx; + return p1.f + x * (p1.df * dx + x * (0.5 * p1.d2f * dx * dx + x * (0.5 * p1mult - 4.0 * p2mult + 10.0 * p3mult + x * (-p1mult + 7.0 * p2mult - 15.0 * p3mult + x * (0.5 * p1mult - 3.0 * p2mult + 6.0 * p3mult))))); + } + } + + public static double _linear_interp(double x1, double y1, double x2, double y2, double x) { + /// return SplineCalcsCLR.linear_interp(x, new double[] { x1, x2 }, new double[] { y1, y2 }, 2); + return ((y2 - y1) / (x2 - x1)) * (x - x1) + y1; + } + + //This is a copy of _interp in UIFramework d:/home/darby/bts/blue2-hotfix-akuna/blue2/UIFramework/tc2/Calculator2/InterpolationCalculation/XFEDInterpolationCalculator.cs + //I since removed it from there + public static void interp(InterpolationMethod interp_method, TheoPoint p1, TheoPoint p2, double driver, TheoPoint result, + DateTime exp, double strike) { + if (interp_method == InterpolationMethod.LINEAR) { + result.driver = driver; + result.call = _linear_interp(p1.driver, p1.call, p2.driver, p2.call, driver); + result.put = _linear_interp(p1.driver, p1.put, p2.driver, p2.put, driver); + result.cdelta = _linear_interp(p1.driver, p1.cdelta, p2.driver, p2.cdelta, driver); + result.pdelta = _linear_interp(p1.driver, p1.pdelta, p2.driver, p2.pdelta, driver); + } else if (interp_method == InterpolationMethod.TAYLOR) { + result.driver = driver; + double parity_roll = strike + p1.call - p1.put - p1.driver; + double fwd = driver + parity_roll; + if ((p1.c_interp_gamma == 0.0 || p2.c_interp_gamma == 0.0) && (DateTime.Now.Date >= exp)) { + result.call = Math.Max(fwd - strike, 0.0); + result.cdelta = (strike < fwd) ? 1.0 : 0.0; + //BCG.Utilities.BlueEventLog.logEvent(String.Format("Parity : {0} {1} {2} {3} {4} {5}", p1.driver, p2.driver, driver, exp, strike, true), BCG.Utilities.BlueEventLevel.Information); + } else { + result.call = _weighted_mean_taylor_interp(p1.driver, p1.call, p1.c_interp_delta, p1.c_interp_gamma, + p2.driver, p2.call, p2.c_interp_delta, p2.c_interp_gamma, driver); + result.cdelta = _linear_interp(p1.driver, p1.cdelta, p2.driver, p2.cdelta, driver); + } + + if ((p1.p_interp_gamma == 0.0 || p2.p_interp_gamma == 0.0) && (DateTime.Now.Date >= exp)) { + result.put = Math.Max(strike - fwd, 0.0); + result.pdelta = (strike > fwd) ? -1.0 : 0.0; + //BCG.Utilities.BlueEventLog.logEvent (String.Format ("Parity : {0} {1} {2} {3} {4} {5}", p1.driver, p2.driver, driver, exp, strike, false), BCG.Utilities.BlueEventLevel.Information); + } else { + result.put = _weighted_mean_taylor_interp(p1.driver, p1.put, p1.p_interp_delta, p1.p_interp_gamma, + p2.driver, p2.put, p2.p_interp_delta, p2.p_interp_gamma, driver); + result.pdelta = _linear_interp(p1.driver, p1.pdelta, p2.driver, p2.pdelta, driver); + } + } else if (interp_method == InterpolationMethod.POLY) { + result.driver = driver; + double parity_roll = strike + p1.call - p1.put - p1.driver; + double fwd = driver + parity_roll; + if ((p1.c_interp_gamma == 0.0 || p2.c_interp_gamma == 0.0) && (DateTime.Now.Date >= exp)) { + result.call = Math.Max(fwd - strike, 0.0); + result.cdelta = (strike < fwd) ? 1.0 : 0.0; + //BCG.Utilities.BlueEventLog.logEvent(String.Format("Parity : {0} {1} {2} {3} {4} {5}", p1.driver, p2.driver, driver, exp, strike, true), BCG.Utilities.BlueEventLevel.Information); + } else { + result.call = _poly_interp(p1.driver, p1.call, p1.c_interp_delta, p1.c_interp_gamma, p2.driver, p2.call, p2.c_interp_delta, p2.c_interp_gamma, driver); + result.cdelta = _poly_interp(p1.driver, p1.cdelta, p1.c_interp_gamma, 0.0, p2.driver, p2.cdelta, p2.c_interp_gamma, 0.0, driver); + } + + if ((p1.p_interp_gamma == 0.0 || p2.p_interp_gamma == 0.0) && (DateTime.Now.Date >= exp)) { + result.put = Math.Max(strike - fwd, 0.0); + result.pdelta = (strike > fwd) ? -1.0 : 0.0; + //BCG.Utilities.BlueEventLog.logEvent(String.Format("Parity : {0} {1} {2} {3} {4} {5}", p1.driver, p2.driver, driver, exp, strike, false), BCG.Utilities.BlueEventLevel.Information); + } else { + result.put = _poly_interp(p1.driver, p1.put, p1.p_interp_delta, p1.p_interp_gamma, p2.driver, p2.put, p2.p_interp_delta, p2.p_interp_gamma, driver); + result.pdelta = _poly_interp(p1.driver, p1.pdelta, p1.p_interp_gamma, 0.0, p2.driver, p2.pdelta, p2.p_interp_gamma, 0.0, driver); + } + } + /// the rest can only be linear, because we dont have the derivatives + result.cgamma = _linear_interp(p1.driver, p1.cgamma, p2.driver, p2.cgamma, driver); + result.pgamma = _linear_interp(p1.driver, p1.pgamma, p2.driver, p2.pgamma, driver); + result.cvega = _linear_interp(p1.driver, p1.cvega, p2.driver, p2.cvega, driver); + result.pvega = _linear_interp(p1.driver, p1.pvega, p2.driver, p2.pvega, driver); + result.c_theta = _linear_interp(p1.driver, p1.c_theta, p2.driver, p2.c_theta, driver); + result.p_theta = _linear_interp(p1.driver, p1.p_theta, p2.driver, p2.p_theta, driver); + result.vol = _linear_interp(p1.driver, p1.vol, p2.driver, p2.vol, driver); + result.fwd = _linear_interp(p1.driver, p1.fwd, p2.driver, p2.fwd, driver); + result.standard_strike = _linear_interp(p1.driver, p1.standard_strike, p2.driver, p2.standard_strike, driver); + result.c_adj_vega = _linear_interp(p1.driver, p1.c_adj_vega, p2.driver, p2.c_adj_vega, driver); + result.p_adj_vega = _linear_interp(p1.driver, p1.p_adj_vega, p2.driver, p2.p_adj_vega, driver); + result.c_oev = _linear_interp(p1.driver, p1.c_oev, p2.driver, p2.c_oev, driver); + result.p_oev = _linear_interp(p1.driver, p1.p_oev, p2.driver, p2.p_oev, driver); + result.c_slope_vega = _linear_interp(p1.driver, p1.c_slope_vega, p2.driver, p2.c_slope_vega, driver); + result.p_slope_vega = _linear_interp(p1.driver, p1.p_slope_vega, p2.driver, p2.p_slope_vega, driver); + result.c_vanna = _linear_interp(p1.driver, p1.c_vanna, p2.driver, p2.c_vanna, driver); + result.p_vanna = _linear_interp(p1.driver, p1.p_vanna, p2.driver, p2.p_vanna, driver); + result.veganovr = _linear_interp(p1.driver, p1.veganovr, p2.driver, p2.veganovr, driver); + result.standard_strike = _linear_interp(p1.driver, p1.standard_strike, p2.driver, p2.standard_strike, driver); + result.theo_time = p1.theo_time; + } + + /// Computes theos at a given driver price (extrapolating using taylors) + public static double get_theo_at_driver(TheoPoint tp, double driver, bool is_call) { + tp = tp ?? TheoPoint.shared_null_tp; + double driver_diff = driver - tp.driver; + if (is_call) + return tp.call + (tp.cdelta * driver_diff) + (0.5 * tp.cgamma * driver_diff * driver_diff); + else + return tp.put + (tp.pdelta * driver_diff) + (0.5 * tp.pgamma * driver_diff * driver_diff); + } + } +} \ No newline at end of file diff --git a/src/client/spark/NMSheets/Outside/TheoTags.cs b/src/client/spark/NMSheets/Outside/TheoTags.cs new file mode 100644 index 000000000..505fa960f --- /dev/null +++ b/src/client/spark/NMSheets/Outside/TheoTags.cs @@ -0,0 +1,28 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace BCG { + public class TheoTags { + public class LiveOptionTheoTag : KeyedTag { public LiveOptionTheoTag(string option_name) : base(option_name) { } } + + public class PrecomputedOptionTheoTag : KeyedTag { public PrecomputedOptionTheoTag(string option_name) : base(option_name) { } } + + public class LiveFutureTheoTag : KeyedTag { public LiveFutureTheoTag(string future_name) : base(future_name) { } } + + public class TheoreticalEdgesTag : mbts.bb.EqualsHelper { } + + public class OptionRollsTag : KeyedTag { public OptionRollsTag(string option_name) : base(option_name) { } } + + public class PNLRollOverDataTag : KeyedTag { public PNLRollOverDataTag(string option_symbol) : base(option_symbol) { } } + + public class CompletePNLRolloverDataTag : mbts.bb.EqualsHelper { } + + public class PresaveTheoTag : NamedTag { + public PresaveTheoTag(int volsurface_id) + : base(volsurface_id) { } + } + } +} \ No newline at end of file diff --git a/src/client/spark/NMSheets/Outside/ThreadSafeQueue.cs b/src/client/spark/NMSheets/Outside/ThreadSafeQueue.cs new file mode 100644 index 000000000..0c12d3fcb --- /dev/null +++ b/src/client/spark/NMSheets/Outside/ThreadSafeQueue.cs @@ -0,0 +1,151 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace BCG { + /// + /// Uses locks to provide thread safety. This turns out to be + /// a problem if there are a lot of threads trying to access + /// a queue. For this purpose this class will serve as the base + /// class for later lock free (wait free) implementations + /// + /// + public class ThreadSafeQueue { + private readonly int _max_size = Int32.MaxValue; + private Queue _main_queue = new Queue(); + + private DateTime _last_dequeque_time = DateTime.MinValue; + private string _queue_name = String.Empty; + private bool _log_queue_size_warnings = false; + private int _warning_log_size = Int32.MaxValue; + private readonly TimeSpan _warning_log_period = TimeSpan.MaxValue, _first_log_period = TimeSpan.FromSeconds(30); + private DateTime _last_log_time = DateTime.MinValue; + private readonly DateTime _construction_time = DateTime.Now; + + public ThreadSafeQueue() + : this(Int32.MaxValue) { } + + public ThreadSafeQueue(int max_size) + : this(max_size, String.Empty, false, Int32.MaxValue, TimeSpan.MaxValue) { } + + public ThreadSafeQueue(int max_size, string queue_name, bool log_queue_size_warnings, int warning_log_size, TimeSpan warning_log_period) { + _max_size = max_size; + _queue_name = queue_name; + _log_queue_size_warnings = log_queue_size_warnings; + _warning_log_size = warning_log_size; + _warning_log_period = warning_log_period; + } + + public virtual bool enqueue(T t) { + lock (this) { + int count = getCount(); + _check_size_and_warn(count); + if (count < _max_size) { + _main_queue.Enqueue(t); + return true; + } else + return false; + } + } + + public virtual int enqueue(ICollection list) { + int nElements = 0; + lock (this) { + foreach (T t in list) + if (enqueue(t)) + nElements++; + } + return nElements; + } + + public virtual int getCount() { + int count; + lock (this) { count = _main_queue.Count; } + return count; + } + + public virtual bool clear_and_enqueue(T t) { + bool rv; + lock (this) { + _main_queue.Clear(); + rv = enqueue(t); + } + return rv; + } + + public virtual int clear_and_enqueue(ICollection list) { + int rv = 0; + lock (this) { + _main_queue.Clear(); + rv = enqueue(list); + } + return rv; + } + + public virtual T dequeue() { + T rv; + lock (this) { + if (_main_queue.Count > 0) { + _last_dequeque_time = DateTime.Now; + rv = _main_queue.Dequeue(); + } else + rv = default(T); + } + return rv; + } + + public virtual List dequeueAll() { + List rv = new List(); + lock (this) { + int sz = getCount(); + for (int i = 0; i < sz; i++) + rv.Add(dequeue()); + } + return rv; + } + + public virtual bool enqueue_and_crush(T new_elem, Comparison comp) { + bool rv; + lock (this) { + Dictionary marked_for_deletion = new Dictionary(); + List all_elements = dequeueAll(); + for (int i = 0; i < all_elements.Count; i++) + if (_compare(new_elem, all_elements[i], comp)) + marked_for_deletion.Add(i, true); + for (int i = 0; i < all_elements.Count; i++) + if (!marked_for_deletion.ContainsKey(i)) + enqueue(all_elements[i]); + rv = enqueue(new_elem); + } + return rv; + } + + private static bool _compare(T t1, T t2, Comparison comp) { + if (comp != null) + return comp(t1, t2) == 0; + else + return t1 != null && t1.Equals(t2); + } + + public virtual List dequeueLimited(int max) { + List rv = new List(); + lock (this) { + int limit = Math.Min(max, _main_queue.Count); + for (int i = 0; i < limit; i++) + rv.Add(dequeue()); + } + return rv; + } + + + private void _check_size_and_warn(int count) { + if (_log_queue_size_warnings) { + if (count > _warning_log_size && (DateTime.Now - _last_log_time > _warning_log_period) && (DateTime.Now - _construction_time > _first_log_period)) { + _last_log_time = DateTime.Now; + bts.Log.Gen.warn(String.Format("ThreadSafeQueue size breach queue_name : {0} type : {1} hash : {2} n of elems : {3}", _queue_name, typeof(T), GetHashCode(), count)); + } + } + } + + } +} diff --git a/src/client/spark/NMSheets/Outside/ThreadedBlackboard.cs b/src/client/spark/NMSheets/Outside/ThreadedBlackboard.cs new file mode 100644 index 000000000..abd0bc4a7 --- /dev/null +++ b/src/client/spark/NMSheets/Outside/ThreadedBlackboard.cs @@ -0,0 +1,203 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace BCG { + /// + /// For classes, that are constructed and run on their + /// own thread, this class provides a threaded wrapper + /// around the main blackboard. + /// The assumption here is that this class will + /// be constructed in the secondary thread, and + /// all functions prefixed with 'sec_thread' will be called + /// from the same secondary thread. + /// + public class ThreadedBlackboard : BCG.Utilities.General.IWorker, IAgent { + public delegate void OnBBData(object tag, object data); + private readonly Blackboard _bb; + private readonly MasterWorker _master_worker; + private readonly int _secondary_thread_id = System.Threading.Thread.CurrentThread.ManagedThreadId; + private int _main_thread_id = -1; + /// state + private bool _bb_joined = false, _sec_disposed = false; + private IDictionary _subsribed_tags = new Dictionary(); + private List> _subsribed_tags_funcs = new List>(); + private Dictionary _cached_data = new Dictionary(); + /// thread transfer data + private ThreadSafeQueue> _main_to_sec_callback_waiting_data_queue, _sec_to_main_write_request_queue; + private ThreadSafeQueue _sec_to_main_subscription_request_queue; + private ThreadSafeQueue> _sec_to_main_subscription_func_request_queue; + private readonly string _bb_name; + private BCG.Utilities.General.HighPerformanceTimer _timer = new Utilities.General.HighPerformanceTimer(); + + public ThreadedBlackboard(string bb_name, Blackboard bb, MasterWorker main_loop_worker, + OnBBData callback, params object[] subsribed_tags) { + _bb_name = bb_name; + _main_to_sec_callback_waiting_data_queue = new ThreadSafeQueue>(Int32.MaxValue, String.Format("MainToSecondaryWrite_{0}", _bb_name), true, 250, TimeSpan.FromSeconds(30)); + _sec_to_main_write_request_queue = new ThreadSafeQueue>(Int32.MaxValue, String.Format("SecondaryToMainWrite_{0}", _bb_name), true, 250, TimeSpan.FromSeconds(30)); + _sec_to_main_subscription_request_queue = new ThreadSafeQueue(Int32.MaxValue, String.Format("SecondaryToMainSubscription_{0}", _bb_name), true, 50, TimeSpan.FromSeconds(30)); + _sec_to_main_subscription_func_request_queue = new ThreadSafeQueue>(Int32.MaxValue, String.Format("SecondaryToMainSubscriptionFunc_{0}", _bb_name), true, 50, TimeSpan.FromSeconds(30)); + _check_secondary_thread_consistency(); + bts.Log.assert(!_sec_disposed, "Already disposed"); + _bb = bb; + _master_worker = main_loop_worker; + data_callback = callback; + if (subsribed_tags != null && subsribed_tags.Length > 0) + add_to_subscription_list(subsribed_tags); + _master_worker.addWorker(this, new TimeSpan(0, 0, 0, 0, 10)); + } + + #region Secondary Multithreaded Functions + + #region Public API + + public OnBBData data_callback; + public Action timer_callback; + + public void add_to_subscription_list(params object[] tags) { + _check_secondary_thread_consistency(); + _sec_to_main_subscription_request_queue.enqueue(tags); + } + + public void add_to_subscription_list(Func sub_func) { + _check_secondary_thread_consistency(); + _sec_to_main_subscription_func_request_queue.enqueue(sub_func); + } + + public void sec_thread_write(object tag, object value) { sec_thread_write(tag, value, false); } + + internal IBlackboard get_underlying_blackboard() { return _bb; } + + /// + /// this can be a blocking or non blocking call + /// depending on the last arg + /// + /// + /// + public void sec_thread_write(object tag, object value, bool block_until_written) { + _check_secondary_thread_consistency(); + bts.Log.assert(!_sec_disposed, "Already disposed"); + _sec_to_main_write_request_queue.enqueue(new Pair(tag, value)); + while (block_until_written && _sec_to_main_write_request_queue.getCount() > 0) + System.Threading.Thread.Sleep(10); + } + + public void sec_thread_dowork() { + _check_secondary_thread_consistency(); + bts.Log.assert(!_sec_disposed, "Already disposed"); + List> bb_data = _main_to_sec_callback_waiting_data_queue.dequeueAll(); + _store_in_cache(bb_data); + if (data_callback != null) + foreach (Pair p in bb_data) + foreach (Delegate d in data_callback.GetInvocationList()) { + _timer.start(); d.DynamicInvoke(p.first, p.second); _timer.stop(); + if (_timer.lastIntervalTime > 500) + bts.Log.Ui.warn(String.Format("Threaded_bb callback for tag {0} took {1} msecs callee {2}", p.first, _timer.lastIntervalTime, d.Target.GetType().ToString())); + } + if (timer_callback != null) + timer_callback(); + } + + public object sec_thread_retrieve_from_cache(object tag) { + _check_secondary_thread_consistency(); + object rv = null; + if (_cached_data.TryGetValue(tag, out rv)) + return rv; + else + return null; + } + + #endregion + + private void _store_in_cache(List> bb_data) { + foreach (Pair p in bb_data) + _cached_data[p.first] = p.second; + } + + private void _check_secondary_thread_consistency() { bts.Log.assert(System.Threading.Thread.CurrentThread.ManagedThreadId == _secondary_thread_id, "ThreadedBlackboard can only be used from one secondary thread"); } + + private void _check_main_thread_consistency() { bts.Log.assert(_main_thread_id == -1 || System.Threading.Thread.CurrentThread.ManagedThreadId == _main_thread_id, "Main thread access problem"); } + + public void sec_thread_dispose() { + _check_secondary_thread_consistency(); + bts.Log.assert(!_sec_disposed, "Already disposed"); + _sec_disposed = true; + } + + #endregion + + #region main thread functions + + private bool _secondary_thread_all_done() { + /// so even after sec_dispose is called from the sec thread, + /// there could be unwritten items. Up until those are nto written + /// to the bb, the main doWork keeps going + return _sec_disposed && _sec_to_main_write_request_queue.getCount() == 0; + } + + /// Main thread doWork + public void doWork() { + if (_main_thread_id == -1) + _main_thread_id = System.Threading.Thread.CurrentThread.ManagedThreadId; + _check_main_thread_consistency(); + if (!_secondary_thread_all_done()) { + /// joining, if first time + if (!_bb_joined) { + _bb_joined = true; + _bb.join(this); + } + List tags_waiting_to_be_subscribed = _sec_to_main_subscription_request_queue.dequeueAll(); + foreach (object tag in tags_waiting_to_be_subscribed) { + _subsribed_tags[tag] = true; + object v = _bb.read(tag); + if (v != null) + _main_to_sec_callback_waiting_data_queue.enqueue(new Pair(tag, v)); + } + List> funcs_waiting_to_be_subscribed = _sec_to_main_subscription_func_request_queue.dequeueAll(); + if (funcs_waiting_to_be_subscribed != null && funcs_waiting_to_be_subscribed.Count > 0) { + _subsribed_tags_funcs.AddRange(funcs_waiting_to_be_subscribed); + foreach (object tag in _bb.getAllTags()) + foreach (Func f in funcs_waiting_to_be_subscribed) + if (f(tag)) + _main_to_sec_callback_waiting_data_queue.enqueue(new Pair(tag, _bb.read(tag))); + } + /// waiting write requests + List> data_to_be_written = _sec_to_main_write_request_queue.dequeueAll(); + foreach (Pair p in data_to_be_written) + _bb.write(p.first, p.second); + } else { + /// As long as its guaranteed that doWork wont be called after + /// the removeWorker, this _main_thread_active bool is superflous. + /// (Up until I verify that i am keeping this check here) + if (_main_thread_active) { + _main_thread_active = false; + _bb.leave(this); + _master_worker.removeWorker(this); + } + } + } + + private bool _main_thread_active = true; + + #region IAgent functions called in the main thread + + public void begin() { } + + public void change(object tag) { + if (_subsribed_tags.ContainsKey(tag)) + _main_to_sec_callback_waiting_data_queue.enqueue(new Pair(tag, _bb.read(tag))); + else { + foreach (Func f in _subsribed_tags_funcs) + if (f(tag)) + _main_to_sec_callback_waiting_data_queue.enqueue(new Pair(tag, _bb.read(tag))); + } + } + + public void commit(System.Collections.IDictionary changedTags) { } + + #endregion + + #endregion + } +} diff --git a/src/client/spark/NMSheets/Outside/TickConverter2.cs b/src/client/spark/NMSheets/Outside/TickConverter2.cs new file mode 100644 index 000000000..da4dac333 --- /dev/null +++ b/src/client/spark/NMSheets/Outside/TickConverter2.cs @@ -0,0 +1,535 @@ +using System; +using System.Collections; + +namespace BCG.Utilities.General +{ + public class TickConverter2 + { + // double has 15-16 digit precision, but double multiplication has less precision + // make the precision of fraction to 10 + private static readonly double myDoubleSignificant = 0.000000001; + private static readonly double myRoundfraction = 0.500000001; + private static readonly string myDecimalSeparator = "."; + private static readonly string myFractionSeparator = "-"; + + public class TickTypeInfo + { + public TickTypeInfo(bool isDecimal, int tickBase, double interval, bool dropZero) + { + this.isDecimal = isDecimal; + this.tickBase = tickBase; + this.interval = isDecimal ? interval / 100d : interval / tickBase; + this.dropZero = dropZero; + } + + public TickTypeInfo(bool isDecimal, int tickBase, double interval, bool dropZero, int numOfFractionalCharacters) : + this(isDecimal, tickBase, interval, dropZero) + { + this.numOfFractionalCharacters = numOfFractionalCharacters; + } + + public readonly bool isDecimal; + public readonly int tickBase; + public readonly double interval; + public readonly int numOfFractionalCharacters = -1; + public readonly bool dropZero; + } + + internal class TypeInfoMapping + { + public readonly TickType tickType; + public readonly TickTypeInfo tickTypeInfo; + public TypeInfoMapping(TickType t, TickTypeInfo i) + { + tickType = t; + tickTypeInfo = i; + } + } + + public enum TickType + { + tick8 = 0, + tick8_QuarterRound, + tick8_2Digits, + tick8_3Digits, + tick4, + tick16, + tick32, + tick64, + tickDecimal2Strike, + tickBondFuture, + tickBondFutureStrike, + tickBondOption, + + #region decimals + tickDecimal0, + tickDecimal1, + tickDecimal1_2Digits, + tickDecimal2, + tickDecimal3, + tickDecimal4, + tickDecimal5, + tickDecimal4_25, + tickDecimal2_05, + tickDecimal2_25, + tickDecimal2_50, + #endregion + + #region base 64 + tickBase64FullTick, //bond option prices + tickBase64OneTenthTick, //bond option theos + #endregion + + #region base 32 + tickBase32HalfTick, //bond futures prices (FV, TY) + tickBase32FullTick, + tickBase32FullTick_3Digits, //bond future prices (US) + tickBase32OneTenthTick, //bond future theos + #endregion + tickDecimal3_25 + }; + + internal static readonly TypeInfoMapping[] tickTypeInfoMapping = + { + new TypeInfoMapping(TickType.tick8, new TickTypeInfo(false, 80, 10.0d, false)), + new TypeInfoMapping(TickType.tick8_QuarterRound, new TickTypeInfo(false, 80, 20.0d, false)), + new TypeInfoMapping(TickType.tick8_2Digits, new TickTypeInfo(false, 80, 1, false)), + new TypeInfoMapping(TickType.tick8_3Digits, new TickTypeInfo(false, 80, 0.1d, false)), + new TypeInfoMapping(TickType.tick4, new TickTypeInfo(false, 40, 10.0d, false)), + new TypeInfoMapping(TickType.tick16, new TickTypeInfo(false, 16, 1.0d, false)), + new TypeInfoMapping(TickType.tick32, new TickTypeInfo(false, 32, 1.0d, false)), + new TypeInfoMapping(TickType.tick64, new TickTypeInfo(false, 64, 1.0d, false)), + new TypeInfoMapping(TickType.tickDecimal2Strike, new TickTypeInfo(true, 100, 1.0d, true)), + new TypeInfoMapping(TickType.tickBondFuture, new TickTypeInfo(false, 32, 0.1d, false)), + new TypeInfoMapping(TickType.tickBondFutureStrike, new TickTypeInfo(false, 32, 1.0d, true)), + new TypeInfoMapping(TickType.tickBondOption, new TickTypeInfo(false, 64, 0.1d, false)), + + new TypeInfoMapping(TickType.tickDecimal0, new TickTypeInfo(true, 100, 10.0d, true)), + new TypeInfoMapping(TickType.tickDecimal1, new TickTypeInfo(true, 100, 10.0d, false)), + new TypeInfoMapping(TickType.tickDecimal1_2Digits, new TickTypeInfo(true, 100, 10.0d, false, 2)), + new TypeInfoMapping(TickType.tickDecimal2, new TickTypeInfo(true, 100, 1.0d, false)), + new TypeInfoMapping(TickType.tickDecimal3, new TickTypeInfo(true, 100, 0.1d, false)), + new TypeInfoMapping(TickType.tickDecimal4, new TickTypeInfo(true, 100, 0.01d, false)), + new TypeInfoMapping(TickType.tickDecimal4_25, new TickTypeInfo(true, 100, 0.25d, false)), + new TypeInfoMapping(TickType.tickDecimal5, new TickTypeInfo (true, 100, 0.001d, false)), + new TypeInfoMapping(TickType.tickDecimal2_05, new TickTypeInfo(true, 100, 5.0d, false)), + new TypeInfoMapping(TickType.tickDecimal2_25, new TickTypeInfo(true, 100, 25.0d, false)), + new TypeInfoMapping(TickType.tickDecimal2_50, new TickTypeInfo(true, 100, 50.0d, false)), + new TypeInfoMapping(TickType.tickDecimal3_25, new TickTypeInfo(true, 100, 2.5d, false, 3)), + + new TypeInfoMapping(TickType.tickBase64FullTick, new TickTypeInfo (false, 64, 1, false)), + new TypeInfoMapping(TickType.tickBase64OneTenthTick, new TickTypeInfo (false, 64, 0.1d, false)), + + new TypeInfoMapping(TickType.tickBase32OneTenthTick, new TickTypeInfo (false, 32, 0.1d, false)), + new TypeInfoMapping(TickType.tickBase32FullTick, new TickTypeInfo (false, 32, 1.0d, false)), + new TypeInfoMapping(TickType.tickBase32FullTick_3Digits, new TickTypeInfo (false, 32, 1.0d, false, 3)), + new TypeInfoMapping(TickType.tickBase32HalfTick, new TickTypeInfo (false, 32, 0.5d, false)), + }; + + internal static Hashtable tickType2Info; + public static TickTypeInfo getTickTypeInfo(TickType t) + { + if (tickType2Info == null) + { + lock (typeof(TickConverter2)) + { + tickType2Info = new Hashtable(); + for (int i = 0; i < tickTypeInfoMapping.Length; i++) + { + tickType2Info[tickTypeInfoMapping[i].tickType] = tickTypeInfoMapping[i].tickTypeInfo; + } + } + } + return (TickTypeInfo)tickType2Info[t]; + } + + public TickConverter2() + { + } + + public static string get_separator(TickTypeInfo tt_info) + { + return tt_info.isDecimal ? myDecimalSeparator : myFractionSeparator; + } + + public static string getSeparator(TickType t) + { + TickTypeInfo info = getTickTypeInfo(t); + return info.isDecimal ? + myDecimalSeparator : + myFractionSeparator; + } + + public static string toTick(double d, int b) + { + //looks like this assumes tick_interval of 1 + //return TickTranslator.get_tick(d, b); + if (double.IsNaN(d)) + { + return double.NaN.ToString(); + } + else if (d == 0.0d) + { + return d.ToString(); + } + else if (b == 100) + { + return d.ToString(); + } + else + { + return to_tick(d, new TickTypeInfo(false, b, 1, false)); + } + } + + public static void to_tick(double new_price, TickTypeInfo tt_info, bool conform_to_tick, out string rounded_price_text, out double rounded_price) + { + //TickTranslator.get_tick_and_tick_rounded_value(new_price, tt_info.tickBase, tt_info.interval, out rounded_price, out rounded_price_text); + if (tt_info.isDecimal) + { + if (conform_to_tick) + { + rounded_price_text = to_tick(new_price, tt_info, out rounded_price); + } + else + { + /// Here we dont want to conform the new_price to tt_info's tickInterval. + /// Hence we create raw_tt_info which is like tt_info except the tickInterval + /// is small enough to not cause rounding + BCG.Utilities.General.TickConverter2.TickTypeInfo raw_tt_info = new BCG.Utilities.General.TickConverter2.TickTypeInfo(tt_info.isDecimal, tt_info.tickBase, 0.0000001d, true, -1); + rounded_price_text = to_tick(new_price, raw_tt_info, out rounded_price); + } + } + else + { + rounded_price_text = to_tick(new_price, tt_info, out rounded_price); + //_to_tick_non_decimal(new_price, tt_info, conform_to_tick, out rounded_price_text, out rounded_price); + } + } + + public static string to_tick(double d, TickType tt) + { + return to_tick(d, getTickTypeInfo(tt)); + } + + public static string to_tick(double d, TickTypeInfo info) + { + //return TickTranslator.get_tick(info.tickBase, (int)info.interval, d); + return info.isDecimal ? + formatDecimal(d, info.interval, info.dropZero, info.numOfFractionalCharacters) : + formatFraction(d, info.tickBase, info.interval, info.dropZero, info.numOfFractionalCharacters); + } + + public static string to_tick(double d, TickTypeInfo info, out double matching_value) + { + //string tick; + //TickTranslator.get_tick_and_tick_rounded_value(d, info.tickBase, info.interval, out matching_value, out tick); + return info.isDecimal ? + formatDecimal(d, info.interval, info.dropZero, info.numOfFractionalCharacters, out matching_value) : + formatFraction(d, info.tickBase, info.interval, info.dropZero, info.numOfFractionalCharacters, out matching_value); + } + + + public static string toTick(double d, TickType t) + { + //return TickTranslator.get_tick(d, info.tickBase, info.interval); + TickTypeInfo info = getTickTypeInfo(t); + + return info.isDecimal ? + formatDecimal(d, info.interval, info.dropZero, + info.numOfFractionalCharacters) : + formatFraction(d, info.tickBase, info.interval, + info.dropZero, info.numOfFractionalCharacters); + } + + public static string toTick(double d, TickType t, out double matchingValue) + { + //string tick; + //TickTranslator.get_tick_and_tick_rounded_value(d, info.tickBase, info.interval, out matchingValue, out tick); + TickTypeInfo info = getTickTypeInfo(t); + return info.isDecimal ? + formatDecimal(d, info.interval, info.dropZero, info.numOfFractionalCharacters, + out matchingValue) : + formatFraction(d, info.tickBase, info.interval, info.dropZero, info.numOfFractionalCharacters, + out matchingValue); + } + + public static double fromTick(string signedString, TickTypeInfo info) + { + //return TickTranslator.get_value(signedString, info.tickBase, info.interval); + if (signedString.Equals(double.NaN.ToString())) + { + return double.NaN; + } + + if (info.isDecimal) + { + return double.Parse(signedString); + } + + string s = signedString[0] == '-' ? + signedString.Substring(1, signedString.Length - 1) : + signedString; + + string intPart; + string fractionPart = string.Empty; + + int i = s.IndexOfAny(new char[] { '-' }); + if (i < 0) + { + intPart = s; + } + else + { + intPart = s.Substring(0, i); + fractionPart = s.Substring(i + 1, s.Length - i - 1); + } + + double fraction = 0.0; + if (fractionPart != string.Empty) + { + fraction = info.isDecimal ? + Convert.ToDouble(fractionPart) : + Convert.ToDouble(fractionPart) * 100.0d / info.tickBase; + + for (int fi = 0; fi < fractionPart.Length; fi++) + { + fraction /= 10.0d; + } + } + + double v = (intPart == string.Empty ? 0 : Convert.ToDouble(intPart)) + fraction; + + return signedString[0] == '-' ? -v : v; + } + + public static double fromTick(string signedString, TickType t) + { + //return TickTranslator.get_value(signedString, info.tickBase, info.interval) + TickTypeInfo info = getTickTypeInfo(t); + return TickConverter2.fromTick(signedString, info); + } + + private static string[] fractionFormats = new string[]{"f0", "f1", "f2", + "f3", "f4", "f5", + "f6", "f7", "f8", + "f9", "f10", "f11", + "f12", "f13", "f15"}; + + private static string[] dFractionFormats = new string[]{"D0", "D1", "D2", + "D3", "D4", "D5", + "D6", "D7", "D8", + "D9", "D10", "D11", + "D12", "D13", "D15"}; + + public static string formatDecimal(double signed, double interval, bool padding, + int numFractionalCharacters) + { + //return TickTranslator.get_tick(signed, tick_base, interval); + if (double.IsNaN(signed)) + { + return double.NaN.ToString(); + } + + double v = signed < 0 ? -signed : signed; + + int fs = numFractionalCharacters > 0 ? numFractionalCharacters : + myGetDecimalSpace(100, interval); + int round = myGetTickDecimalPoint(100, + fs); + + double outValue = + Math.Round((long)(v / interval + myRoundfraction) * interval, + round); + + outValue = v = signed < 0 ? -outValue : outValue; + + return padding ? outValue.ToString() : outValue.ToString(fractionFormats[fs]); + } + + public static string formatDecimal(double signed, double interval, bool padding, + int numFractionalCharacters, + out double outValue) + { + //string tick; + //TickTranslator.get_tick_and_rounded_value(signed, tick_base, interval, out tick, out outValue); + //return tick; + if (double.IsNaN(signed)) + { + outValue = double.NaN; + return double.NaN.ToString(); + } + + double v = signed < 0 ? -signed : signed; + + int fs = numFractionalCharacters > 0 ? numFractionalCharacters : + myGetDecimalSpace(100, interval); + int round = myGetTickDecimalPoint(100, + fs); + outValue = + Math.Round((long)(v / interval + myRoundfraction) * interval, + round); + outValue = v = signed < 0 ? -outValue : outValue; + + return padding ? outValue.ToString() : outValue.ToString(fractionFormats[fs]); + } + + public static string formatFraction(double signed, int b, double interval, bool dropZero, + int numFractionalCharacters) + { + //return TickTranslator.get_tick(interval, base, value) + if (double.IsNaN(signed)) + { + return double.NaN.ToString(); + } + + double v = signed < 0 ? -signed : signed; + + int fs = numFractionalCharacters > 0 ? numFractionalCharacters : + myGetDecimalSpace(b, interval); + + long intPart = (long)v; + + double fraction = v - intPart; + + double roundedFraction = (int)(fraction / interval + myRoundfraction) * interval; + + double fractionPart = roundedFraction * b; + + for (int i = 0; i < fs - 2; i++) + { + fractionPart *= 10.0d; + } + + return string.Concat( + signed < 0 && (intPart != 0 || fractionPart != 0) ? myFractionSeparator : "", + intPart.ToString(), + dropZero && fractionPart == 0 ? "" : + string.Concat(myFractionSeparator, ((int)fractionPart).ToString(dFractionFormats[fs]))); + } + + public static string formatFraction(double signed, int b, double interval, bool dropZero, + int numFractionalCharacters, + out double outValue) + { + //string tick; + //TickTranslator.get_tick_and_rounded_value(signed, b, interval, out tick, out outValue); + //return tick; + if (double.IsNaN(signed)) + { + outValue = double.NaN; + return double.NaN.ToString(); + } + + double v = signed < 0 ? -signed : signed; + + int fs = numFractionalCharacters > 0 ? numFractionalCharacters : + myGetDecimalSpace(b, interval); + int round = myGetTickDecimalPoint(b, fs); + + long intPart = (long)v; + + double fraction = v - intPart; + + double roundedFraction = (int)(fraction / interval + myRoundfraction) * interval; + + double fractionPart = roundedFraction * b; + + for (int i = 0; i < fs - 2; i++) + { + fractionPart *= 10.0d; + } + + outValue = Math.Round(intPart + roundedFraction, round); + + outValue = v = signed < 0 ? -outValue : outValue; + + return string.Concat( + signed < 0 && (intPart != 0 || fractionPart != 0) ? myFractionSeparator : "", + intPart.ToString(), + dropZero && fractionPart == 0 ? "" : + string.Concat(myFractionSeparator, ((int)fractionPart).ToString(dFractionFormats[fs]))); + } + + private static int myGetDecimalSpace(int b, double minInterval) + { + int r = b > 9 && b < 101 ? 2 : (int)(Math.Ceiling(Math.Log10(b)) + myRoundfraction); + + int s = 0; + double d = minInterval * b; + + if (b == 100 && d > 0.9999999999d) + { + for (int j = 0; j < 2; j++) + { + d = d / 10; + if (d - (int)d < myDoubleSignificant) + { + s--; + d = (int)d; + } + } + } + else + { + while (d < 0.9999999999d && d > myDoubleSignificant) + { + d = d * 10; + d = d - (int)d; + s++; + } + } + + return s + r; + } + + private static int myGetTickDecimalPoint(int tickbase, int numOfFractionalCharacters) + { + int b = int.MinValue; + + switch (tickbase) + { + case 8: + b = 3; //0.125 + b = b + numOfFractionalCharacters - 1; + break; + + case 16: + b = 4; //0.0625 + b = b + numOfFractionalCharacters - 2; + break; + + case 32: + b = 5; // 0.03125 + b = b + numOfFractionalCharacters - 2; + break; + + case 64: + b = 6; //0.015625 + b = b + numOfFractionalCharacters - 2; + break; + + case 80: + b = 4; //0.0125 + b = b + numOfFractionalCharacters - 2; + break; + + case 128: + b = 7; + b = b + numOfFractionalCharacters - 3; + break; + + case 100: + b = 2; + b = b + numOfFractionalCharacters - 2; + break; + + default: + throw new ApplicationException("unknown tickbase " + tickbase.ToString()); + } + + return b; + } + + } +} diff --git a/src/client/spark/NMSheets/Outside/TradeAndPositionTags.cs b/src/client/spark/NMSheets/Outside/TradeAndPositionTags.cs new file mode 100644 index 000000000..878a92aa6 --- /dev/null +++ b/src/client/spark/NMSheets/Outside/TradeAndPositionTags.cs @@ -0,0 +1,27 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace BCG { + public class TradeAndPositionTags { + /// + /// Tag for the complete position for one symbol, + /// for the account the logged in trader is supposed + /// to trade in + /// + public class OptionSymbolPositionTag : KeyedTag { public OptionSymbolPositionTag(string option_symbol) : base(option_symbol) { } } + + /// IEnumeraable of TradeLogUIRow for all the trades in the system + public class TradeLogTag : mbts.bb.EqualsHelper { public TradeLogTag() : base() { } } + + public class FutureSymbolPositionTag : KeyedTag { public FutureSymbolPositionTag(string future_symbol) : base(future_symbol) { } } + + /// Trades done today (after PNL RO) + public class DayTradesTag : mbts.bb.EqualsHelper { public DayTradesTag() : base() { } } + + /// Trades - Day Trades + public class PositionTradesTag : mbts.bb.EqualsHelper { public PositionTradesTag() : base() { } } + } +} diff --git a/src/client/spark/NMSheets/Outside/tc2/BidAsk/BidAskConfig.cs b/src/client/spark/NMSheets/Outside/tc2/BidAsk/BidAskConfig.cs new file mode 100644 index 000000000..8e2114c6a --- /dev/null +++ b/src/client/spark/NMSheets/Outside/tc2/BidAsk/BidAskConfig.cs @@ -0,0 +1,108 @@ +using System; +using System.Drawing; + +namespace BCG +{ + [Serializable] + public class BidAskConfig : ICloneable + { + public enum OrderType + { + OPG, + IOC, + Limit + } + + public BidAskConfig() {} + + public bool showMainFormBidAskColors = false; + public bool ShowMainFormBidAskColors + { + get {return showMainFormBidAskColors;} + set {showMainFormBidAskColors = value;} + } + + private OrderType myDefaultOrderType = OrderType.IOC; + public OrderType DefaultOrderType + { + get { return myDefaultOrderType; } + set { myDefaultOrderType = value; } + } + + private bool myDefaultAutoHedge = false; + public bool DefaultAutoHedge + { + get { return myDefaultAutoHedge; } + set { myDefaultAutoHedge = value; } + } + + private string _default_internal_account; + public string DefaultInternalAccount + { + get { return _default_internal_account; } + set { _default_internal_account = value; } + } + + private Nullable _default_order_size = 10; + public Nullable DefaultOrderSize + { + get { return _default_order_size; } + set { _default_order_size = (value == null ? 0 : value); } + } + + private string _carding_hedging_symbol_override = String.Empty; + public string CardingHedgingSymbolOverride + { + get { return _carding_hedging_symbol_override; } + set { _carding_hedging_symbol_override = value; } + } + + private Nullable _use_trade_price_for_ticker_orders = false; + public Nullable UseTradePriceForTickerOrders + { + get { return _use_trade_price_for_ticker_orders; } + set { _use_trade_price_for_ticker_orders = (value == null ? false : value); } + } + + private Nullable _direct_io_order_size = 0; + public Nullable DirectIOCOrderSize + { + get { return _direct_io_order_size; } + set { _direct_io_order_size = (value == null ? 0 : value); } + } + + private string _predefined_ee_edges = "0.25 0.5 0.75 1.0"; + public string PredefinedEEEdges + { + get { return _predefined_ee_edges; } + set { _predefined_ee_edges = value; } + } + + private string _predefined_ee_sizes = "1 5 10 20 25 50"; + public string PredefinedEESizes + { + get { return _predefined_ee_sizes; } + set { _predefined_ee_sizes = value; } + } + + private string _predefined_spread_ee_edges = "0.25 0.5 0.75 1.0"; + public string PredefinedSpreadEEEdges + { + get { return _predefined_spread_ee_edges; } + set { _predefined_spread_ee_edges = value; } + } + + private string _predefined_spread_ee_sizes = "1 5 10 20 25 50"; + public string PredefinedSpreadEESizes + { + get { return _predefined_spread_ee_sizes; } + set { _predefined_spread_ee_sizes = value; } + } + + #region ICloneable Members + + public object Clone() {return MemberwiseClone ();} + + #endregion + } +} diff --git a/src/client/spark/NMSheets/Outside/tc2/BidAsk/BidAskConfigTag.cs b/src/client/spark/NMSheets/Outside/tc2/BidAsk/BidAskConfigTag.cs new file mode 100644 index 000000000..794a738ce --- /dev/null +++ b/src/client/spark/NMSheets/Outside/tc2/BidAsk/BidAskConfigTag.cs @@ -0,0 +1,17 @@ +using System; + +namespace BCG +{ + /// + /// Maps to BidAskConfig. Denotes the grid + /// settings that should be used in the display of bid and asks + /// for a given product + /// + [Serializable] + public class BidAskConfigTag : ProductTag, IConfigTag + { + public BidAskConfigTag (string product) + : base (product) + {} + } +} diff --git a/src/client/spark/NMSheets/Outside/tc2/BlackboardStructure/BlackboardBusProvider.cs b/src/client/spark/NMSheets/Outside/tc2/BlackboardStructure/BlackboardBusProvider.cs new file mode 100644 index 000000000..2425c4646 --- /dev/null +++ b/src/client/spark/NMSheets/Outside/tc2/BlackboardStructure/BlackboardBusProvider.cs @@ -0,0 +1,107 @@ +// using System; +// using bts.api; +// using System.ComponentModel.Composition; +// using bts.api.analytics; +// using mbts.ui; +// using System.Reactive.Linq; +// using mbts.api; +// using System.Collections.Generic; +// using System.Windows; +// using mbts.bb; +// using System.Windows.Threading; + +// namespace BCG +// { +// // No need to export IProvider as this is created through the shell's CompositionContainer not the API one +// //[Export(typeof(IProvider))] +// [Export(typeof(IInitializable))] +// [ExportMetadata("name", "BlackboardBusProvider")] +// class BlackboardBusProvider : bts.api.data.ProviderBase, IInitializable +// { +// // Lazy is not required but is here because create_subscription() might never be called +// readonly Lazy _bb; + +// [ImportingConstructor] +// public BlackboardBusProvider(Lazy bb, IBus post, IComposer composer) : base(post) { +// _bb = bb; +// composer.register_provider(this); +// } +// public override string description { get { return "Bridge between Blackboard and Edge IBus"; } } + +// public override bool can_produce(bts.api.ITag tag) { +// return tag is IBlackboardTag; +// } + +// public override IObservable create_subscription(bts.api.ITag tag) { +// var bbtag = (IBlackboardTag)tag; +// return Observable.Create(observer => { +// return _bb.Value.subscribe(new BBSub(tag, value => { +// if (value is T) { +// observer.OnNext((T)value); +// } +// })); +// }); +// } + +// public void initialize() { +// } +// } + +// [Export(typeof(IBlackboardBus))] +// class BlackboardIBus : IBlackboardBus +// { +// private readonly Lazy _bb; +// private readonly IBus _bus; + +// [ImportingConstructor] +// public BlackboardIBus(IBus bus, Lazy blackboard) { +// _bus = bus; +// _bb = blackboard; +// Application.Current.Resources["Bus"] = bus; +// } + +// public void Dispose() { } + +// public string[] missing_pieces() { +// return _bus.missing_pieces(); +// } + +// public void post(bts.api.ITag tag, object data) { +// if (tag is IBlackboardTag) { +// Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Send, (Action)(() => { +// _bb.Value.write(tag, data); +// })); +// } +// else { +// _bus.post(tag, data); +// } +// } + +// public void post(bts.api.ITag tag, T data) { +// if (tag is IBlackboardTag) { +// Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Send, (Action)(() => { +// _bb.Value.write(tag, data); +// })); +// } +// else { +// _bus.post(tag, data); +// } +// } + +// public void report_error(string name, Exception e) { +// _bus.report_error(name, e); +// } + +// public void report_message(string msg) { +// _bus.report_message(msg); +// } + +// public ISubscription subscribe(bts.api.ITag tag, Type data_type) { +// return _bus.subscribe(tag, data_type); +// } + +// public ISubscription subscribe(bts.api.ITag tag) { +// return _bus.subscribe(tag); +// } +// } +// } diff --git a/src/client/spark/NMSheets/Outside/tc2/BlackboardStructure/BlackboardSetup.cs b/src/client/spark/NMSheets/Outside/tc2/BlackboardStructure/BlackboardSetup.cs new file mode 100644 index 000000000..6dd968480 --- /dev/null +++ b/src/client/spark/NMSheets/Outside/tc2/BlackboardStructure/BlackboardSetup.cs @@ -0,0 +1,168 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Windows.Forms; +using System.Diagnostics; + +using BCG; +using BCG.Utilities; +using BCG.Utilities.General; +using bts.api; + +namespace mbts.engine { + public struct SecuritySideKey : IEquatable { + public Side side; + public uint security_key; + + public int key { get { return side == Side.Buy ? (int)security_key : -(int)security_key; } } + + public SecuritySideKey(int key) { + security_key = Convert.ToUInt32(Math.Abs(key)); + side = key > 0 ? Side.Buy : Side.Sell; + } + + public SecuritySideKey(uint security_key, Side side) + : this(get_security_side_key(security_key, side)) { } + + public static int get_security_side_key(uint security_key, Side side) { + return side == Side.Buy ? (int)security_key : -1 * (int)security_key; + } + + public bool Equals(SecuritySideKey other) { + return other.security_key == security_key && other.side == side; + } + + public override bool Equals(object obj) { + return obj is SecuritySideKey && Equals((SecuritySideKey)obj); + } + + public override int GetHashCode() { + return key.GetHashCode(); + } + + public static bool operator ==(SecuritySideKey a, SecuritySideKey b) { + return a.Equals(b); + } + + public static bool operator !=(SecuritySideKey a, SecuritySideKey b) { + return !a.Equals(b); + } + } +} + +namespace BCG { + // [Export(typeof(mbts.ui.IInitializable))] + // public class BlackboardSetup : mbts.ui.IInitializable { + // private Blackboard _bb; + // private mbts.ui.ITimer _timer; + // private mbts.api.IBlackboardBus _bus; + // private readonly PubsubHub _hub; + // private readonly string _user; + // public static string current_user; + + // [ImportingConstructor()] + // public BlackboardSetup([Import("username")] string user, + // mbts.ui.ITimer timer, + // Blackboard bb, + // PubsubHub hub, + // mbts.api.IBlackboardBus bb_bus) { + // _timer = timer; + // _bb = bb; + // _user = user; + // current_user = user; + // _hub = hub; + // _bus = bb_bus; + // _init(user, hub); + // _timer.Tick += _on_timer_tick; + // } + + // private readonly TimeSpan _warn_time = TimeSpan.FromMilliseconds(500); + // private DateTime _last_mainloop_time = DateTime.MaxValue; + // private void _on_timer_tick() { + // MasterWorker.getInstance(false).doWork(); + // publish_host_info(_hub, current_user); + // TimeSpan this_period = DateTime.Now - _last_mainloop_time; + // if (this_period >= _warn_time) + // mbts.Logger.log(bts.log.Level.Warn, bts.log.Subsystem.gen, String.Format("Main Thread took {0} msecs", this_period.TotalMilliseconds)); + // _last_mainloop_time = DateTime.Now; + // } + + // private void _init(string user, PubsubHub hub) { + // // _bb.write(new TraderLoginTag(), user); + // // new ShellResourceAllocationKeeper(_bb, _bus, user); + // // new ShellLiveOptionTheosDispenser(_bb); + // // new SpreadSummaryForm (_bb); + // // new SpreadManager(_bb,user); + // // new SimpleOrderManager(_bb, user); + // // new SimpleTradeExecutioner(_bb); + // // new CBOEMMTNExecutioner(_bb, hub); + // // new SymbolExchangeAssociationSource(_bb); + // // new MessageDisplayAgent(_bb); + // // new NamesListProvider(_bb); + // // TradingStrip.TradingStripFactory.get_strip(); + // // new SpreadCalculationSynchronizer(_bb); + // // new SpreadBookRequestSynchronizer(_bb, user); + // // new ReportRequestSynchronizer(_bb); + // // new ElectronicTradingParameterSaver(_bb); + // // new OptionExpirationAgent(_bb, _timer); + // // new GeneralTradeTickerRequestSynchronizer(_bb); + // // new DirectOrderProcessor(_bb); + // // new OptionExpDataSource(_bb); + // // new ShellLiveFutureTheoDispenser(ViewStreamDatabase.instance, _bb); + // // new CBOETraderMMTNListSource(_bb, ViewStreamDatabase.instance, hub); + // // new VolSurfaceBlackboardManager(_bb, MasterWorker.getInstance(false), _bus); + // // new OptionOneFiveValueDispenser(_bb); + // // if(mbts.config.Configuration.get().use_edge_pubsub_theos) + // // new XGraphOptionMDProvider(_bb, _bus); + // } + + // #region Tradepad publishing + // private static DateTime _last_host_info_publish = DateTime.MinValue; + // private static bts.utils.HostInfo _host_info = null; + // private static string _host_info_topic = Guid.NewGuid().ToString(); + + // private static void publish_host_info(PubsubHub hub, string user) { + // if ((DateTime.Now - _last_host_info_publish).TotalSeconds > 20) { + // _last_host_info_publish = DateTime.Now; + // if (_host_info == null) { + // _host_info = new bts.utils.HostInfo(); + // try { + // _host_info = mbts.HostUtils.get_host_info(); + // _host_info.username = user; + // } catch (Exception) { } + // } + + // var lst = new List(); + // lst.Add(_host_info); + // hub.publish( + // String.Format("/ui/host_info/{0}", _host_info_topic), + // lst); + // } + // } + // #endregion + + // public int priority { + // get { return 0; } + // } + + + // public void initialize() { + // int count = 0; + // mbts.Logger.OnSystemCrashing += (msg, detail) => { + // try { + // var topic = string.Format("/crash/{0}/{1}/{2}", Environment.MachineName, Process.GetCurrentProcess().Id, ++count); + // _hub.publish(topic, new[] { + // new bts.utils.CrashDescription() { + // crash_timestamp = (ulong)mbts.DatetimeImports.ll_local_now(), + // host = Environment.MachineName, + // message = msg, + // details = detail.ToString() + // } + // }); + // } catch {/*try not to crash twice*/} + // // try to let the pubsub thread flush + // System.Threading.Thread.Sleep(1000); + // }; + // } + // } +} diff --git a/src/client/spark/NMSheets/Outside/tc2/BlackboardStructure/ConfigTags/IConfigTag.cs b/src/client/spark/NMSheets/Outside/tc2/BlackboardStructure/ConfigTags/IConfigTag.cs new file mode 100644 index 000000000..41f70bf22 --- /dev/null +++ b/src/client/spark/NMSheets/Outside/tc2/BlackboardStructure/ConfigTags/IConfigTag.cs @@ -0,0 +1,12 @@ +using System; +using BCG; +using BCG.Utilities; + +namespace BCG +{ + /// + /// Marker interface for all config items + /// + public interface IConfigTag + {} +} diff --git a/src/client/spark/NMSheets/Outside/tc2/BlackboardStructure/ConfigTags/TheoGridConfigTag.cs b/src/client/spark/NMSheets/Outside/tc2/BlackboardStructure/ConfigTags/TheoGridConfigTag.cs new file mode 100644 index 000000000..95ba63dce --- /dev/null +++ b/src/client/spark/NMSheets/Outside/tc2/BlackboardStructure/ConfigTags/TheoGridConfigTag.cs @@ -0,0 +1,19 @@ +using System; +using System.Runtime.Serialization; +using BCG; +using BCG.Utilities; + +namespace BCG +{ + /// + /// Maps to an object of type GridConfig. Denotes the grid + /// settings that should be used in the display of theos + /// for a given product + /// + [Serializable] + public class TheoGridConfigTag : ProductTag, IConfigTag + { + public TheoGridConfigTag (string product) :base(product) + {} + } +} diff --git a/src/client/spark/NMSheets/Outside/tc2/BlackboardStructure/ITag.cs b/src/client/spark/NMSheets/Outside/tc2/BlackboardStructure/ITag.cs new file mode 100644 index 000000000..365ce4a83 --- /dev/null +++ b/src/client/spark/NMSheets/Outside/tc2/BlackboardStructure/ITag.cs @@ -0,0 +1,6 @@ +using System; + +namespace BCG +{ + public interface ITag{} +} diff --git a/src/client/spark/NMSheets/Outside/tc2/BlackboardStructure/OneFiveValueTag.cs b/src/client/spark/NMSheets/Outside/tc2/BlackboardStructure/OneFiveValueTag.cs new file mode 100644 index 000000000..32076002b --- /dev/null +++ b/src/client/spark/NMSheets/Outside/tc2/BlackboardStructure/OneFiveValueTag.cs @@ -0,0 +1,12 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace BCG +{ + public class OneFiveValueTag : ProductTag + { + public OneFiveValueTag(string product) : base(product) { } + } +} diff --git a/src/client/spark/NMSheets/Outside/tc2/BlackboardStructure/ProductTag.cs b/src/client/spark/NMSheets/Outside/tc2/BlackboardStructure/ProductTag.cs new file mode 100644 index 000000000..29a962f35 --- /dev/null +++ b/src/client/spark/NMSheets/Outside/tc2/BlackboardStructure/ProductTag.cs @@ -0,0 +1,57 @@ +using System; +using System.IO; +using BCG; +using BCG.Utilities; + +namespace BCG +{ + [Serializable] + public abstract class ProductTag : ITag + { + private string myProduct; + + public static ProductTag make(Type t, string forSymbol) + { + return (ProductTag) + t.GetConstructor(new Type[] {typeof(string)}).Invoke(new object[]{forSymbol}); + } + + public ProductTag(string product) + { + myProduct = product; + } + + public string product + { + get + { + return myProduct; + } + } + + public override bool Equals(object obj) + { + return obj != null + && obj.GetType().Equals(this.GetType()) + && ((myProduct == null && (obj as ProductTag).myProduct == null) + || + ((myProduct != null && (obj as ProductTag).myProduct != null) + && + myProduct.Equals((obj as ProductTag).myProduct))); + } + + public override int GetHashCode() + { + if (myProduct == null) + return base.GetHashCode(); + else + return myProduct.GetHashCode(); + } + + public override string ToString() + { + return this.GetType().Name + (myProduct == null? "" : (" " + myProduct)); + } + } +} + \ No newline at end of file diff --git a/src/client/spark/NMSheets/Outside/tc2/Calculator2/MainForm/ATM/ATMData.cs b/src/client/spark/NMSheets/Outside/tc2/Calculator2/MainForm/ATM/ATMData.cs new file mode 100644 index 000000000..92cfe8808 --- /dev/null +++ b/src/client/spark/NMSheets/Outside/tc2/Calculator2/MainForm/ATM/ATMData.cs @@ -0,0 +1,97 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace BCG +{ + /// + /// Encapsultes the ATM greeks, for a single option_expiration. + /// Also includes the roll and fwd for that exp + /// + public class ATMData + { + public double roll_offset = Double.NaN, fwd = Double.NaN; + public Dictionary strike_vs_data = new Dictionary(); + public Dictionary> strike_vs_callput_bbo_mid = new Dictionary>(); + + public double get_md_midpoint_straddle(double strike) + { + Pair p = null; + if (strike_vs_callput_bbo_mid.TryGetValue(strike, out p)) + return p.first + p.second; + else + return Double.NaN; + } + + public double get_vol(double strike) + { + mbts.TheoPoint tp = null; + return strike_vs_data.TryGetValue(strike, out tp) ? tp.vol : Double.NaN; + } + + public mbts.TheoPoint get_atm_data_for_closest_strike_to_fwd() + { + double closest_to_fwd_strike = get_strike_closest_to_fwd(); + mbts.TheoPoint rv = null; + strike_vs_data.TryGetValue(closest_to_fwd_strike, out rv); + return rv; + } + + public double get_theo_straddle(double strike) + { + mbts.TheoPoint tp = null; + return strike_vs_data.TryGetValue(strike, out tp) ? tp.call + tp.put : Double.NaN; + } + + public double get_md_midpoint_straddle_minus_theo_straddle (double strike) + { + return get_md_midpoint_straddle(strike) - get_theo_straddle(strike); + } + + public double get_strike(bool closest) + { + double[] atm_strikes = strike_vs_data.Keys.ToArray(); + if (atm_strikes.Length == 0) + return Double.NaN; + else if (atm_strikes.Length == 1) + return atm_strikes[0]; + else + return Math.Abs(atm_strikes[0] - fwd) < Math.Abs(atm_strikes[1] - fwd) ? (closest ? atm_strikes[0] : atm_strikes[1]) : (closest ? atm_strikes[1] : atm_strikes[0]); + } + + public double get_strike_closest_to_fwd() { return get_strike(true); } + + public IEnumerable get_sorted_strikes() + { + List rv = new List(strike_vs_data.Keys); + rv.Sort(); + return rv; + } + + public void reduce_to_nearest_expiration() + { + if (strike_vs_data.Count > 1) + { + double furtherest_strike = get_strike(false); + if (strike_vs_data.ContainsKey(furtherest_strike)) + strike_vs_data.Remove(furtherest_strike); + } + } + + public static void reduce_to_nearest_expiration(Dictionary atmData) + { + foreach (ATMData d in atmData.Values) + d.reduce_to_nearest_expiration(); + } + + public static Dictionary> get_exp_strike_map(Dictionary atm_data_map) + { + Dictionary> rv = new Dictionary>(); + if (atm_data_map != null) + foreach (KeyValuePair p in atm_data_map) + rv.Add(p.Key, new List(p.Value.strike_vs_data.Keys)); + return rv; + } + } +} diff --git a/src/client/spark/NMSheets/Outside/tc2/Calculator2/MainForm/ATM/OptionATMDataSource.cs b/src/client/spark/NMSheets/Outside/tc2/Calculator2/MainForm/ATM/OptionATMDataSource.cs new file mode 100644 index 000000000..1da63134a --- /dev/null +++ b/src/client/spark/NMSheets/Outside/tc2/Calculator2/MainForm/ATM/OptionATMDataSource.cs @@ -0,0 +1,102 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +using BCG.Utilities; + +namespace BCG { + /// + /// Bunch of static funtions to deal with ATM + /// + public class OptionATMDataSource { + #region stateless helpers + internal static void fill_in_bbo(ref Dictionary atm_data_map, + ExpStrikeKeyedData> theo_data, + IDictionary bbo_data) { + foreach (KeyValuePair p in atm_data_map) { + DateTime exp = p.Key; + ATMData exp_atm_data = p.Value; + exp_atm_data.strike_vs_callput_bbo_mid = new Dictionary>(); + foreach (double k in exp_atm_data.strike_vs_data.Keys) { + Triplet tp = theo_data.get_data(exp, k) ?? new Triplet(null, 0, 0); + BBOPacket call_md, put_md; + bbo_data.TryGetValue(tp.second, out call_md); + bbo_data.TryGetValue(tp.third, out put_md); + double call_bid_price = BBOPacket.get_bid_price(call_md), + call_ask_price = BBOPacket.get_ask_price(call_md), + put_bid_price = BBOPacket.get_bid_price(put_md), + put_ask_price = BBOPacket.get_ask_price(put_md); + exp_atm_data.strike_vs_callput_bbo_mid[k] = new Pair((call_bid_price + call_ask_price) / 2, (put_bid_price + put_ask_price) / 2); + } + } + } + + internal static IDictionary compute_atm_data(string option_symbol, double one_five, ExpStrikeKeyedData theo_data, IDictionary opt_exp_rolls) { + IDictionary exp_vs_drivers = _get_computed_drivers(theo_data); + IDictionary rv = new Dictionary(); + if (one_five != 0) + foreach (DateTime exp in new List(exp_vs_drivers.Keys)) + exp_vs_drivers[exp] = (exp_vs_drivers[exp] - one_five) / 2.0; + foreach (DateTime exp in theo_data.get_expirations()) { + double exp_driver = 0.0; + exp_vs_drivers.TryGetValue(exp, out exp_driver); + rv[exp] = find_data_for_single_exp(exp_driver, exp, theo_data, opt_exp_rolls); + } + return rv; + } + + internal static Dictionary _get_computed_drivers(ExpStrikeKeyedData expStrikeTheos) { + Dictionary rv = new Dictionary(); + foreach (Triplet t in expStrikeTheos.get_data_linearly()) + if (!rv.ContainsKey(t.first)) + rv.Add(t.first, t.third.driver); + return rv; + } + + internal static ATMData find_data_for_single_exp(double driver_price, DateTime exp, + ExpStrikeKeyedData theo_data, IDictionary opt_exp_rolls) { + ATMData rv = new ATMData(); + IDictionary strike_theos = theo_data.get_data_for_single_exp(exp); + double roll = 0; // absent offset is 0 offset + if (opt_exp_rolls != null) + opt_exp_rolls.TryGetValue(exp, out roll); + double[] atm_strikes = find_atm_strikes_for_single_exp(driver_price, roll, strike_theos); + rv.roll_offset = roll; + rv.fwd = roll + driver_price; + foreach (double s in atm_strikes) { + rv.strike_vs_data.Add(s, strike_theos[s]); + } + return rv; + } + + internal static double[] find_atm_strikes_for_single_exp(double driver_price, double roll, IDictionary strike_theos) { + driver_price += roll; + double[] strikes = strike_theos.Keys.ToArray(); + Array.Sort(strikes); + return find_nearest_strike(strikes, driver_price); + } + + internal static double[] find_nearest_strike(double[] sorted_strikes, double driver_price) { + if (Double.IsNaN(driver_price)) + return new double[] { }; + else if (sorted_strikes.Length == 0) + return new double[] { }; + else if (driver_price <= sorted_strikes[0]) + return new double[] { sorted_strikes[0] }; + else if (driver_price >= sorted_strikes[sorted_strikes.Length - 1]) + return new double[] { sorted_strikes[sorted_strikes.Length - 1] }; + else if (sorted_strikes.Contains(driver_price)) + return new double[] { driver_price }; + else { + /// has to be sandwiched bw 2 strikes + for (int i = 0; i < sorted_strikes.Length - 1; i++) + if (driver_price >= sorted_strikes[i] && driver_price <= sorted_strikes[i + 1]) + return new double[] { sorted_strikes[i], sorted_strikes[i + 1] }; + } + bts.Log.assert(false); + return null; + } + #endregion + } +} diff --git a/src/client/spark/NMSheets/Outside/tc2/Calculator2/OptionSymbolContractParamaterSource.cs b/src/client/spark/NMSheets/Outside/tc2/Calculator2/OptionSymbolContractParamaterSource.cs new file mode 100644 index 000000000..f3b97cea2 --- /dev/null +++ b/src/client/spark/NMSheets/Outside/tc2/Calculator2/OptionSymbolContractParamaterSource.cs @@ -0,0 +1,14 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace BCG +{ + public class OptionSymbolTheoShiftTag : ProductTag + { + public OptionSymbolTheoShiftTag(string option_symbol) + : base(option_symbol) + { } + } +} diff --git a/src/client/spark/NMSheets/Outside/tc2/ClickTrading/BidAskAlert.cs b/src/client/spark/NMSheets/Outside/tc2/ClickTrading/BidAskAlert.cs new file mode 100644 index 000000000..05a4bdaec --- /dev/null +++ b/src/client/spark/NMSheets/Outside/tc2/ClickTrading/BidAskAlert.cs @@ -0,0 +1,12 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace BCG +{ + public enum SheetsAlertMode + { + SimpleCross, + Proximity + } +} diff --git a/src/client/spark/NMSheets/Outside/tc2/ClickTrading/ClickTradingFormLocationTag.cs b/src/client/spark/NMSheets/Outside/tc2/ClickTrading/ClickTradingFormLocationTag.cs new file mode 100644 index 000000000..521130148 --- /dev/null +++ b/src/client/spark/NMSheets/Outside/tc2/ClickTrading/ClickTradingFormLocationTag.cs @@ -0,0 +1,24 @@ +using mbts.bb; +using System; + +namespace BCG +{ + [Serializable] + public class ClickTradingFormLocationTag : ProductTag, IConfigTag + { + public ClickTradingFormLocationTag(string product) : base(product) { } + } + + [Serializable] + public class SpreadFormLocationTag : ProductTag, IConfigTag + { + public SpreadFormLocationTag(string product) : base(product) { } + } + + [Serializable] + public class FillAlertFormLocationTag : EqualsHelper, IConfigTag + { + public FillAlertFormLocationTag() : base() { } + } + +} diff --git a/src/client/spark/NMSheets/Outside/tc2/ClickTrading/InitialTradingSideHint.cs b/src/client/spark/NMSheets/Outside/tc2/ClickTrading/InitialTradingSideHint.cs new file mode 100644 index 000000000..7c7c4d782 --- /dev/null +++ b/src/client/spark/NMSheets/Outside/tc2/ClickTrading/InitialTradingSideHint.cs @@ -0,0 +1,30 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace BCG +{ + public enum InitialTradingSideHint + { + Buy, + Sell, + MostEdge + } + + public enum SpreadWindowMode + { + Click, + Card, + Greeks + } + + public class SpreadInititialState + { + public InitialTradingSideHint preset_trading_side; + public SpreadWindowMode preset_mode; + public Nullable preset_order_hint = null; + public double preset_price = Double.NaN; + public UInt32 preset_size = 0; + } +} diff --git a/src/client/spark/NMSheets/Outside/tc2/ExpirationBasedPrices/VolShifts/VolShiftTag.cs b/src/client/spark/NMSheets/Outside/tc2/ExpirationBasedPrices/VolShifts/VolShiftTag.cs new file mode 100644 index 000000000..3a972d296 --- /dev/null +++ b/src/client/spark/NMSheets/Outside/tc2/ExpirationBasedPrices/VolShifts/VolShiftTag.cs @@ -0,0 +1,18 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace BCG +{ + /// + /// Corresponding data is a dictionary of exps vs + /// their shifts. An absent expiration denotes a 0 vol shift + /// + public class VolShiftTag : ProductTag + { + public VolShiftTag(string product) + : base(product) + { } + } +} diff --git a/src/client/spark/NMSheets/Outside/tc2/GUI/BlueUpArrow.ico b/src/client/spark/NMSheets/Outside/tc2/GUI/BlueUpArrow.ico new file mode 100644 index 000000000..692002fc8 Binary files /dev/null and b/src/client/spark/NMSheets/Outside/tc2/GUI/BlueUpArrow.ico differ 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/DownArrow.ico b/src/client/spark/NMSheets/Outside/tc2/GUI/DownArrow.ico new file mode 100644 index 000000000..352e24321 Binary files /dev/null and b/src/client/spark/NMSheets/Outside/tc2/GUI/DownArrow.ico differ diff --git a/src/client/spark/NMSheets/Outside/tc2/GUI/FormConfig.cs b/src/client/spark/NMSheets/Outside/tc2/GUI/FormConfig.cs new file mode 100644 index 000000000..ab1e793b6 --- /dev/null +++ b/src/client/spark/NMSheets/Outside/tc2/GUI/FormConfig.cs @@ -0,0 +1,37 @@ +using System; +using System.Runtime.Serialization; + +using BCG; +using BCG.Utilities; + +namespace BCG +{ + [ProtoBuf.ProtoContract(Name="FormConfig")] + [Serializable] + public class FormConfig + { + public FormConfig() { width = -1; } + + [ProtoBuf.ProtoMember(2)] + public int left { get; set; } + + [ProtoBuf.ProtoMember(4)] + public int top { get; set; } + + [ProtoBuf.ProtoMember(6)] + public int height { get; set; } + + [ProtoBuf.ProtoMember(8)] + public int width { get; set; } + + public FormConfig(int left, int top, int height, int width) + {this.left = left;this.top = top; this.height= height; this.width= width;} + } + + [ProtoBuf.ProtoContract(Name="FormLocationWidthAndHeights")] + public class FormLocationWidthAndHeights + { + [ProtoBuf.ProtoMember(2)] + public FormConfig[] form_location_width_and_heights { get; set; } + } +} diff --git a/src/client/spark/NMSheets/Outside/tc2/GUI/GDI32BitWrapper.cs b/src/client/spark/NMSheets/Outside/tc2/GUI/GDI32BitWrapper.cs new file mode 100644 index 000000000..56cc7f3b2 --- /dev/null +++ b/src/client/spark/NMSheets/Outside/tc2/GUI/GDI32BitWrapper.cs @@ -0,0 +1,221 @@ +using System; +using System.Drawing; +using System.Runtime.InteropServices; + +namespace BCG { + public class GDI32BitWrapper : IGraphicsWrapper { + [StructLayout(LayoutKind.Sequential)] + public struct BLENDFUNCTION { + public byte BlendOp; + public byte BlendFlags; + public byte SourceConstantAlpha; + public byte AlphaFormat; + }; + + public readonly int SRCCOPY = 0xCC0020; + [DllImport("gdi32")] + public static extern int BitBlt(IntPtr hDestDC, + int x, int y, int nWidth, int nHeight, + IntPtr hSrcDC, int xSrc, int ySrc, int dwRop); + + [DllImport("gdi32")] public static extern IntPtr CreateCompatibleDC(IntPtr hDC); + [DllImport("gdi32")] + public static extern IntPtr CreateCompatibleBitmap(IntPtr hdc, + int nWidth, int nHeight); + [DllImport("gdi32")] public static extern int DeleteDC(IntPtr hDC); + [DllImport("gdi32")] + private static extern bool Rectangle( + IntPtr hdc, + int ulCornerX, int ulCornerY, + int lrCornerX, int lrCornerY); + [DllImport("gdi32")] private static extern int GetBkColor(IntPtr hDC); + [DllImport("gdi32")] private static extern int SetBkMode(IntPtr hdc, int bkMode); + [DllImport("gdi32")] private static extern int CreateSolidBrush(int crColor); + [DllImport("gdi32")] private static extern int SelectObject(IntPtr hDC, int hObject); + [DllImport("gdi32")] private static extern int DeleteObject(IntPtr bObject); + [DllImport("gdi32")] private static extern IntPtr SelectObject(IntPtr hDC, IntPtr hObject); + [DllImport("gdi32")] private static extern IntPtr CreatePen(int nPenStyle, int nWidth, int crColor); + [DllImport("gdi32")] private static extern int MoveToEx(IntPtr hDC, int x, int y, out Point lpPoint); + [DllImport("gdi32")] private static extern int LineTo(IntPtr hDC, int x, int y); + [DllImport("gdi32")] private static extern int SetTextAlign(IntPtr hDC, int wFlags); + [DllImport("gdi32")] private static extern int SetTextColor(IntPtr hDc, int crColor); + + [DllImport("Msimg32")] + private static extern int AlphaBlend(IntPtr hdcDest, int xoriginDest, int yoriginDest, int wDest, int hDest, + IntPtr hdcSrc, int xoriginSrc, int yoriginSrc, int wSrc, int hSrc, BLENDFUNCTION blendFunction); + + [DllImport("gdi32", EntryPoint = "TextOut")] private static extern int TextOutA(IntPtr hDC, int x, int y, string lpString, int nCount); + [DllImport("gdi32", EntryPoint = "GetTextExtentPoint32")] private static extern int GetTextExtentPoint32A(IntPtr hDC, string lpsz, int cbString, ref Size lpSize); + [DllImport("user32")] private static extern int FillRect(IntPtr hdc, ref Rectangle lpRect, int hBrush); + + private IntPtr myHDC = IntPtr.Zero; + private IntPtr myBitMap = IntPtr.Zero; + private IntPtr myFont = IntPtr.Zero; + private IntPtr myPen = IntPtr.Zero; + private IntPtr myBrush; + private int myWidth; + private int myHeight; + private Graphics _graphics; + + public GDI32BitWrapper(Graphics g, int bitMapWidth, int bitMapHeight) { + _graphics = g; + IntPtr tmpHDC = g.GetHdc(); + myHDC = CreateCompatibleDC(tmpHDC); + myWidth = bitMapWidth; + myHeight = bitMapHeight; + Random rnd = new Random(DateTime.Now.Millisecond); + for (int i = 0; i < 25; i++) { + myBitMap = CreateCompatibleBitmap(tmpHDC, myWidth, myHeight); + if (myBitMap == IntPtr.Zero) { + bts.Log.Ui.error("Failed to initialize BitMap", "Error"); + System.Threading.Thread.Sleep(rnd.Next(50, 250)); + } else + break; + } + initSettings(); + + SelectObject(myHDC, myBitMap); + g.ReleaseHdc(tmpHDC); + } + + public Graphics get_graphics() { return _graphics; } + + public int setBkMode(int bkMode) { + return SetBkMode(myHDC, bkMode); + } + + public static int toColorref(Color c) { + return c.R | c.G << 8 | c.B << 16; + } + + #region IDisposable Members + + public void Dispose() { + if (myFont != IntPtr.Zero) { + DeleteObject(myFont); + } + + if (myPen != IntPtr.Zero) { + DeleteObject(myPen); + } + + DeleteObject(myBitMap); + + DeleteDC(myHDC); + } + + #endregion + + #region IGraphicsWrapper Members + + public object createSolidBrush(Color c) { + return CreateSolidBrush(GDI32Wrapper.toColorref(c)); + } + + public object createPen(Color crColor) { + return CreatePen(0, 1, toColorref(crColor)); + } + + public object createPen(object nPenStyle, Color crColor) { + return CreatePen((int)nPenStyle, 1, toColorref(crColor)); + } + + public void initSettings() { + this.setBkMode(1); + } + + public void clear(Rectangle r, Color c) { + if (r.Equals(System.Drawing.Rectangle.Empty)) { + return; + } + + int colorref = GetBkColor(myHDC); + Rectangle nr = new Rectangle(r.Left, r.Top, r.Right, r.Bottom); + FillRect(myHDC, ref nr, CreateSolidBrush(colorref)); + } + + public void selectPen(object pen) { + if (myPen != IntPtr.Zero) { + DeleteObject(myPen); + } + myPen = (IntPtr)pen; + SelectObject(myHDC, myPen); + } + + public void selectFont(Font font) { + if (myFont != IntPtr.Zero) { + DeleteObject(myFont); + } + + myFont = font.ToHfont(); + SelectObject(myHDC, myFont); + } + + public void selectBrush(object brush) { + if (myBrush != IntPtr.Zero) { + DeleteObject(myBrush); + } + + myBrush = (IntPtr)((int)brush); + SelectObject(myHDC, myBrush); + } + + public void fillRectangle(int x0, int y0, int width, int height) { + Rectangle r = new Rectangle(x0, y0, x0 + width, y0 + height); + FillRect(myHDC, ref r, (int)myBrush); + } + + public void fillRectangle(Rectangle r) { + Rectangle r1 = new Rectangle(r.Left, r.Top, r.Right, r.Bottom); + FillRect(myHDC, ref r1, (int)myBrush); + } + + public void drawRectangle(Rectangle r) { + Rectangle(myHDC, r.Left, r.Top, r.Right, r.Bottom); + } + + public void drawRectangle(int x, int y, int width, int height) { + Rectangle(myHDC, x, y, x + width, y + height); + } + + public void drawLine(int x1, int y1, int x2, int y2) { + Point tmp; + MoveToEx(myHDC, x1, y1, out tmp); + LineTo(myHDC, x2, y2); + } + + public SizeF measureString(string s) { + Size size = new Size(0, 0); + //SelectObject(g, (IntPtr)fonts[s]); + GetTextExtentPoint32A(myHDC, s, s.Length, + ref size); + + return new SizeF(size.Width, size.Height); + } + + public void drawString(string s, float x, float y) { + TextOutA(myHDC, (int)x, (int)y, s, s.Length); + } + + public void setTextColor(Color c) { + SetTextColor(myHDC, toColorref(c)); + } + + public void paint(Graphics g, int sourceX, int sourceY, + int x, int y, int width, int height) { + IntPtr hdc = g.GetHdc(); + BitBlt(hdc, x, y, width, height, myHDC, sourceX, sourceY, SRCCOPY); + g.ReleaseHdc(hdc); + } + + public void set_text_align(int mask) { + SetTextAlign(myHDC, mask); + } + + public int alpha_blend(int xoriginDest, int yoriginDest, int wDest, int hDest, int xoriginSrc, int yoriginSrc, int wSrc, int hSrc, BLENDFUNCTION blendFunction) { + return AlphaBlend(myHDC, xoriginDest, yoriginDest, wDest, hDest, myHDC, xoriginSrc, yoriginSrc, wSrc, hSrc, blendFunction); + } + + #endregion + } +} diff --git a/src/client/spark/NMSheets/Outside/tc2/GUI/GDI32Wrapper.cs b/src/client/spark/NMSheets/Outside/tc2/GUI/GDI32Wrapper.cs new file mode 100644 index 000000000..a8218a43e --- /dev/null +++ b/src/client/spark/NMSheets/Outside/tc2/GUI/GDI32Wrapper.cs @@ -0,0 +1,221 @@ +using System; +using System.Drawing; +using System.Runtime.InteropServices; + +namespace BCG +{ + public class GDI32Wrapper : IGraphicsWrapper + { + private Graphics myGraphics; + private IntPtr myHDC; + private IntPtr myFont = IntPtr.Zero; + private IntPtr myPen = IntPtr.Zero; + private IntPtr myBrush = IntPtr.Zero; + + + [DllImport("gdi32")] private static extern bool Rectangle( + IntPtr hdc, + int ulCornerX, int ulCornerY, + int lrCornerX, int lrCornerY); + + [DllImport("gdi32")] private static extern int GetBkColor(IntPtr hDC); + [DllImport("gdi32")] private static extern int SetBkMode(IntPtr hdc, int bkMode); + [DllImport("gdi32")] private static extern IntPtr CreateSolidBrush(int crColor); + //[DllImport("gdi32")] private static extern int SelectObject(IntPtr hDC, int hObject); + [DllImport("gdi32")] private static extern int DeleteObject(IntPtr bObject); + //[DllImport("gdi32")] private static extern int DeleteObject(int bObject); + [DllImport("gdi32")] private static extern IntPtr SelectObject(IntPtr hDC, IntPtr hObject); + [DllImport("gdi32")] private static extern IntPtr CreatePen(int nPenStyle, int nWidth, int crColor); + [DllImport("gdi32")] private static extern int MoveToEx(IntPtr hDC, int x, int y, out Point lpPoint); + [DllImport("gdi32")] private static extern int LineTo(IntPtr hDC, int x, int y) ; + [DllImport("gdi32")] private static extern int SetTextAlign(IntPtr hDC, int wFlags); + [DllImport("gdi32")] private static extern int SetTextColor(IntPtr hDc, int crColor); + [DllImport("gdi32", EntryPoint="TextOut")] private static extern int TextOutA(IntPtr hDC, int x, int y, string lpString, int nCount) ; + [DllImport("gdi32", EntryPoint="GetTextExtentPoint32")] private static extern int GetTextExtentPoint32A(IntPtr hDC, string lpsz, int cbString, ref Size lpSize); + + [DllImport("user32")] private static extern int FillRect(IntPtr hdc, ref Rectangle lpRect, IntPtr hBrush); + + public GDI32Wrapper(Graphics g) + { + myGraphics = g; + myHDC = myGraphics.GetHdc(); + initSettings(); + } + + public IntPtr hDC + { + get + { + return myHDC; + } + } + + public int setBkMode(int bkMode) + { + return SetBkMode(myHDC, bkMode); + } + + public static int toColorref(Color c) + { + return c.R | c.G << 8 | c.B << 16; + } + + #region IDisposable Members + + public void Dispose() + { + if ( myFont != IntPtr.Zero ) + { + DeleteObject(myFont); + } + + if ( myPen != IntPtr.Zero ) + { + DeleteObject(myPen); + } + + if ( myBrush != IntPtr.Zero ) + { + DeleteObject(myBrush); + } + + myGraphics.ReleaseHdc(myHDC); + } + + #endregion + + #region IGraphicsWrapper Members + + public object createSolidBrush(Color c) + { + return CreateSolidBrush(GDI32Wrapper.toColorref(c)); + } + + public object createPen(Color crColor) + { + return CreatePen(0, 1, toColorref(crColor)); + } + + public object createPen(object nPenStyle, Color crColor) + { + return CreatePen((int)nPenStyle, 1, toColorref(crColor)); + } + + public void initSettings() + { + this.setBkMode(1); + } + + public void clear(Rectangle r, Color c) + { + if ( r.Equals(System.Drawing.Rectangle.Empty) ) + { + return; + } + + int colorref = GetBkColor(myHDC); + Rectangle nr = new Rectangle(r.Left, r.Top, r.Right, r.Bottom); + FillRect(myHDC, ref nr, CreateSolidBrush(colorref)); + } + + public void selectPen(object pen) + { + if (pen.Equals(myPen)) + return; + + if ( myPen != IntPtr.Zero) + { + DeleteObject(myPen); + } + myPen = (IntPtr)pen; + SelectObject(myHDC, myPen); + } + + public void selectFont(Font font) + { + if (font.Equals(myFont)) + return; + + if ( myFont != IntPtr.Zero) + { + DeleteObject(myFont); + } + + myFont = font.ToHfont(); + SelectObject(myHDC, myFont); + } + + public void selectBrush(object brush) + { + if ( myBrush != IntPtr.Zero ) + { + DeleteObject(myBrush); + } + + myBrush = (IntPtr)brush; + SelectObject(myHDC, myBrush); + } + + public void fillRectangle(int x0, int y0, int width, int height) + { + Rectangle r = new Rectangle(x0, y0, x0 + width, y0+height); + FillRect(myHDC, ref r, myBrush); + } + + public void fillRectangle(Rectangle r) + { + Rectangle r1 = new Rectangle(r.Left, r.Top, r.Right, r.Bottom); + FillRect(myHDC, ref r1, myBrush); + } + + public void drawRectangle(Rectangle r) + { + Rectangle(myHDC, r.Left, r.Top, r.Right, r.Bottom); + } + + public void drawRectangle(int x, int y, int width, int height) + { + Rectangle(myHDC, x, y, x+width, y+height); + } + + public void drawLine(int x1, int y1, int x2, int y2) + { + Point tmp; + MoveToEx(myHDC, x1, y1, out tmp); + LineTo(myHDC, x2, y2); + } + + public SizeF measureString(string s) + { + Size size = new Size(0,0); + //SelectObject(g, (IntPtr)fonts[s]); + GetTextExtentPoint32A(myHDC, s, s.Length, + ref size); + + return new SizeF(size.Width, size.Height); + } + + public void drawString(string s, float x, float y) + { + TextOutA(myHDC, (int)x, (int)y, s, s.Length); + } + + public void setTextColor(Color c) + { + SetTextColor(myHDC, toColorref(c)); + } + + public void paint(Graphics g, int sourceX, int souceY, + int x, int y, int width, int height){} + + public void set_text_align(int mask) + { + SetTextAlign(myHDC, mask); + } + + public Graphics get_graphics() { return myGraphics; } + + #endregion + + } +} diff --git a/src/client/spark/NMSheets/Outside/tc2/GUI/GDIPlusWrapper.cs b/src/client/spark/NMSheets/Outside/tc2/GUI/GDIPlusWrapper.cs new file mode 100644 index 000000000..fbfae5a08 --- /dev/null +++ b/src/client/spark/NMSheets/Outside/tc2/GUI/GDIPlusWrapper.cs @@ -0,0 +1,144 @@ +using System; +using System.Windows.Forms; +using System.Drawing; +using System.Drawing.Imaging; +using System.Drawing.Drawing2D; +using System.Collections; + +namespace BCG { + /// + /// Summary description for GDIPlusWrapper. + /// + public class GDIPlusWrapper : IGraphicsWrapper { + private Graphics myGraphics; + private Pen myPen = null; + private Font myFont = null; + private SolidBrush myBrush = null; + + private Hashtable myColor2SolidBrush = new Hashtable(); + + public GDIPlusWrapper(Graphics g) { + myGraphics = g; + initSettings(); + } + + private SolidBrush myGetSolidBrush(Color c) { + if (!myColor2SolidBrush.Contains(c)) { + myColor2SolidBrush[c] = new SolidBrush(c); + } + + return (SolidBrush)myColor2SolidBrush[c]; + } + + #region IGraphicsWrapper Members + + public void initSettings() { + myGraphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.SingleBitPerPixelGridFit; + myGraphics.PixelOffsetMode = PixelOffsetMode.Default; + myGraphics.SmoothingMode = SmoothingMode.Default; + myGraphics.CompositingQuality = CompositingQuality.Default; + } + + public object createSolidBrush(Color color) { + return new SolidBrush(color); + } + + public object createPen(Color c) { + return new Pen(c); + } + + public object createPen(object penStyle, Color c) { + Pen p = new Pen(c); + p.DashStyle = (System.Drawing.Drawing2D.DashStyle)penStyle; + return p; + } + + public void clear(Rectangle r, Color c) { + myGraphics.Clear(c); + } + + public void selectPen(object pen) { + if (myPen != null) { + myPen.Dispose(); + } + myPen = (Pen)pen; + } + + public void selectFont(Font f) { + if (myFont != null) { + myFont.Dispose(); + } + myFont = f; + } + + public void selectBrush(object solidBrush) { + if (myBrush != null) { + myBrush.Dispose(); + } + + myBrush = (SolidBrush)solidBrush; + } + + public void fillRectangle(Rectangle r) { + myGraphics.FillRectangle(myBrush, r.Left, r.Top, r.Width, r.Height); + } + + public void fillRectangle(int x, int y, int width, int height) { + myGraphics.FillRectangle(myBrush, x, y, width, height); + } + + public void drawRectangle(Rectangle r) { + myGraphics.DrawRectangle(myPen, + r.Left, r.Top, r.Width, r.Height); + } + + public void drawRectangle(int x, int y, int width, int height) { + myGraphics.DrawRectangle(myPen, + x, y, width, height); + } + + public void drawLine(int x1, int y1, int x2, int y2) { + myGraphics.DrawLine(myPen, x1, y1, x2, y2); + } + + public SizeF measureString(string s) { + return myGraphics.MeasureString(s, (Font)myFont); + } + + public void drawString(string s, float x, float y) { + myGraphics.DrawString(s, myFont, myBrush, x, y); + } + + public void setTextColor(Color c) { + selectBrush(new SolidBrush(c)); + } + + public void paint(Graphics g, int sourceX, int souceY, int x, int y, int width, int height) { } + + public void set_text_align(int mask) { + bts.Log.assert(false, "Not implemented"); + } + + public Graphics get_graphics() { return myGraphics; } + + #endregion + + #region IDisposable Members + + public void Dispose() { + if (myPen != null) { + myPen.Dispose(); + } + + if (myFont != null) { + myFont.Dispose(); + } + + if (myBrush != null) { + myBrush.Dispose(); + } + } + + #endregion + } +} diff --git a/src/client/spark/NMSheets/Outside/tc2/GUI/GridConfig.cs b/src/client/spark/NMSheets/Outside/tc2/GUI/GridConfig.cs new file mode 100644 index 000000000..dd819d76f --- /dev/null +++ b/src/client/spark/NMSheets/Outside/tc2/GUI/GridConfig.cs @@ -0,0 +1,862 @@ +using System; +using System.Windows.Forms; +using System.Drawing; +using System.Runtime.Serialization; + +using BCG; +using BCG.Utilities; + +namespace BCG +{ + public enum StraddleDisplayEnum + { + StraddleTheo, + StraddleTheoVsMarket + } + + [Serializable] + public class GridConfig : ICloneable + { + #region Background Colors + public Color CellHighlightColor + { + set { cellHighlightColor = value; } + get { return cellHighlightColor; } + } + public Color cellHighlightColor = Color.FromKnownColor(KnownColor.Yellow); + + public Color CellHighlightRectangleColor + { + set { cellHighlightRectangleColor = value; } + get { return cellHighlightRectangleColor; } + } + public Color cellHighlightRectangleColor = Color.FromKnownColor(KnownColor.Black); + + public Color ATMStrikeRowBackColor + { + set { atmStrikeRowBackColor = value; } + get { return atmStrikeRowBackColor; } + } + public Color atmStrikeRowBackColor = Color.Gray; + + public Color TheoBackColor + { + set { theoBackColor = value; } + get { return theoBackColor; } + } + public Color theoBackColor = Color.Azure; + + public Color DeltaBackColor + { + set { deltaBackColor = value; } + get { return deltaBackColor; } + } + public Color deltaBackColor = Color.Azure; + + public Color GammaBackColor + { + set { gammaBackColor = value; } + get { return gammaBackColor; } + } + public Color gammaBackColor = Color.Azure; + + public Color VegaBackColor + { + set { vegaBackColor = value; } + get { return vegaBackColor; } + } + public Color vegaBackColor = Color.Azure; + + public Color VolBackColor + { + set { volBackColor = value; } + get { return volBackColor; } + } + public Color volBackColor = Color.DimGray; + + public Color straddle_back_color = Color.LightGreen; + public Color StraddleBackColor + { + get { return straddle_back_color; } + set { straddle_back_color = value; } + } + public Color vol_change_back_color = Color.Olive; + public Color VolChangeBackColor + { + set { vol_change_back_color = value; } + get { return vol_change_back_color; } + } + + public Color MarketBidPriceBackColor + { + set { marketBidPriceBackColor = value; } + get { return marketBidPriceBackColor; } + } + public Color marketBidPriceBackColor = Color.LightBlue; + + public Color MarketBidSizeBackColor + { + set { marketBidSizeBackColor = value; } + get { return marketBidSizeBackColor; } + } + public Color marketBidSizeBackColor = Color.LightBlue; + + public Color MarketAskPriceBackColor + { + set { marketAskPriceBackColor = value; } + get { return marketAskPriceBackColor; } + } + public Color marketAskPriceBackColor = Color.LightBlue; + + public Color MarketAskSizeBackColor + { + set { marketAskSizeBackColor = value; } + get { return marketAskSizeBackColor; } + } + public Color marketAskSizeBackColor = Color.LightBlue; + + public Color StrikeBackColor + { + get { return strikeBackColor; } + set { strikeBackColor = value; } + } + public Color strikeBackColor = Color.Black; + + public Color HeaderBackgroundColor + { + set { headerBackColor = value; } + get { return headerBackColor; } + } + public Color headerBackColor = Color.RoyalBlue; + + private SheetsAlertMode _alert_mode = SheetsAlertMode.SimpleCross; + public SheetsAlertMode AlertMode + { + get { return _alert_mode; } + set { _alert_mode = value; } + } + + private Color _proximity_almost_color = Color.Yellow; + public Color ProximityAlmostColor + { + get { return _proximity_almost_color; } + set { _proximity_almost_color = value; } + } + + private Color _proximity_cross_color = Color.Red; + public Color ProximityCrossColor + { + get { return _proximity_cross_color; } + set { _proximity_cross_color = value; } + } + + public Color BuyAlertColor + { + get { return buyAlertColor; } + set { buyAlertColor = value; } + } + public Color buyAlertColor = Color.GreenYellow; + + public Color SellAlertColor + { + get { return sellAlertColor; } + set { sellAlertColor = value; } + } + public Color sellAlertColor = Color.Red; + + public Color position_back_color = Color.SteelBlue; + public Color PositionBackColor + { + get { return position_back_color; } + set { position_back_color = value; } + } + + public Color shift_back_color = Color.Azure; + public Color ShiftBackColor + { + get { return shift_back_color; } + set { shift_back_color = value; } + } + + public Color shifted_theo_back_color = Color.Azure; + public Color ShiftedTheoBackColor + { + get { return shifted_theo_back_color; } + set { shifted_theo_back_color = value; } + } + + public Color quoting_bid_edge_back_color = Color.Pink; + public Color QuotingBidEdgeBackColor + { + get { return quoting_bid_edge_back_color; } + set { quoting_bid_edge_back_color = value; } + } + + public Color quoting_ask_edge_back_color = Color.Pink; + public Color QuotingAskEdgeBackColor + { + get { return quoting_ask_edge_back_color; } + set { quoting_ask_edge_back_color = value; } + } + + private Color _presave_theo_back_color = Color.LightBlue; + public Color PresaveTheoBackColor + { + get { return _presave_theo_back_color; } + set { _presave_theo_back_color = value; } + } + + private Color _presave_theo_diff_back_color = Color.LightBlue; + public Color PresaveTheoDiffBackColor + { + get { return _presave_theo_diff_back_color; } + set { _presave_theo_diff_back_color = value; } + } + + private Color _standard_strike_back_color = Color.LightBlue; + public Color StandardStrikeBackColor + { + get { return _standard_strike_back_color; } + set { _standard_strike_back_color = value; } + } + + #endregion + + #region Font Colors + + public Color HeaderFontColor + { + set { headerFontColor = value; } + get { return headerFontColor; } + } + public Color headerFontColor = Color.White; + + public Color TheoFontColor + { + set { theoFontColor = value; } + get { return theoFontColor; } + } + public Color theoFontColor = Color.Black; + + public Color DeltaFontColor + { + set { deltaFontColor = value; } + get { return deltaFontColor; } + } + public Color deltaFontColor = Color.Black; + + public Color GammaFontColor + { + set { gammaFontColor = value; } + get { return gammaFontColor; } + } + public Color gammaFontColor = Color.Black; + + public Color VegaFontColor + { + set { vegaFontColor = value; } + get { return vegaFontColor; } + } + public Color vegaFontColor = Color.Black; + + public Color VolFontColor + { + set { volFontColor = value; } + get { return volFontColor; } + } + public Color volFontColor = Color.Yellow; + + public Color straddle_font_color = Color.Navy; + public Color StraddleFontColor + { + set { straddle_font_color = value; } + get { return straddle_font_color; } + } + + public Color vol_change_font_color = Color.Yellow; + public Color VolChangeFontColor + { + set { vol_change_font_color = value; } + get { return vol_change_font_color; } + } + + public Color StrikeFontColor + { + set { strikeFontColor = value; } + get { return strikeFontColor; } + } + public Color strikeFontColor = Color.White; + + public Color MarketBidPriceFontColor + { + set { marketBidPriceFontColor = value; } + get { return marketBidPriceFontColor; } + } + public Color marketBidPriceFontColor = Color.Blue; + + public Color MarketBidSizeFontColor + { + set { marketBidSizeFontColor = value; } + get { return marketBidSizeFontColor; } + } + public Color marketBidSizeFontColor = Color.Blue; + + public Color MarketAskPriceFontColor + { + set { marketAskPriceFontColor = value; } + get { return marketAskPriceFontColor; } + } + public Color marketAskPriceFontColor = Color.Red; + + public Color MarketAskSizeFontColor + { + set { marketAskSizeFontColor = value; } + get { return marketAskSizeFontColor; } + } + public Color marketAskSizeFontColor = Color.Red; + + public Color position_font_color = Color.Black; + public Color PositionFontColor + { + get { return position_font_color; } + set { position_font_color = value; } + } + + public Color shift_font_color = Color.Navy; + public Color ShiftFontColor + { + get { return shift_font_color; } + set { shift_font_color = value; } + } + + public Color shifted_theo_font_color = Color.Navy; + public Color ShiftedTheoFontColor + { + get { return shifted_theo_font_color; } + set { shifted_theo_font_color = value; } + } + + public Color quoting_bid_edge_font_color = Color.Blue; + public Color QuotingBidEdgeFontColor + { + get { return quoting_bid_edge_font_color; } + set { quoting_bid_edge_font_color = value; } + } + + public Color quoting_ask_edge_font_color = Color.Red; + public Color QuotingAskEdgeFontColor + { + get { return quoting_ask_edge_font_color; } + set { quoting_ask_edge_font_color = value; } + } + + private Color _presave_theo_font_color = Color.Black; + public Color PresaveTheoFontColor + { + get { return _presave_theo_font_color; } + set { _presave_theo_font_color = value; } + } + + private Color _presave_theo_diff_font_color = Color.Black; + public Color PresaveTheoDiffFontColor + { + get { return _presave_theo_diff_font_color; } + set { _presave_theo_diff_font_color = value; } + } + + private Color _standard_strike_font_color = Color.Black; + public Color StandardStrikeFontColor + { + get { return _standard_strike_font_color; } + set { _standard_strike_font_color = value; } + } + + #endregion + + #region Grid Line Colors + + public Color RowSeparatorLineColor + { + set { lineColor = value; } + get { return lineColor; } + } + public Color lineColor = Color.Gray; + + private Color _expiration_seperator_linecolor = Color.Black; + public Color ExpirationSeperatorLineColor + { + get { return _expiration_seperator_linecolor; } + set { _expiration_seperator_linecolor = value; } + } + + + #endregion + + #region Fonts + + public Font TheoFont + { + set { theoFont = value; } + get { return theoFont; } + } + public Font theoFont = new Font("Tahoma", 8, FontStyle.Bold); + + public Font DeltaFont + { + set { deltaFont = value; } + get { return deltaFont; } + } + public Font deltaFont = new Font("Tahoma", 7); + + public Font GammaFont + { + set { gammaFont = (value == null ? new Font("Tahoma", 7) : value); } + get { return gammaFont; } + } + public Font gammaFont = new Font("Tahoma", 7); + + public Font VegaFont + { + set { vegaFont = (value == null ? new Font("Tahoma", 7) : value); } + get { return vegaFont; } + } + public Font vegaFont = new Font("Tahoma", 7); + + public Font VolFont + { + set { volFont = (value == null ? new Font("Tahoma", 7) : value); } + get { return volFont; } + } + public Font volFont = new Font("Tahoma", 7); + + public Font vol_change_font = new Font("Tahoma", 7); + public Font VolChangeFont + { + set { vol_change_font = (value == null ? new Font("Tahoma", 7) : value); } + get { return vol_change_font; } + } + + public Font straddle_font = new Font("Tahoma", 7); + public Font StraddleFont + { + set { straddle_font = value; } + get { return straddle_font; } + } + + public Font StrikeFont + { + set { strikeFont = value; } + get { return strikeFont; } + } + public Font strikeFont = new Font("Tahoma", 8, FontStyle.Bold); + + public Font MarketBidPriceFont + { + set { marketBidPriceFont = value; } + get { return marketBidPriceFont; } + } + public Font marketBidPriceFont = new Font("Tahoma", 8); + + public Font MarketAskPriceFont + { + set { marketAskPriceFont = value; } + get { return marketAskPriceFont; } + } + public Font marketAskPriceFont = new Font("Tahoma", 8); + + public Font MarketBidSizeFont + { + set { marketBidSizeFont = value; } + get { return marketBidSizeFont; } + } + public Font marketBidSizeFont = new Font("Tahoma", 7); + + public Font MarketAskSizeFont + { + set { marketAskSizeFont = value; } + get { return marketAskSizeFont; } + } + public Font marketAskSizeFont = new Font("Tahoma", 7); + + public Font position_font = new Font("Tahoma", 7); + public Font PositionFont + { + get { return position_font; } + set { position_font = value; } + } + + public Font shift_font = new Font("Tahoma", 7); + public Font ShiftFont + { + get { return shift_font; } + set { shift_font = value; } + } + + public Font shifted_theo_font = new Font("Tahoma", 7); + public Font ShiftedTheoFont + { + get { return shifted_theo_font; } + set { shifted_theo_font = value; } + } + + public Font quoting_bid_edge_font = new Font("Tahoma", 7, FontStyle.Italic); + public Font QuotingBidEdgeFont + { + get { return quoting_bid_edge_font; } + set { quoting_bid_edge_font = value; } + } + + public Font quoting_ask_edge_font = new Font("Tahoma", 7, FontStyle.Italic); + public Font QuotingAskEdgeFont + { + get { return quoting_ask_edge_font; } + set { quoting_ask_edge_font = value; } + } + + public Font HeaderFont + { + set { headerFont = value; } + get { return headerFont; } + } + public Font headerFont = new Font("Tahoma", 8); + + private Font _presave_theo_font = new Font("Tahoma", 8); + public Font PresaveTheoFont + { + get { return _presave_theo_font; } + set { _presave_theo_font = value; } + } + + private Font _presave_theo_diff_font = new Font("Tahoma", 7); + public Font PresaveTheoDiffFont + { + get { return _presave_theo_diff_font; } + set { _presave_theo_diff_font = value; } + } + + private Font _standard_strike_font = new Font("Tahoma", 7); + public Font StandardStrikeFont + { + get { return _standard_strike_font; } + set { _standard_strike_font = value; } + } + + #endregion + + private bool myATMNearestStrikeOnly = false; + public bool ATMNearestStrikeOnly + { + get { return myATMNearestStrikeOnly; } + set { myATMNearestStrikeOnly = value; } + } + + public int HeaderVerticalPadding + { + set { headerVPadding = value; } + get { return headerVPadding; } + } + public int headerVPadding = 1; + + public bool DrawRowSeparatorLine + { + set { drawLine = value; } + get { return drawLine; } + } + public bool drawLine = true; + + public int HorizontalPadding + { + set { hPadding = value; } + get { return hPadding; } + } + public int hPadding = 1; + + public int VerticalPadding + { + set { vPadding = value; } + get { return vPadding; } + } + public int vPadding = 2; + + public int HorizontalScrollStep + { + set { hScrollStep = value; } + get { return hScrollStep; } + } + public int hScrollStep = 50; + + public int VerticalScrollStep + { + set { vScrollStep = value; } + get { return vScrollStep; } + } + public int vScrollStep = 100; + + public int distanceForPage = 50; + public int distanceForCell = 10; + + public bool TrackMotion + { + set { trackMotion = value; } + get { return trackMotion; } + } + public bool trackMotion = true; + + public int ScrollPerSecond + { + set { scrollPerSecond = value; } + get { return scrollPerSecond; } + } + public int scrollPerSecond = 1000; + + public int SpeedThreshhold + { + set { speedThreshhold = value; } + get { return speedThreshhold; } + } + public int speedThreshhold = 10; + + public int DistanceThreshhold + { + set { distanceThreshhold = value; } + get { return distanceThreshhold; } + } + public int distanceThreshhold = 10; + + public bool ShowMarketData + { + set { showMarketData = value; } + get { return showMarketData; } + } + public bool showMarketData = true; + + private Nullable _show_marketdata_size = null; + public Nullable ShowMarketDataSize + { + get {return _show_marketdata_size;} + set { _show_marketdata_size = value; } + } + + public bool show_position = false; + public bool ShowPosition + { + set { show_position = value; } + get { return show_position; } + } + + public bool show_quoting_edges = false; + public bool ShowQuotingEdges + { + get { return show_quoting_edges; } + set { show_quoting_edges = value; } + } + + public bool show_shift = false; + public bool ShowShift + { + get { return show_shift; } + set + { + show_shift = String.IsNullOrEmpty (TC2Settings.instance.TheoShiftColumnName) ? false : value; + } + } + + public bool show_shifted_theo = false; + public bool ShowShiftedTheo + { + get { return show_shifted_theo; } + set + { + show_shifted_theo = String.IsNullOrEmpty(TC2Settings.instance.TheoShiftColumnName) ? false : value; + } + } + + public bool show_straddle = true; + public bool ShowStraddle + { + get { return show_straddle; } + set {show_straddle = value;} + } + + private int _input_change_flash_period_seconds = 10; + public int InputChangeFlashPeriodSeconds + { + set { _input_change_flash_period_seconds = value; } + get { return _input_change_flash_period_seconds; } + } + + private Nullable _show_theo = true; + public Nullable ShowTheo + { + get { return _show_theo; } + set + { + _show_theo = value == null ? false : value; + } + } + + private Nullable _show_delta = true; + public Nullable ShowDelta + { + get { return _show_delta; } + set + { + _show_delta = value == null ? false : value; + } + } + + private bool myShowGamma = true; + public bool ShowGamma + { + set { myShowGamma = value; } + get { return myShowGamma; } + } + + private bool myShowVega = true; + public bool ShowVega + { + set { myShowVega = value; } + get { return myShowVega; } + } + + private bool myShowVol = true; + public bool ShowVol + { + set { myShowVol = value; } + get { return myShowVol; } + } + + private bool _show_vol_change = false; + public bool ShowVolChange + { + set { _show_vol_change = value; } + get { return _show_vol_change; } + } + + private Nullable _show_presave_theos = false; + public Nullable ShowPreSaveTheos + { + get { return _show_presave_theos == null ? false : _show_presave_theos.Value; } + set { _show_presave_theos = value == null ? false : value.Value; } + } + + private Nullable _show_presave_theos_diff = false; + public Nullable ShowPreSaveTheosDiff + { + get { return _show_presave_theos_diff == null ? false : _show_presave_theos_diff.Value; } + set { _show_presave_theos_diff = value == null ? false : value.Value; } + } + + private Nullable _show_standard_strike = false; + public Nullable ShowStandardStrike + { + get { return _show_standard_strike == null ? false : _show_standard_strike.Value; } + set { _show_standard_strike = value == null ? false : value.Value; } + } + + private bool _expandTradingStrip = false; + public bool ExpandTradingStrip + { + get { return _expandTradingStrip; } + set { _expandTradingStrip = value; } + } + + private Nullable _grid_paint_throttle_ms = 333; + public Nullable GridPaintThrottleMs + { + get { return _grid_paint_throttle_ms; } + set { _grid_paint_throttle_ms = (value == null ? 0 : value); } + } + + private Nullable _driver_mult = 1.0; + public Nullable DriverMult + { + get { return _driver_mult; } + set { _driver_mult = (value == null ? 1.0 : value); } + } + + private string _theotime_symbol = String.Empty; + public string TheoTimeSymbol + { + get { return _theotime_symbol; } + set { _theotime_symbol = value; } + } + + private Nullable _straddle_display = StraddleDisplayEnum.StraddleTheo; + public Nullable StraddleDisplay + { + get { return _straddle_display.HasValue ? _straddle_display.Value : StraddleDisplayEnum.StraddleTheo; } + set { _straddle_display = (value.HasValue ? value.Value : StraddleDisplayEnum.StraddleTheo); } + } + + private Nullable _straddle_theo_vs_market_negative_back_color = Color.Pink; + public Nullable StraddleTheoVsMarketNegativeBackColor + { + get { return _straddle_theo_vs_market_negative_back_color.HasValue ? _straddle_theo_vs_market_negative_back_color.Value : Color.Pink; } + set { _straddle_theo_vs_market_negative_back_color = value.HasValue ? value.Value : Color.Pink; } + } + + private Nullable _straddle_theo_vs_market_negative_font_color = Color.Black; + public Nullable StraddleTheoVsMarketNegativeFontColor + { + get { return _straddle_theo_vs_market_negative_font_color.HasValue ? _straddle_theo_vs_market_negative_font_color.Value : Color.Black; } + set { _straddle_theo_vs_market_negative_font_color = value.HasValue ? value.Value : Color.Black; } + } + + private Nullable _straddle_theo_vs_market_positive_back_color = Color.LightGreen; + public Nullable StraddleTheoVsMarketPositiveBackColor + { + get { return _straddle_theo_vs_market_positive_back_color.HasValue ? _straddle_theo_vs_market_positive_back_color.Value : Color.LightGreen; } + set { _straddle_theo_vs_market_positive_back_color = value.HasValue ? value.Value : Color.LightGreen; } + } + + private Nullable _straddle_theo_vs_market_positive_font_color = Color.Black; + public Nullable StraddleTheoVsMarketPositiveFontColor + { + get { return _straddle_theo_vs_market_positive_font_color.HasValue ? _straddle_theo_vs_market_positive_font_color.Value : Color.Black; } + set { _straddle_theo_vs_market_positive_font_color = value.HasValue ? value.Value : Color.Black; } + } + + private Nullable _show_vol_shift_control_in_expiration_header = true; + public Nullable ShowVolShiftControlInExpirationHeader + { + get { return _show_vol_shift_control_in_expiration_header.HasValue ? _show_vol_shift_control_in_expiration_header.Value : true; } + set { _show_vol_shift_control_in_expiration_header = value.HasValue ? value.Value : true; } + } + + public static GridConfig change_font_size(GridConfig gc, float size_change, float floor, float ceil) + { + GridConfig rv = gc.Clone () as GridConfig; + foreach (System.Reflection.PropertyInfo pi in gc.GetType().GetProperties()) + { + if (pi.CanRead && pi.CanWrite) + { + object property_val = pi.GetValue(gc, null); + Type property_type = pi.PropertyType; + + if (property_type.Equals(typeof(System.Drawing.Font))) + { + Font orig_font = property_val as Font; + Font new_font = CommonGUIUtilities.change_font_size (orig_font, size_change, floor, ceil); + if (orig_font.Size == new_font.Size) + /// this will only happen if the ceil or floor prevented + /// a font from changing size. In that case we wont + /// change the font size for anything. + return gc; + pi.SetValue(rv, new_font); + } + } + } + return rv; + } + + #region ICloneable Members + + public object Clone() + { + return MemberwiseClone(); + } + + #endregion + } +} diff --git a/src/client/spark/NMSheets/Outside/tc2/GUI/GuiChange.cs b/src/client/spark/NMSheets/Outside/tc2/GUI/GuiChange.cs new file mode 100644 index 000000000..258d8e5a2 --- /dev/null +++ b/src/client/spark/NMSheets/Outside/tc2/GUI/GuiChange.cs @@ -0,0 +1,10 @@ +using System; +using BCG; +using BCG.Utilities; + +namespace BCG +{ + public delegate void GUIChange (object sender, object value); + +// public delegate void PokeDelegate(); +} diff --git a/src/client/spark/NMSheets/Outside/tc2/GUI/IGraphicsWrapper.cs b/src/client/spark/NMSheets/Outside/tc2/GUI/IGraphicsWrapper.cs new file mode 100644 index 000000000..45a855ace --- /dev/null +++ b/src/client/spark/NMSheets/Outside/tc2/GUI/IGraphicsWrapper.cs @@ -0,0 +1,29 @@ +using System; +using System.Drawing; + +namespace BCG +{ + public interface IGraphicsWrapper : IDisposable + { + object createSolidBrush(Color color); + object createPen(object penStyle, Color c); + object createPen(Color c); + + void initSettings(); + void clear(Rectangle r, Color c); + void selectPen(object pen); + void selectFont(Font font); + void selectBrush(object brush); + void fillRectangle(Rectangle r); + void fillRectangle(int x, int y, int width, int height); + void drawRectangle(Rectangle r); + void drawRectangle(int x, int y, int width, int height); + void drawLine(int x1, int y1, int x2, int y2); + SizeF measureString(string s); + void drawString(string s, float x, float y); + void paint(Graphics g, int sourceX, int souceY, int x, int y, int width, int height); + void setTextColor(Color c); + void set_text_align(int mask); + Graphics get_graphics(); + } +} diff --git a/src/client/spark/NMSheets/Outside/tc2/GUI/ITheoFormatter.cs b/src/client/spark/NMSheets/Outside/tc2/GUI/ITheoFormatter.cs new file mode 100644 index 000000000..835646adf --- /dev/null +++ b/src/client/spark/NMSheets/Outside/tc2/GUI/ITheoFormatter.cs @@ -0,0 +1,18 @@ +using System; +using BCG; + +namespace BCG +{ + /// + /// returns the string representaion, for a + /// value (exp, theo, delta etc). the reason for + /// this interface is that for some products the + /// values are required in degrees/minutes, some + /// have to be rounded in a particular way etc + /// + public interface ITheoFormatter + { + string formatTheo (string theoType, object value); + string formatExpiration (DateTime expiration); + } +} diff --git a/src/client/spark/NMSheets/Outside/tc2/GUI/PriceControlGUI.cs b/src/client/spark/NMSheets/Outside/tc2/GUI/PriceControlGUI.cs new file mode 100644 index 000000000..ad8a9aa47 --- /dev/null +++ b/src/client/spark/NMSheets/Outside/tc2/GUI/PriceControlGUI.cs @@ -0,0 +1,335 @@ +using System; +using System.Collections; +using System.ComponentModel; +using System.Drawing; +using System.Data; +using System.Windows.Forms; + +using BCG.Utilities.General; +using mbts.ui; +namespace BCG { + public enum Anchors { + primary, + secondary + } + + public class PriceControlGUI : System.Windows.Forms.UserControl { + private System.Windows.Forms.CheckBox myFreezeCheckBox; + private bool myShowSecondary; + private ValueEntryGUI myAnchor1Entry; + private ValueEntryGUI myAnchor2Entry; + private ValueEntryGUI[] myAnchorGUIs; + private double[] myIntervals = new double[] { 0.1, 0.1 }; + + private double[] myCurrentPrices = new double[] { double.NaN, double.NaN }; + + private TickConverter2.TickType[] myTickTypes = new TickConverter2.TickType[] + {TickConverter2.TickType.tickDecimal2,TickConverter2.TickType.tickDecimal2}; + + private System.ComponentModel.Container components = null; + + #region public members + + public ValueEntryGUI primaryAnchor { get { return myAnchor1Entry; } } + + public bool showSecondary { + set { + myShowSecondary = value; + myRedraw(); + } + get { return myShowSecondary; } + } + + public int minSize { + get { + return + myFreezeCheckBox.Width + + myAnchor1Entry.minSize.Width + + (showSecondary ? myAnchor2Entry.minSize.Width + myPrimSecSeparation : 0); + } + } + + public TickConverter2.TickType getTickType(int wichAnchor) { return myTickTypes[wichAnchor]; } + + public void setTickType(int wichAnchor, TickConverter2.TickType newType) { + // changing the tick type might + // change the price if the price happens + // to be ilegal in the new tick format. + if (newType != myTickTypes[wichAnchor]) { + double primaryValue = getAnchor(wichAnchor); + myTickTypes[wichAnchor] = newType; + setAnchor(wichAnchor, primaryValue); + + if (myFreezeCheckBox.Checked && onFreezePrice != null) + onFreezePrice(this, new Object[] { wichAnchor, getAnchor(wichAnchor) }); + } + } + + private static int myPrimSecSeparation = 10; + public void setInterval(int anchor, double interval) { myIntervals[anchor] = interval; } + + public double getInterval(int anchor) { return myIntervals[anchor]; } + + public GUIChange onFreezePrice; + public GUIChange onLivePrice; + + #endregion + + public PriceControlGUI() { + // This call is required by the Windows.Forms Form Designer. + InitializeComponent(); + + // TODO: Add any initialization after the InitializeComponent call + + myAnchorGUIs = new ValueEntryGUI[2]; + + myAnchorGUIs[0] = myAnchor1Entry; + myAnchorGUIs[1] = myAnchor2Entry; + + setAnchor(0, 0); + setAnchor(1, 0); + + showSecondary = false; + + myAnchor1Entry.onValueDown += new GUIChange(my0Down); + myAnchor1Entry.onValueUp += new GUIChange(my0Up); + myAnchor1Entry.onValueEdit += new GUIChange(my0Edit); + myAnchor1Entry.onValueFlip += new GUIChange(my0Edit); + + myAnchor2Entry.onValueDown += new GUIChange(my1Down); + myAnchor2Entry.onValueUp += new GUIChange(my1Up); + myAnchor2Entry.onValueEdit += new GUIChange(my1Edit); + myAnchor2Entry.onValueFlip += new GUIChange(my1Edit); + } + + internal ValueEntryGUIConfig config { + set { + myAnchor1Entry.config = value; + myAnchor2Entry.config = value; + this.BackColor = value.backColor; + this.myFreezeCheckBox.BackColor = value.backColor; + } + + get { return myAnchor1Entry.config; } + } + + protected override void OnEnabledChanged(EventArgs e) { + base.OnEnabledChanged(e); + myFreezeCheckBox.Visible = Enabled; + } + + public double getAnchor(int whichAnchor) { + return myCurrentPrices[whichAnchor]; + } + + public void setAnchor(int whichAnchor, double whichValue) { + myAnchorGUIs[whichAnchor].currentValue = + TickConverter2.toTick(whichValue, myTickTypes[whichAnchor]); + myCurrentPrices[whichAnchor] = whichValue; + } + + + private void my0Up(object sender, object value) { myIncrementalPriceChange(0, true); } + + private void my0Down(object sender, object value) { myIncrementalPriceChange(0, false); } + + private void my1Up(object sender, object value) { myIncrementalPriceChange(1, true); } + + private void my1Down(object sender, object value) { myIncrementalPriceChange(1, false); } + + private void my0Edit(object sender, object value) { myPriceChange(0); } + + private void my1Edit(object sender, object value) { myPriceChange(1); } + + private void myIncrementalPriceChange(int anchor, bool direction) //on ups and downs + { + double newValue = + PintoValueRounder.calculateToNearestInterval(getAnchor(anchor), + myIntervals[anchor], + direction, 10); + + setAnchor(anchor, newValue); + if (!myFreezeCheckBox.Checked) + setCheckState(true); + myHandleFreezeCheckBoxChange(true, anchor); + } + + private void myPriceChange(int anchor) //on clicks on price text boxes + { + using (TCNumPad tcNumPad = new TCNumPad(anchor == 0 ? "Primary" : "Secondary", + TickConverter2.getSeparator(myTickTypes[anchor]))) { + if (tcNumPad.myShowDialog() == DialogResult.OK) { + double newPrice = 0; + + try { + newPrice = + TickConverter2.fromTick(tcNumPad.asText, myTickTypes[anchor]); + } catch (Exception) { + MessageBox.Show("Invalid price", "TC2", MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + setAnchor(anchor, newPrice); + if (!myFreezeCheckBox.Checked) + setCheckState(true); + myHandleFreezeCheckBoxChange(true, anchor); + } + } + } + + private void myRedraw() { + + Resize -= new System.EventHandler(this.PriceControlGUI_Resize); + + if (Enabled) { + if (!myAnchor2Entry.Visible && showSecondary) + Width = (Width - myFreezeCheckBox.Width) * 2 + myFreezeCheckBox.Width + myPrimSecSeparation; + else if (myAnchor2Entry.Visible && !showSecondary) + Width = (Width - myFreezeCheckBox.Width) / 2 + myFreezeCheckBox.Width - myPrimSecSeparation; + + int w = this.Width - myFreezeCheckBox.Width; + Resize += new System.EventHandler(this.PriceControlGUI_Resize); + myAnchor1Entry.Left = myFreezeCheckBox.Width; + + if (showSecondary) { + myAnchor1Entry.Width = (w - myPrimSecSeparation) / 2; + myAnchor2Entry.Left = myAnchor1Entry.Left + myAnchor1Entry.Width + myPrimSecSeparation; + myAnchor2Entry.Width = myAnchor1Entry.Width; + myAnchor2Entry.Visible = true; + } else { + myAnchor1Entry.Width = w; + myAnchor2Entry.Visible = false; + } + } else { + if (!myAnchor2Entry.Visible && showSecondary) + Width = (Width) * 2; + else if (myAnchor2Entry.Visible && !showSecondary) + Width = (Width) / 2 - myPrimSecSeparation; + + int w = this.Width; + Resize += new System.EventHandler(this.PriceControlGUI_Resize); + myAnchor1Entry.Left = 0; + + if (showSecondary) { + myAnchor1Entry.Width = (w) / 2; + myAnchor2Entry.Left = myAnchor1Entry.Left + myAnchor1Entry.Width; + myAnchor2Entry.Width = myAnchor1Entry.Width; + myAnchor2Entry.Visible = true; + } else { + myAnchor1Entry.Width = w; + myAnchor2Entry.Visible = false; + } + } + } + + private void PriceControlGUI_Resize(object sender, System.EventArgs e) { myRedraw(); } + + private void myFreezeCheckBox_CheckStateChanged(object sender, System.EventArgs e) { + myHandleFreezeCheckBoxChange(myFreezeCheckBox.Checked, 0); + } + + private void myHandleFreezeCheckBoxChange(bool frozenState, int whichAnchor) { + if (frozenState) { + if (onFreezePrice != null) { + onFreezePrice(this, new object[] { whichAnchor, getAnchor(whichAnchor) }); + } + } else { + if (onLivePrice != null) + onLivePrice(this, 0); + } + } + + public void setState(int whichAnchor, double price, bool checkState) { + bts.Log.assert(whichAnchor == 0, "Can only freeze primary anchor externally"); + setAnchor(whichAnchor, price); + myFreezeCheckBox.Checked = checkState; + } + + public void setCheckState(bool checkState) { + myFreezeCheckBox.CheckStateChanged -= new EventHandler(myFreezeCheckBox_CheckStateChanged); + myFreezeCheckBox.Checked = checkState; + myFreezeCheckBox.CheckStateChanged += new EventHandler(myFreezeCheckBox_CheckStateChanged); + } + + public bool getCheckState() { + return myFreezeCheckBox.Checked; + } + + + public object Tag_Secondary; + /// + /// Clean up any resources being used. + /// + protected override void Dispose(bool disposing) { + if (disposing) { + if (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.myFreezeCheckBox = new System.Windows.Forms.CheckBox(); + this.myAnchor1Entry = new BCG.ValueEntryGUI(); + this.myAnchor2Entry = new BCG.ValueEntryGUI(); + this.SuspendLayout(); + // + // myFreezeCheckBox + // + this.myFreezeCheckBox.FlatStyle = System.Windows.Forms.FlatStyle.Flat; + this.myFreezeCheckBox.Font = new System.Drawing.Font("Arial Narrow", 6.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.myFreezeCheckBox.Location = new System.Drawing.Point(2, 0); + this.myFreezeCheckBox.Name = "myFreezeCheckBox"; + this.myFreezeCheckBox.Size = new System.Drawing.Size(30, 16); + this.myFreezeCheckBox.TabIndex = 0; + this.myFreezeCheckBox.Text = "Fr"; + this.myFreezeCheckBox.CheckStateChanged += new System.EventHandler(this.myFreezeCheckBox_CheckStateChanged); + this.myFreezeCheckBox.BackColor = BTSColors.UI.default_background; + // + // myAnchor1Entry + // + this.myAnchor1Entry.config = null; + this.myAnchor1Entry.currentValue = "0"; + this.myAnchor1Entry.flip = false; + this.myAnchor1Entry.Location = new System.Drawing.Point(33, 0); + this.myAnchor1Entry.Name = "myAnchor1Entry"; + this.myAnchor1Entry.Size = new System.Drawing.Size(136, 16); + this.myAnchor1Entry.TabIndex = 1; + // + // myAnchor2Entry + // + this.myAnchor2Entry.config = null; + this.myAnchor2Entry.currentValue = "0"; + this.myAnchor2Entry.flip = false; + this.myAnchor2Entry.Location = new System.Drawing.Point(171, 0); + this.myAnchor2Entry.Name = "myAnchor2Entry"; + this.myAnchor2Entry.Size = new System.Drawing.Size(136, 16); + this.myAnchor2Entry.TabIndex = 2; + // + // PriceControlGUI + // + this.BackColor = BTSColors.UI.default_background; + this.Controls.Add(this.myAnchor2Entry); + this.Controls.Add(this.myAnchor1Entry); + this.Controls.Add(this.myFreezeCheckBox); + this.Name = "PriceControlGUI"; + this.Size = new System.Drawing.Size(309, 16); + this.Resize += new System.EventHandler(this.PriceControlGUI_Resize); + this.ResumeLayout(false); + + // HighDPI - this seems to fix the 'Fr' text label on the + // NMSheetDrivercontrol from getting chopped off on high dpi displays. + this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + + + } + #endregion + + } +} diff --git a/src/client/spark/NMSheets/Outside/tc2/GUI/PriceControlGUI.resx b/src/client/spark/NMSheets/Outside/tc2/GUI/PriceControlGUI.resx new file mode 100644 index 000000000..19dc0dd8b --- /dev/null +++ b/src/client/spark/NMSheets/Outside/tc2/GUI/PriceControlGUI.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file 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/Outside/tc2/GUI/TheoFormatter.cs b/src/client/spark/NMSheets/Outside/tc2/GUI/TheoFormatter.cs new file mode 100644 index 000000000..ee22e15a9 --- /dev/null +++ b/src/client/spark/NMSheets/Outside/tc2/GUI/TheoFormatter.cs @@ -0,0 +1,159 @@ +using System; +using BCG; +using BCG.Utilities.General; +using System.Collections.Generic; + +namespace BCG { + // 3/7/12 : added formatting for gamma and vega + public class TheoFormatter : ITheoFormatter { + private TickConverter2.TickType myTheoTickType, + myStrikeTickType; + + private static bool _use_cached_values = true;//"true".Equals(BCG.Utilities.BlueConfiguration.ConfigurationRequester.request("cacheTheoFormat")); + + + public TheoFormatter() + : this(TickConverter2.TickType.tickDecimal2, TickConverter2.TickType.tickDecimal2Strike) { } + + public TheoFormatter(TickConverter2.TickType theoTickType) + : this(theoTickType, TickConverter2.TickType.tickDecimal2Strike) { } + + public TheoFormatter(TickConverter2.TickType theoTickType, TickConverter2.TickType strikeTickType) { + myTheoTickType = theoTickType; + myStrikeTickType = strikeTickType; + } + + public TheoFormatter(string sym) { + myTheoTickType = TickConverter2.TickType.tickDecimal3; // TODO TickTypeResolver.getTickType(sym, TickTypeResolver.ValueType.theo); + myStrikeTickType = TickConverter2.TickType.tickDecimal2Strike; // TODO TickTypeResolver.getTickType(sym, TickTypeResolver.ValueType.strike); + } + + #region ITheoFormatter Members + + private struct CacheEntry { + public string value; + public DateTime last_access; + } + + private Dictionary> _cached_data = new Dictionary>(); + private DateTime _last_clean = DateTime.Now; + private DateTime _now = DateTime.Now; + + private void evict_old_cache_entries() { + const int max_cache_duration_minutes = 5; + + if ((_now - _last_clean).TotalMinutes > max_cache_duration_minutes) { + _last_clean = DateTime.Now; + foreach (var cache in _cached_data.Values) { + List to_clean = new List(); + foreach (var kvp in cache) { + if ((_now - kvp.Value.last_access).TotalMinutes > max_cache_duration_minutes) + to_clean.Add(kvp.Key); + } + foreach (double d in to_clean) + cache.Remove(d); + } + } + } + + UInt64 _cycle_count = 0; + public string formatTheo(string theo_type, double v) { + _cycle_count++; + if (_cycle_count % 10000 == 0) + _now = DateTime.Now; + if (_use_cached_values) { + evict_old_cache_entries(); + v = Math.Round(v, 4); + Dictionary val_to_string; + if (!_cached_data.TryGetValue(theo_type, out val_to_string)) { + val_to_string = new Dictionary(); + _cached_data.Add(theo_type, val_to_string); + } + CacheEntry rv; + if (!val_to_string.TryGetValue(v, out rv)) { + rv = new CacheEntry { + value = _format_theo(theo_type, v), + }; + val_to_string.Add(v, rv); + } + rv.last_access = _now; + return rv.value; + } else + return _format_theo(theo_type, v); + } + + private string _format_theo(string theoType, double v) { + if (theoType.Equals("call") || theoType.Equals("put") || theoType.Equals("primaryLive") || theoType.Equals("straddle")) + return TickConverter2.toTick((double)v, myTheoTickType); + else if (theoType.Equals("callGamma") || theoType.Equals("putGamma") || theoType.Equals("gamma")) + return TickConverter2.toTick((double)v * 100, TickConverter2.TickType.tickDecimal2); + else if (theoType.Equals("callVega") || theoType.Equals("putVega") || theoType.Equals("vega")) + return TickConverter2.toTick((double)v, TickConverter2.TickType.tickDecimal2); + else if (theoType.Equals("vol") || theoType.Equals("vol_change")) + return TickConverter2.toTick((double)(v * 100.0), TickConverter2.TickType.tickDecimal2); + else if (theoType.Equals("callBid") || theoType.Equals("callAsk") || theoType.Equals("putBid") || theoType.Equals("putAsk")) + return Double.IsNaN(v) ? String.Empty : TickConverter2.toTick((double)v, myTheoTickType); + else if (theoType.Equals("callBidSize") || theoType.Equals("callAskSize") || theoType.Equals("putBidSize") || theoType.Equals("putAskSize")) + return (Double.IsNaN(v) || v == Int32.MinValue || v == 0) ? String.Empty : TickConverter2.toTick((double)v, TickConverter2.TickType.tickDecimal2Strike); + else if (theoType.Equals("callDelta") || theoType.Equals("putDelta")) { + /// delta*100 mult for sheets + v *= 100; + double delta100 = Math.Abs(v); + if (delta100 < TC2Settings.instance.deltaRoundingThreshold) + delta100 = Math.Floor(delta100 * 10.0 + 0.5) / 10.0; + else + delta100 = Math.Floor(delta100 + 0.5); + + return delta100.ToString(); + } else if (theoType.Equals("signedDelta")) { + /// this calls into formatting again so no + /// need to multiply it here + if (v >= 0) + return formatTheo("callDelta", v); + else + return "-" + formatTheo("callDelta", v); + } else if (theoType.Equals("strike")) + return TickConverter2.toTick(v, myStrikeTickType); + else if (theoType.Equals("call_position") || theoType.Equals("put_position")) { + if (DBNull.Value.Equals(v) || v == 0) + return String.Empty; + else + return TickConverter2.toTick(v, TickConverter2.TickType.tickDecimal0); + } else if (theoType.Equals("call_shift") || theoType.Equals("put_shift") || theoType.Equals("call_shifted_theo") || theoType.Equals("put_shifted_theo")) + return TickConverter2.toTick((double)v, myTheoTickType); + if (theoType.Equals("call_bid_edge") || theoType.Equals("call_ask_edge") || theoType.Equals("put_bid_edge") || theoType.Equals("put_ask_edge")) + return TickConverter2.toTick((double)v, myTheoTickType); + else if (theoType.Equals("presave_call_theo_diff") || theoType.Equals("presave_put_theo_diff") || theoType.Equals("theta") || theoType.Equals("callTheta") || theoType.Equals("putTheta")) + return TickConverter2.toTick((double)v, TickConverter2.TickType.tickDecimal2); + else if (theoType.Equals("presave_call_theo") || theoType.Equals("presave_put_theo")) + return TickConverter2.toTick((double)v, myTheoTickType); + else if (theoType.Equals("standard_strike")) + return TickConverter2.toTick((double)v, TickConverter2.TickType.tickDecimal2); + else + return v.ToString(); + } + + public string formatTheo(string theoType, object theoValue) { return formatTheo(theoType, theoValue == null ? Double.NaN : (double)theoValue); } + + public string formatExpiration(DateTime expiration) { + //expiration = expiration.AddMonths(TC2Settings.instance.expMonthOffset); + string[] shortMonths = + new string[] { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }; + return expiration.Day + " " + shortMonths[expiration.Month - 1] + " " + (expiration.Year - 2000).ToString("00"); + } + + public string formatTheoTime(DateTime time) { + return time.ToString("T"); + } + + public TickConverter2.TickType theoTickType { + get { return myTheoTickType; } + } + + public TickConverter2.TickType strikeTickType { + get { return myStrikeTickType; } + } + + #endregion + } +} diff --git a/src/client/spark/NMSheets/Outside/tc2/GUI/TheoGridColumnOrder.cs b/src/client/spark/NMSheets/Outside/tc2/GUI/TheoGridColumnOrder.cs new file mode 100644 index 000000000..8ca1752b7 --- /dev/null +++ b/src/client/spark/NMSheets/Outside/tc2/GUI/TheoGridColumnOrder.cs @@ -0,0 +1,144 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace BCG +{ + [Serializable] + public class TheoGridColumnOrder + { + public string[] columns; + public static Dictionary md_columns = new Dictionary(); + static TheoGridColumnOrder() + { + md_columns.Add("callBidSize", true); + md_columns.Add("callAskSize", true); + md_columns.Add("callBid", true); + md_columns.Add("callAsk", true); + md_columns.Add("putBidSize", true); + md_columns.Add("putAskSize", true); + md_columns.Add("putBid", true); + md_columns.Add("putAsk", true); + } + + public static string[] md_columns_array + { + get + { + string[] rv = new string[md_columns.Count]; + md_columns.Keys.CopyTo(rv, 0); + return rv; + } + } + + public TheoGridColumnOrder(string[] theColumns) { columns = theColumns; } + + public TheoGridColumnOrder() + { + columns = new string[] + { + "callBidSize", + "callBid", + "call_position", + "call_bid_edge", + "call", + "presave_call_theo", + "presave_call_theo_diff", + "call_ask_edge", + "call_shift", + "call_shifted_theo", + "callDelta", + "callGamma", + "callVega", + "callAsk", + "callAskSize", + "strike", + "standard_strike", + "vol", + "vol_change", + "straddle", + "putBidSize", + "putBid", + "put_bid_edge", + "put", + "presave_put_theo", + "presave_put_theo_diff", + "put_ask_edge", + "put_shift", + "put_shifted_theo", + "putDelta", + "putGamma", + "putVega", + "put_position", + "putAsk", + "putAskSize" + }; + } + + public void remove_erroneous_cols() + { + List standard_cols = new List(new TheoGridColumnOrder().columns); + /// remove columns that are not part of this class + List this_ins_cols = new List (columns); + foreach (string col in columns) + if (!standard_cols.Contains(col)) + this_ins_cols.Remove(col); + /// add columns that are not part of this type + foreach (string col in standard_cols) + if (!this_ins_cols.Contains(col)) + this_ins_cols.Insert(0, col); + columns = this_ins_cols.ToArray(); + } + + public static Dictionary get_conversion_map() + { + Dictionary rv = new Dictionary(); + rv.Add("callBidSize", NMSheetColumnName.call_bid_size); + rv.Add("callBid", NMSheetColumnName.call_bid_price); + rv.Add("call_position", NMSheetColumnName.call_position); + //rv.Add ("call_bid_edge",NMSheetColumnName + rv.Add("call", NMSheetColumnName.call_theo); + rv.Add("presave_call_theo", NMSheetColumnName.presave_call_theo); + rv.Add("presave_call_theo_diff", NMSheetColumnName.presave_call_theo_diff); + //rv.Add ("call_ask_edge", + rv.Add("callDelta", NMSheetColumnName.call_delta); + rv.Add("callGamma", NMSheetColumnName.call_gamma); + rv.Add("callVega", NMSheetColumnName.call_vega); + rv.Add("callAsk", NMSheetColumnName.call_ask_price); + rv.Add("callAskSize", NMSheetColumnName.call_ask_size); + rv.Add("strike", NMSheetColumnName.strike); + rv.Add("standard_strike", NMSheetColumnName.standard_strike); + rv.Add("vol", NMSheetColumnName.vol); + rv.Add("vol_change", NMSheetColumnName.vol_change); + rv.Add("straddle", NMSheetColumnName.straddle); + rv.Add("putBidSize", NMSheetColumnName.put_bid_size); + rv.Add("putBid", NMSheetColumnName.put_bid_price); + //rv.Add ("put_bid_edge",NMSheetColumnName. + rv.Add("put", NMSheetColumnName.put_theo); + rv.Add("presave_put_theo", NMSheetColumnName.presave_put_theo); + rv.Add("presave_put_theo_diff", NMSheetColumnName.presave_put_theo_diff); + //rv.Add ("put_ask_edge",NMSheetColumnName. + rv.Add("putDelta", NMSheetColumnName.put_delta); + rv.Add("putGamma", NMSheetColumnName.put_gamma); + rv.Add("putVega", NMSheetColumnName.put_vega); + rv.Add("put_position", NMSheetColumnName.put_position); + rv.Add("putAsk", NMSheetColumnName.put_ask_price); + rv.Add("putAskSize", NMSheetColumnName.put_ask_size); + return rv; + } + + public static Dictionary get_column_position_map(TheoGridColumnOrder col_order) + { + Dictionary rv = new Dictionary(); + Dictionary conversion_map = get_conversion_map(); + foreach (string col_name in col_order.columns) + { + NMSheetColumnName col_name_enum; + if (conversion_map.TryGetValue(col_name, out col_name_enum)) + rv.Add(col_name_enum, rv.Count); + } + return rv; + } + } +} diff --git a/src/client/spark/NMSheets/Outside/tc2/GUI/UpArrow2.ico b/src/client/spark/NMSheets/Outside/tc2/GUI/UpArrow2.ico new file mode 100644 index 000000000..b711f86bc Binary files /dev/null and b/src/client/spark/NMSheets/Outside/tc2/GUI/UpArrow2.ico differ diff --git a/src/client/spark/NMSheets/Outside/tc2/GUI/ValueEntryGUI.cs b/src/client/spark/NMSheets/Outside/tc2/GUI/ValueEntryGUI.cs new file mode 100644 index 000000000..d9750f157 --- /dev/null +++ b/src/client/spark/NMSheets/Outside/tc2/GUI/ValueEntryGUI.cs @@ -0,0 +1,407 @@ +using System; +using System.Collections; +using System.ComponentModel; +using System.Drawing; +using System.Data; +using System.Windows.Forms; +using System.Runtime.Serialization; +using mbts.ui.dpi; +using System.Collections.Generic; +using BCG.Utilities.General; + +namespace BCG { + public class ValueEntryGUI : System.Windows.Forms.UserControl { + //internal static ArrayList comps = new ArrayList (); + /// + /// Minimum size this control can have and still display things properly + /// + public Size minSize { + get { + OnPaint(new PaintEventArgs(Graphics.FromImage(new Bitmap(1, 1)), new Rectangle(1, 1, 1, 1))); + return myMinSize; + } + } + + /// + /// Current value, the representation of which is displayed in the control + /// + public object currentValue { + set { + myValue = value; + myPaint(); + } + get { return myValue; } + } + + /// + /// GUI settings for this control + /// + public ValueEntryGUIConfig config { + set { + myCFG = value; + myPaint(); + } + get { + if (myCFG == null && !DesignMode) // the designer has some beef with deserializing this class + myCFG = new ValueEntryGUIConfig(); + return myCFG; + } + } + + /// + /// True if the control in a flipped state, meaning in state in + /// which an alternate color shold be used for the background + /// on which the value is displayed. + /// + public bool flip { + set { + if (value != myFlipped) { + myFlipped = value; + myPaint(); + } + } + get { return myFlipped; } + } + + + + /// + /// Up arrow clicked + /// + public GUIChange onValueUp; + + /// + /// Down arrow clicked + /// + public GUIChange onValueDown; + + /// + /// Request for value edit + /// + public GUIChange onValueEdit; + + /// + /// Request for flipping value + /// + public GUIChange onValueFlip; + + + private bool myFlipped; + private ValueEntryGUIConfig myCFG = null; + private bool myMouseIsDown = false; + private object myValue = "0"; + private Rectangle myUpButtonRec = new Rectangle(-1, -1, -1, -1); + private Rectangle myDownButtonRec = new Rectangle(-1, -1, -1, -1); + private Rectangle myValueRec = new Rectangle(-1, -1, -1, -1); + private Rectangle myFlipRec = new Rectangle(-1, -1, -1, -1); + private Point myPreviousMousePosition = new Point(-1, -1); + private Size myMinSize = new Size(0, 0); + private System.Windows.Forms.ImageList myImageList; + private System.ComponentModel.IContainer components; + private System.Windows.Threading.DispatcherTimer _timer = new System.Windows.Threading.DispatcherTimer(); + private int _thread_id; + + private Dictionary _naive_cache = new Dictionary(); + private static readonly bool _cache_is_enabled = true; //TODO: mbts.config.Configuration.get().enabled; + private const int _up_image_index = 0; + private const int _down_image_index = 1; + private System.Drawing.Image _get_dpi_adjusted_image_from_cache(string cache_key) { + if (_naive_cache.ContainsKey(cache_key)) { + return _naive_cache[cache_key]; + } else { + Image _unadjusted_image = (cache_key == "up") ? myImageList.Images[_up_image_index] : myImageList.Images[_down_image_index]; + Image _adjusted_image = _unadjusted_image.GetImageStretchedDPI(); + _naive_cache.Add(cache_key, _adjusted_image); + return _adjusted_image; + } + } + + + public ValueEntryGUI() { + // This call is required by the Windows.Forms Form Designer. + InitializeComponent(); + _thread_id = System.Threading.Thread.CurrentThread.ManagedThreadId; + SetStyle(ControlStyles.UserPaint, true); + SetStyle(ControlStyles.AllPaintingInWmPaint, true); + SetStyle(ControlStyles.Opaque, true); + SetStyle(ControlStyles.DoubleBuffer, true); + _timer.Tick += myTimer_Tick; + _timer.Interval = TimeSpan.FromMilliseconds(100); + _timer.Start(); + //CentralTimer.timer.Tick += new System.EventHandler(this.myTimer_Tick); + } + + + protected override void Dispose(bool disposing) { + _timer.Tick -= myTimer_Tick; + foreach (System.Drawing.Image img in _naive_cache.Values) { + img.Dispose(); + } + //CentralTimer.timer.Tick -= new System.EventHandler(this.myTimer_Tick); + if (disposing) { + if (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.components = new System.ComponentModel.Container(); + System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(ValueEntryGUI)); + this.myImageList = new System.Windows.Forms.ImageList(this.components); + // + // myImageList + // + this.myImageList.ColorDepth = System.Windows.Forms.ColorDepth.Depth16Bit; + this.myImageList.ImageSize = new System.Drawing.Size(11, 10); + this.myImageList.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("myImageList.ImageStream"))); + this.myImageList.TransparentColor = System.Drawing.Color.White; + // + // ValueEntryGUI + // + this.Name = "ValueEntryGUI"; + this.Size = new System.Drawing.Size(136, 24); + this.Move += new System.EventHandler(this.ValueEntryGUI_Move); + this.Click += new System.EventHandler(this.ValueEntryGUI_Click); + this.Resize += new System.EventHandler(this.ValueEntryGUI_Resize); + this.MouseUp += new System.Windows.Forms.MouseEventHandler(this.ValueEntryGUI_MouseUp); + this.MouseDown += new System.Windows.Forms.MouseEventHandler(this.ValueEntryGUI_MouseDown); + + } + #endregion + + private void myPaint() { Invalidate(); } + + protected override void OnPaint(PaintEventArgs e) { + Graphics g = e.Graphics; + + if (myValue != null && !DesignMode) { + g.Clear(config.backColor); + Image up; + Image down; + if (HighDpiExtensions.DPIIsOne() || !_cache_is_enabled) { + up = myImageList.Images[0]; + down = myImageList.Images[1]; + } else { + up = _get_dpi_adjusted_image_from_cache("up"); + down = _get_dpi_adjusted_image_from_cache("down"); + } + + myUpButtonRec = new Rectangle( + this.Width - config.buttonSize.Width * 2 - config.buttonDistance * 2, + (this.Height - config.buttonSize.Height) / 2, + config.buttonSize.Width, + config.buttonSize.Height); + + myDownButtonRec = new Rectangle( + this.Width - config.buttonSize.Width - config.buttonDistance, + myUpButtonRec.Y, + myUpButtonRec.Width, + myUpButtonRec.Height); + + // HighDPI - this makes it so that the +/- on the trade card + // are not cut off at 200% scaling + if (config.CanFlip) + myFlipRec = new Rectangle(0, 0, + config.FlipSize.Width.MultipliedByDPIRatio(), + this.Height); + else + myFlipRec = new Rectangle(0, 0, 0, 0); + + int flipSeparator = config.CanFlip ? config.FlipSeparation : 0; + + myValueRec = + new Rectangle(myFlipRec.Width + flipSeparator, 0, + myUpButtonRec.X - 1 - config.valueRPadding - myFlipRec.Width - flipSeparator, this.Height); + + if (config.CanFlip) { + string flipString = config.FlipString; + SizeF flipStringSize = g.MeasureString(flipString, config.valueFont); + + int xxValue = 0; + if (flipStringSize.Width < myFlipRec.Width) + xxValue = (int)(myFlipRec.Width - flipStringSize.Width) / 2; + + int yyValue = 0; + if (flipStringSize.Height < myFlipRec.Height) + yyValue = (int)(myFlipRec.Height - flipStringSize.Height) / 2; + + g.FillRectangle(new SolidBrush(config.FlipBackroungColor), + myFlipRec); + + g.DrawString(flipString, config.valueFont, + new SolidBrush(config.valueFColor), + xxValue, yyValue); + } + + + string valueS = myValue.ToString(); + SizeF valueStringSize = g.MeasureString(valueS, config.valueFont); + + int xValue = 0; + + if ((valueStringSize.Width + config.valueRPadding) < myUpButtonRec.X) { + if (config.CenterValueHorizontally) + xValue = (int)(myUpButtonRec.X - config.valueRPadding - valueStringSize.Width - myFlipRec.Width) / 2 + myFlipRec.X; + else + xValue = myUpButtonRec.X - (int)valueStringSize.Width - config.valueRPadding + myFlipRec.X; + } + + int yValue = 0; + if (valueStringSize.Height < this.Height) + yValue = (this.Height - (int)valueStringSize.Height) / 2; + + g.FillRectangle(new SolidBrush(myFlipped ? + config.flippedValueBColor : config.valueBColor), + myValueRec); + + g.DrawString(valueS, config.valueFont, + new SolidBrush(config.valueFColor), + xValue, yValue); + + if (Enabled) { + g.DrawImage(up, + myUpButtonRec.X + (myUpButtonRec.Width - up.Width) / 2, + myUpButtonRec.Y + (myUpButtonRec.Height - up.Height) / 2); + + g.DrawImage(down, + myDownButtonRec.X + (myDownButtonRec.Width - down.Width) / 2, + myDownButtonRec.Y + (myDownButtonRec.Height - down.Height) / 2); + + Point mousePos = this.PointToClient(Cursor.Position); + if (myUpButtonRec.Contains(mousePos)) + myDrawOutline(g, myUpButtonRec, myMouseIsDown); + else if (myDownButtonRec.Contains(mousePos)) + myDrawOutline(g, myDownButtonRec, myMouseIsDown); + else if (myValueRec.Contains(mousePos)) + myDrawOutline(g, myValueRec, false); + else if (myFlipRec.Contains(mousePos)) + myDrawOutline(g, myFlipRec, false); + } else { + g.FillRectangle(new SolidBrush(config.backColor), + myUpButtonRec.X + (myUpButtonRec.Width - up.Width) / 2, + myUpButtonRec.Y + (myUpButtonRec.Height - up.Height) / 2, + up.Width + down.Width, up.Height); + } + + myMinSize.Width = (int)Math.Max(config.minHSize, + myFlipRec.Width + (config.CanFlip ? config.FlipSeparation : 0) + + myUpButtonRec.Width + myDownButtonRec.Width + + valueStringSize.Width + config.valueRPadding + config.valueLPadding + + config.buttonDistance * 2); + + myMinSize.Height = (int)Math.Max(config.minVSize, + Math.Max(valueStringSize.Height + config.valueVPadding, config.buttonSize.Height)); + } else + g.FillRectangle(new SolidBrush(Color.IndianRed), 0, 0, this.Width, this.Height); + } + + private void myDrawOutline(Graphics g, Rectangle r, bool depressed) { + //System.Diagnostics.Trace.WriteLine(depressed); + Color c1, c2; + + if (depressed) { + c1 = config.darkOutlineColor; + c2 = config.lightOutlineColor; + } else { + c1 = config.lightOutlineColor; + c2 = config.darkOutlineColor; + } + + Pen p1 = new Pen(new SolidBrush(c1)); + Pen p2 = new Pen(new SolidBrush(c2)); + + g.DrawLine(p1, r.X, r.Y, r.X + r.Width - 1, r.Y); + g.DrawLine(p1, r.X, r.Y, r.X, r.Y + r.Height - 1); + + g.DrawLine(p2, r.X + r.Width - 1, r.Y + r.Height - 1, r.X + r.Width - 1, r.Y); + g.DrawLine(p2, r.X + r.Width - 1, r.Y + r.Height - 1, r.X, r.Y + r.Height - 1); + } + + private void myTimer_Tick(object sender, System.EventArgs e) { + bts.Log.assert(_thread_id == System.Threading.Thread.CurrentThread.ManagedThreadId); + // This function should never be called after Dispose is called, but the + // the following did happen: + // System.ObjectDisposedException: Cannot access a disposed object named "ValueEntryGUI". + // Object name: "ValueEntryGUI". + // at System.Windows.Forms.Control.CreateHandle() + // at System.Windows.Forms.Control.get_Handle() + // at System.Windows.Forms.Control.PointToClientInternal(Point p) + // at System.Windows.Forms.Control.PointToClient(Point p) + // at BCG.ValueEntryGUI.myTimer_Tick(Object sender, EventArgs e) in X:\BCG\blue2\TradeEntry\TC2\GUI\ValueEntryGUI.cs:line 315 + // at System.EventHandler.Invoke(Object sender, EventArgs e) + // at System.Windows.Forms.Timer.OnTick(EventArgs e) + // at System.Windows.Forms.Timer.Callback(IntPtr hWnd, Int32 msg, IntPtr idEvent, IntPtr dwTime) + if (IsDisposed) + return; + + Point p = this.PointToClient(Cursor.Position); + if (myPreviousMousePosition.X == -1 + || + + (myUpButtonRec.Contains(myPreviousMousePosition) != + myUpButtonRec.Contains(p.X, p.Y)) + + || + (myDownButtonRec.Contains(myPreviousMousePosition) != + myDownButtonRec.Contains(p.X, p.Y)) + + || + (myValueRec.Contains(myPreviousMousePosition) != + myValueRec.Contains(p.X, p.Y)) + + || + (myFlipRec.Contains(myPreviousMousePosition) != + myFlipRec.Contains(p.X, p.Y))) { + myPaint(); + } + myPreviousMousePosition.X = p.X; + myPreviousMousePosition.Y = p.Y; + } + + private void ValueEntryGUI_Click(object sender, System.EventArgs e) { + } + + private void ValueEntryGUI_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e) { + myMouseIsDown = true; + myPaint(); + } + + private void ValueEntryGUI_MouseUp(object sender, System.Windows.Forms.MouseEventArgs e) { + Point p = this.PointToClient(Cursor.Position); + + if (myUpButtonRec.Contains(p)) { + if (onValueUp != null) { + onValueUp(this, myValue); + } + } else if (myDownButtonRec.Contains(p)) { + if (onValueDown != null) { + onValueDown(this, myValue); + } + } else if (myValueRec.Contains(p)) { + if (onValueEdit != null) + onValueEdit(this, myValue); + } else if (myFlipRec.Contains(p)) { + if (onValueFlip != null) + onValueFlip(this, myValue); + } + + + myMouseIsDown = false; + myPaint(); + } + + private void ValueEntryGUI_Resize(object sender, System.EventArgs e) { + myPaint(); + } + + private void ValueEntryGUI_Move(object sender, System.EventArgs e) { + } + } +} diff --git a/src/client/spark/NMSheets/Outside/tc2/GUI/ValueEntryGUI.resx b/src/client/spark/NMSheets/Outside/tc2/GUI/ValueEntryGUI.resx new file mode 100644 index 000000000..b15591563 --- /dev/null +++ b/src/client/spark/NMSheets/Outside/tc2/GUI/ValueEntryGUI.resx @@ -0,0 +1,159 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Private + + + Private + + + 17, 17 + + + + AAEAAAD/////AQAAAAAAAAAMAgAAAFpTeXN0ZW0uV2luZG93cy5Gb3JtcywgVmVyc2lvbj0xLjAuNTAw + MC4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPWI3N2E1YzU2MTkzNGUwODkFAQAAACZT + eXN0ZW0uV2luZG93cy5Gb3Jtcy5JbWFnZUxpc3RTdHJlYW1lcgEAAAAERGF0YQcCAgAAAAkDAAAADwMA + AADUAgAAAk1TRnQBSQFMAgEBAgEAAQQBAAEEAQABCwEAAQoBAAT/AREBEAj/AUIBTQE2BwABNgMAASgD + AAEsAwABCgMAAQEBAAEQBQABcAEDGAABzAEYAcwBGAHMARgBzAEYAcwBGBAAAcwBGDwAAcwBGAEbARYB + +gERAbkBAQHMARgOAAHMARgBuQEBAcwBGDoAAcwBGAE7AR4BGwEWAfoBEQHMARgMAAHMARgBGwEWAfoB + EQG5AQEBzAEYMgABzAEYAcwBGAHMARgBzAEYAXwBJgE7AR4BGwEWAcwBGAHMARgBzAEYAcwBGAQAAcwB + GAF8ASYBOwEeARsBFgH6AREBuQEBAcwBGDAAAcwBGAH+AT4B3QE6Ab0BMgGcASoBfAEmATsBHgEbARYB + +gERAbkBAQHMARgCAAHMARgBvQEyAZwBKgF8ASYBOwEeARsBFgH6AREBuQEBAcwBGDAAAcwBGAH+AT4B + 3QE6Ab0BMgGcASoBfAEmATsBHgEbARYBzAEYAgABzAEYAf4BPgHdAToBvQEyAZwBKgF8ASYBOwEeARsB + FgH6AREBuQEBAcwBGDAAAcwBGAH+AT4B3QE6Ab0BMgGcASoBfAEmAcwBGAQAAcwBGAHMARgBzAEYAcwB + GAG9ATIBnAEqAXwBJgHMARgBzAEYAcwBGAHMARgyAAHMARgB/gE+Ad0BOgG9ATIBzAEYDAABzAEYAd0B + OgG9ATIBnAEqAcwBGDoAAcwBGAH+AT4BzAEYDgABzAEYAf4BPgHdAToBvQEyAcwBGDwAAcwBGBAAAcwB + GAHMARgBzAEYAcwBGAHMARgyAAFCAU0BPgcAAT4DAAEoAwABLAMAAQoDAAEBAQABAQUAAVAXAAP/AQAB + 4AH/AXwFAAHgAf4BPAUAAeAB/AEcBgABGAEMBgABEAEEBQABgAEgBgABwAFgBgAB4AH8ARwFAAHxAfwB + HAUAAfsB/AEcGwAL + + + + ValueEntryGUI + + + False + + + False + + + True + + + True + + + 80 + + + (Default) + + + False + + + Private + + + 8, 8 + + \ No newline at end of file diff --git a/src/client/spark/NMSheets/Outside/tc2/GUI/ValueEntryGUIConfig.cs b/src/client/spark/NMSheets/Outside/tc2/GUI/ValueEntryGUIConfig.cs new file mode 100644 index 000000000..98d5e97e6 --- /dev/null +++ b/src/client/spark/NMSheets/Outside/tc2/GUI/ValueEntryGUIConfig.cs @@ -0,0 +1,200 @@ +using System; +using System.Collections; +using System.ComponentModel; +using System.Drawing; +using System.Data; +using System.Windows.Forms; +using System.Runtime.Serialization; + +using BCG.Utilities.General; +using mbts.ui; +using mbts.ui.dpi; + +namespace BCG +{ + [Serializable] + public class ValueEntryGUIConfig : ICloneable + { + // determines if the control should provide + // an area for flipping (used for instance + // to switch from + to - in a number + public bool CanFlip + { + set {myCanFlip = value;} + get {return myCanFlip;} + } + bool myCanFlip = false; + + // the string written in the flip area + public string FlipString + { + set{myFlipString = value;} + get{return myFlipString;} + } + string myFlipString = "+/-"; + + // the size of the flip area + public Size FlipSize + { + set{myFlipSize=value;} + get{return myFlipSize;} + } + Size myFlipSize = new Size (20,16); + + // space between flip area and value area + public int FlipSeparation + { + set{myFlipSeparation=value;} + get{return myFlipSeparation;} + } + int myFlipSeparation = 5; + + // color used for the flip area backroung + public Color FlipBackroungColor + { + set{myFlipBackroungColor = value;} + get{return myFlipBackroungColor;} + } + Color myFlipBackroungColor = Color.FromKnownColor(KnownColor.Transparent); + + // font used to display value + public Font valueFont + { + set {myValueFont = value;} + get {return myValueFont;} + } + + // the smallest width allowed for the control + public int minHSize + { + set {myMinHSize = value;} + get {return myMinHSize;} + } + + // the smallest height allowed for the control + public int minVSize + { + set {myMinVSize = value;} + get {return myMinVSize;} + } + + // Space between value and left button + public int valueRPadding + { + set {myValueRPadding = value;} + get {return myValueRPadding;} + } + + // space between left of control and value + public int valueLPadding + { + set {myValueLPadding = value;} + get {return myValueLPadding;} + } + + // space above value + public int valueVPadding + { + set {myValueVPadding = value;} + get {return myValueVPadding;} + } + + // space between buttons and to the right of + // right button + public int buttonDistance + { + set {myButtonDistance = value;} + get {return myButtonDistance;} + } + + // color used for value text + public Color valueFColor + { + set {myValueFColor = value;} + get {return myValueFColor;} + } + + // color used for value background + public Color valueBColor + { + set {myValueBColor = value;} + get {return myValueBColor;} + } + + // bool, if true the value is centered, + // else right justified + public bool CenterValueHorizontally + { + set {myCenterValueHorizontally = value;} + get {return myCenterValueHorizontally;} + } + + // button area back color + public Color backColor + { + set {myBackColor = value;} + get {return myBackColor;} + } + + // 1st color of the button highlight (visible only when + // pressed or overed over) + public Color darkOutlineColor + { + set {myDarkOutlineColor = value;} + get {return myDarkOutlineColor;} + } + + // 2nd color of the button highlight + public Color lightOutlineColor + { + set {myLightOutlineColor = value;} + get {return myLightOutlineColor;} + } + + // space taken by buttons + public Size buttonSize + { + set {myButtonSize = value;} + get {return myButtonSize;} + } + + // color used when the control is in a flipped state + public Color flippedValueBColor + { + set {myFlippedValueBColor = value;} + get {return myFlippedValueBColor;} + } + + private bool myCenterValueHorizontally = true; + + private int myMinVSize = 20; + private int myMinHSize = 20; + + private int myValueVPadding = 2; + private int myValueLPadding = 10; + private Font myValueFont = new Font("Tahoma",8); + private int myButtonDistance = 1; + private int myValueRPadding = 2; + // HighDPI - These are the up/down arrows on the top of the expirations + // in the sheets, as well as up/down arrows next to the driver price + // in the trade card. + private Size myButtonSize = new Size((15).MultipliedByDPIRatio(),(16).MultipliedByDPIRatio()); + private Color myFlippedValueBColor = BTSColors.UI.warning; + private Color myValueFColor = BTSColors.UI.default_text; + private Color myBackColor = BTSColors.UI.default_background; + + private Color myDarkOutlineColor = BTSColors.UI.gray_light; + private Color myLightOutlineColor = BTSColors.UI.gray_light; + + private Color myValueBColor = Color.FromKnownColor(KnownColor.LemonChiffon); + + #region ICloneable Members + + public object Clone() + { + return MemberwiseClone(); + } + + #endregion + } +} diff --git a/src/client/spark/NMSheets/Outside/tc2/GUI/tests/GDITestForm.cs b/src/client/spark/NMSheets/Outside/tc2/GUI/tests/GDITestForm.cs new file mode 100644 index 000000000..dbc29ec0d --- /dev/null +++ b/src/client/spark/NMSheets/Outside/tc2/GUI/tests/GDITestForm.cs @@ -0,0 +1,201 @@ +using System; +using System.Drawing; +using System.Collections; +using System.ComponentModel; +using System.Windows.Forms; + +namespace BCG +{ + /// + /// Summary description for GDITestForm. + /// + public class GDITestForm : System.Windows.Forms.Form + { + /// + /// Required designer variable. + /// + private System.ComponentModel.Container components = null; + + public GDITestForm() + { + // + // Required for Windows Form Designer support + // + InitializeComponent(); + + SetStyle(ControlStyles.AllPaintingInWmPaint, true); + SetStyle(ControlStyles.DoubleBuffer,true); + } + + /// + /// Clean up any resources being used. + /// + protected override void Dispose( bool disposing ) + { + if( disposing ) + { + if(components != null) + { + components.Dispose(); + } + } + 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.components = new System.ComponentModel.Container(); + this.Size = new System.Drawing.Size(300,300); + this.Text = "GDITestForm"; + } + #endregion + #region paint + protected override void OnResize(EventArgs e) + { + base.OnResize (e); + Invalidate(); + } + + private DateTime myStart = DateTime.Now; + private IGraphicsWrapper myGetWrapper(Graphics g) + { + IGraphicsWrapper w = null; + if ( TC2Settings.instance.paintMethod == "gdi32" ) + { + w = new GDI32Wrapper(g); + } + else if (TC2Settings.instance.paintMethod == "gdiPlus" ) + { + w = new GDIPlusWrapper(g); + } + else if (TC2Settings.instance.paintMethod == "bit" ) + { + w = new GDI32BitWrapper(g, 500, 500); + } + else + { + throw new ApplicationException("unknown paint method"); + } + + return w; + } + + public void myMainTest(PaintEventArgs e) + { + Rectangle r = e.ClipRectangle; + IGraphicsWrapper g = myGetWrapper(e.Graphics); + + for(int i = 1; i < 1000; i++ ) + { + Font f = new Font("Tahoma",8,FontStyle.Bold); + string t = f.Name + " " +f.Size.ToString(); + g.selectFont(f); + } + + int margin = 1; + g.clear(r, Color.Purple); + + Rectangle rUL = new Rectangle( + margin + r.Left, + margin + r.Top, + r.Width/2 - 2*margin, + r.Height/2 - 2 * margin); + g.selectBrush(g.createSolidBrush(Color.Red)); + g.fillRectangle(rUL.Left, rUL.Top, rUL.Width, rUL.Height); + + Rectangle rUR = new Rectangle( + margin + r.Left + r.Width/2, + margin + r.Top, + r.Width/2 - 2*margin, + r.Height/2 - 2 * margin); + + g.selectBrush(g.createSolidBrush(Color.Green)); + g.fillRectangle(rUR); + + Rectangle rLL = new Rectangle( + r.Left + margin, + margin + r.Top + r.Height/2, + r.Width/2 - 2*margin, + r.Height/2 - 2 * margin); + + g.selectBrush(g.createSolidBrush(Color.Blue)); + g.fillRectangle(rLL.Left, rLL.Top, rLL.Width, rLL.Height); + + Rectangle rLR= new Rectangle( + margin + r.Left + r.Width/2, margin + r.Top + r.Height/2, + r.Width/2 - 2*margin, + r.Height/2 - 2 * margin); + + g.selectBrush(g.createSolidBrush(Color.RoyalBlue)); + g.fillRectangle(rLR); + + int rm = r.Width/8; + Rectangle lR = new Rectangle( + r.Left + rm, + r.Top + rm, + r.Width/2, + r.Height/2 ); + + g.selectPen(g.createPen( + 2, + Color.Black)); + g.drawRectangle(lR.Left, lR.Top, lR.Width, lR.Height); + + rm = r.Width/6; + lR = new Rectangle( + r.Left + rm, + r.Top + rm, + r.Width/2, + r.Height/2 ); + g.drawRectangle(lR); + + g.selectPen(g.createPen( + Color.RosyBrown)); + g.drawLine(lR.Left, lR.Top, lR.Right, lR.Bottom); + + + g.selectBrush(g.createSolidBrush(Color.SpringGreen)); + string tn = g.GetType().Name; + g.selectFont(new Font("Tahoma",10,FontStyle.Bold)); + g.setTextColor(Color.Yellow); + g.drawString(tn, r.Left + 3.0f, r.Top + 3.0f); + + g.selectFont(new Font("Tahoma",20,FontStyle.Bold)); + g.setTextColor(Color.Purple); + g.drawString(tn, r.Left + r.Width/2 + 3.0f, r.Top + r.Height/2 + 3.0f); + + g.paint(e.Graphics, 0, 0, 0, 0, r.Width, r.Height); + g.Dispose(); + } + + private void myTest1(PaintEventArgs e) + { + Rectangle r = e.ClipRectangle; + GDI32Wrapper w = new GDI32Wrapper(e.Graphics); + + int margin = 20; + Rectangle R = new Rectangle( + r.Left + margin, r.Top + margin, r.Width/2, r.Height/2); + + w.selectBrush(w.createSolidBrush(Color.Red)); + w.fillRectangle(R); + w.selectPen(w.createPen(Color.Green)); + //w.selectBrush(w.createSolidBrush(Color.Transparent)); + w.selectPen(w.createPen(Color.Yellow)); + w.drawRectangle(R); + w.Dispose(); + } + + protected override void OnPaint(PaintEventArgs e) + { + //myMainTest(e); + myTest1(e); + } + #endregion + } +} diff --git a/src/client/spark/NMSheets/Outside/tc2/GUI/tests/GDITestForm.resx b/src/client/spark/NMSheets/Outside/tc2/GUI/tests/GDITestForm.resx new file mode 100644 index 000000000..3f337e081 --- /dev/null +++ b/src/client/spark/NMSheets/Outside/tc2/GUI/tests/GDITestForm.resx @@ -0,0 +1,42 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 1.0.0.0 + + + 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 + + diff --git a/src/client/spark/NMSheets/Outside/tc2/GUI/tests/PriceOverrideGUITestForm.cs b/src/client/spark/NMSheets/Outside/tc2/GUI/tests/PriceOverrideGUITestForm.cs new file mode 100644 index 000000000..47216f029 --- /dev/null +++ b/src/client/spark/NMSheets/Outside/tc2/GUI/tests/PriceOverrideGUITestForm.cs @@ -0,0 +1,121 @@ +using System; +using System.Drawing; +using System.Collections; +using System.ComponentModel; +using System.Windows.Forms; + +namespace BCG +{ + /// + /// Summary description for PriceOverrideGUITestForm. + /// + public class PriceOverrideGUITestForm : System.Windows.Forms.Form + { + /* + private BCG.PriceOverrideGUI myPriceOverrideGUI; + /// + /// Required designer variable. + /// + private System.ComponentModel.Container components = null; + + public PriceOverrideGUITestForm() + { + // + // Required for Windows Form Designer support + // + InitializeComponent(); + + myPriceOverrideGUI.priceInterval = 0.5; + myPriceOverrideGUI.price = 1123.00; + myPriceOverrideGUI.tickType = + BCG.Utilities.General.TickConverter2.TickType.Tick32; + myPriceOverrideGUI.tickFlavor = + BCG.Utilities.General.TickConverter2.TickFlavor.Normal; + } + + /// + /// Clean up any resources being used. + /// + protected override void Dispose( bool disposing ) + { + if( disposing ) + { + if(components != null) + { + components.Dispose(); + } + } + 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.myPriceOverrideGUI = new BCG.PriceOverrideGUI(); + this.SuspendLayout(); + // + // myPriceOverrideGUI + // + this.myPriceOverrideGUI.Location = new System.Drawing.Point(56, 64); + this.myPriceOverrideGUI.Name = "myPriceOverrideGUI"; + this.myPriceOverrideGUI.Size = new System.Drawing.Size(144, 24); + this.myPriceOverrideGUI.TabIndex = 0; + // + // PriceOverrideGUITestForm + // + this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); + this.ClientSize = new System.Drawing.Size(292, 273); + this.Controls.Add(this.myPriceOverrideGUI); + this.Name = "PriceOverrideGUITestForm"; + this.Text = "PriceOverrideGUITestForm"; + this.ResumeLayout(false); + + } + #endregion + + private void myPriceTextBoxMouseUp(object sender, System.Windows.Forms.MouseEventArgs e) + { + new TCNumPad().Show(); + } + */ + private System.Windows.Forms.ImageList imageList1; + private System.Windows.Forms.Button button1; + private System.ComponentModel.IContainer components; + + private void InitializeComponent() + { + this.components = new System.ComponentModel.Container(); + System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(PriceOverrideGUITestForm)); + this.imageList1 = new System.Windows.Forms.ImageList(this.components); + this.button1 = new System.Windows.Forms.Button(); + this.SuspendLayout(); + // + // imageList1 + // + this.imageList1.ColorDepth = System.Windows.Forms.ColorDepth.Depth16Bit; + this.imageList1.ImageSize = new System.Drawing.Size(16, 16); + this.imageList1.TransparentColor = System.Drawing.Color.Transparent; + // + // button1 + // + this.button1.Image = ((System.Drawing.Image)(resources.GetObject("button1.Image"))); + this.button1.Location = new System.Drawing.Point(144, 64); + this.button1.Name = "button1"; + this.button1.TabIndex = 0; + // + // PriceOverrideGUITestForm + // + this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); + this.ClientSize = new System.Drawing.Size(292, 273); + this.Controls.Add(this.button1); + this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); + this.Name = "PriceOverrideGUITestForm"; + this.ResumeLayout(false); + + } + } +} diff --git a/src/client/spark/NMSheets/Outside/tc2/GUI/tests/PriceOverrideGUITestForm.resx b/src/client/spark/NMSheets/Outside/tc2/GUI/tests/PriceOverrideGUITestForm.resx new file mode 100644 index 000000000..ca1cc960b --- /dev/null +++ b/src/client/spark/NMSheets/Outside/tc2/GUI/tests/PriceOverrideGUITestForm.resx @@ -0,0 +1,188 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Private + + + Private + + + 17, 17 + + + False + + + Private + + + Private + + + + Qk02AwAAAAAAADYAAAAoAAAAEAAAABAAAAABABgAAAAAAAAAAADEDgAAxA4AAAAAAAAAAAAAwMDAwMDA + wMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDA + wMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDA + wMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAYzAxYzAxYzAxYzAxYzAxwMDAwMDAwMDAwMDA + wMDAwMDAwMDAwMDAwMDAwMDAwMDAYzAx3oYp1n0hzmkAYzAxwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDA + wMDAwMDAwMDAYzAx3o453oYp1n0hYzAxwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAYzAxYzAxYzAxYzAx + 55pK3o453oYpYzAxYzAxYzAxYzAxwMDAwMDAwMDAwMDAwMDAYzAx975777Zz76pj56JS55pK3o453oYp + 1n0hzmkAYzAxwMDAwMDAwMDAwMDAwMDAwMDAYzAx975777Zz76pj56JS55pK3o453oYpYzAxwMDAwMDA + wMDAwMDAwMDAwMDAwMDAwMDAYzAx975777Zz76pj56JS55pKYzAxwMDAwMDAwMDAwMDAwMDAwMDAwMDA + wMDAwMDAwMDAYzAx975777Zz76pjYzAxwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDA + YzAx9757YzAxwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAYzAxwMDAwMDA + wMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDA + wMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDA + wMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDA + + + + False + + + PriceOverrideGUITestForm + + + (Default) + + + False + + + False + + + 8, 8 + + + True + + + 80 + + + True + + + Private + + + + AAABAAIAICAQAAAAAADoAgAAJgAAABAQEAAAAAAAKAEAAA4DAAAoAAAAIAAAAEAAAAABAAQAAAAAAAAC + AAAAAAAAAAAAABAAAAAQAAAAAAAAAAAAgAAAgAAAAICAAIAAAACAAIAAgIAAAICAgADAwMAAAAD/AAD/ + AAAA//8A/wAAAP8A/wD//wAA////AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAADMzMwAAAAMzMAAAAAAAAAAAMwAAAAMwAAMAAAAAAAAAADMAAAADMAAAMAAAAAAAAAAzAAAAMwAAA + AAAAAAAAAAAMwAAADMAAAAAAAAAAAAAADMAAAAzAAAAAAAAAAAAAAAzAAAAMwAAAAAAAAAAAAAAMwAAA + DMAAAAwAAAAAAAwADMAAwADMAADMAAmZmQAMAAzAAMAAzAAMzAAAkAkADMzMzMzAAADMwAwAAAkAAAAA + AAAAAAAAAAAAAAAAkAAAAAAAAAAAAAAAAAAAAJAAAAAAAAAAAAAAAAAAAAAJAAAAAAAAAAAAAAAAAAAA + CQAAAAAAAAAAAAAAAAAJAAkAAAAAAAAAAAAAAAAAAJmQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA//////// + ////////////////////////////////////////wD8P/8A8B//AOAP/8Phx//Dw+//w8P//8PD///Dw + +f8QgPGDEIhhAQAIAYEADAHHAA8Z4////+P////x////sf///wH///+D////x/////////////////// + //8oAAAAEAAAACAAAAABAAQAAAAAAMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAgAAAAICAAIAA + AACAAIAAgIAAAICAgADAwMAAAAD/AAD/AAAA//8A/wAAAP8A/wD//wAA////AAAAAAAAAAAAB3d3d3d3 + d3dERERERERER0////////hHT///////+EdP///////4R0////////hHT///////+EdP///////4R0// + //////hHT///////+EdIiIiIiIiIR0zMzMzMzMxHxERERERERMAAAAAAAAAAAAAAAAAAAAAA//8AAIAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAD//wAA//8AAA== + + + \ No newline at end of file diff --git a/src/client/spark/NMSheets/Outside/tc2/Interop/FakeFastOptionBBOStream.cs b/src/client/spark/NMSheets/Outside/tc2/Interop/FakeFastOptionBBOStream.cs new file mode 100644 index 000000000..ea7a49dc4 --- /dev/null +++ b/src/client/spark/NMSheets/Outside/tc2/Interop/FakeFastOptionBBOStream.cs @@ -0,0 +1,202 @@ +// using System; +// using System.Collections.Generic; +// using System.Linq; +// using System.Text; + +// namespace BCG +// { +// public class FastPumperStream : ViewStream, BCG.Utilities.General.IWorker +// { +// private ViewStream _parent_stream; +// private TimeSpan _fire_period; +// public FastPumperStream(ViewStream parent_stream, TimeSpan fire_period) +// { +// _fire_period = fire_period; +// _parent_stream = parent_stream; +// } + +// protected override void myOnFirstSubscriber() +// { +// _parent_stream.onChange += new ChangeDelegate(_handle_change); +// ViewStreamDatabase.instance.addWorker(this); +// } + +// private void _handle_change(object newValue) +// { +// if (myLastValue == null) +// myFireEvent(newValue); +// } + +// protected override void myOnLastSubscriber() +// { +// _parent_stream.onChange -= new ChangeDelegate(_handle_change); +// ViewStreamDatabase.instance.removeWorker(this); +// } + +// private DateTime _last_fire_time = DateTime.MinValue; +// public void doWork() +// { +// if (myLastValue != null) +// { +// if (DateTime.Now - _last_fire_time >= _fire_period) +// { +// _last_fire_time = DateTime.Now; +// DataPacket last_dp = myLastValue as DataPacket; +// myFireEvent(new DataPacket(last_dp.newRows, last_dp.newRows, last_dp.newRows)); +// } +// } +// } +// } + +// public class FakeFastDriverStream : ViewStream, BCG.Utilities.General.IWorker +// { +// private ViewStream _base_stream; +// private TimeSpan _fire_period; +// private double _price_inc; +// private Random _rand = new Random(DateTime.Now.Millisecond); +// private DateTime _last_fire_time = DateTime.MinValue; + +// public FakeFastDriverStream(ViewStream base_stream, int fire_period, double inc) +// : this(base_stream, new TimeSpan(0, 0, 0, 0, fire_period), inc) +// { +// } + +// public FakeFastDriverStream(ViewStream base_stream, TimeSpan fire_period, double inc) +// { +// _base_stream = base_stream; +// _fire_period = fire_period; +// _price_inc = inc; +// } + +// protected override void myOnFirstSubscriber() +// { +// _base_stream.onChange += new ChangeDelegate(_handle_driver_changes); +// ViewStreamDatabase.instance.addWorker(this); +// } + +// private void _handle_driver_changes(object newValue) { } + +// protected override void myOnLastSubscriber() +// { +// _base_stream.onChange -= new ChangeDelegate(_handle_driver_changes); +// ViewStreamDatabase.instance.removeWorker(this); +// } + +// private int _driver_step_count = 0; +// public void doWork() +// { +// if (DateTime.Now - _last_fire_time >= _fire_period) +// { +// if (_base_stream.rows != null && _base_stream.rows.Count > 0) +// { +// IBlueRow r = BlueDataUtility.extractRow(_base_stream.rows, 0); +// MutableBlueRow nr = new MutableBlueRow(r); +// if (r["PRICE"] != DBNull.Value) +// { +// double new_value = (double)r["PRICE"]; +// if (_driver_step_count++ % 20 < 10) +// new_value += _price_inc; +// else +// new_value -= _price_inc; + +// nr.setValue("PRICE", new_value); +// BlueTable nt = new BlueTable(nr.schema); +// nt.addRow(nr); +// _last_fire_time = DateTime.Now; +// myFireEvent(new DataPacket(nt, nt, myLastValue == null ? new BlueTable(nt.schema) : (myLastValue as DataPacket).newRows)); +// } +// } +// } +// } +// } + +// /// +// /// To test the limits of Tc2 this stream pumps in +// /// fast made up bbo for every contract, and +// /// keeps incrementing it +// /// +// public class FakeFastOptionBBOStream : ViewStream, BCG.Utilities.General.IWorker +// { +// private IBlueTableSchema _output_schema = new BlueTableSchema("FakeFastOptionBBOStream", +// new ColumnInfo("id", 0, typeof(int)), +// new ColumnInfo("exp", 1, typeof(DateTime)), +// new ColumnInfo("strike", 2, typeof(Single)), +// new ColumnInfo("isBid", 3, typeof(bool)), +// new ColumnInfo("isCall", 4, typeof(bool)), +// new ColumnInfo("value", 5, typeof(Single)), +// new ColumnInfo("size", 6, typeof(int))); +// private ViewStream _strike_stream; +// private TimeSpan _fire_period = new TimeSpan(0, 0, 0, 0, 25); +// private int _row_change_percentage = 20; +// private Random _rnd = new Random(Guid.NewGuid().GetHashCode()); +// private BCG.Utilities.General.HighPerformanceTimer _timer = new Utilities.General.HighPerformanceTimer(); +// private string _option_symbol; + +// public FakeFastOptionBBOStream(string option_name, TimeSpan fire_period) +// { +// _option_symbol = option_name; +// _strike_stream = new AccessStrikesStream(option_name); +// } + +// protected override void myOnFirstSubscriber() +// { +// _strike_stream.onChange += new ChangeDelegate(_handle_strikes); +// ViewStreamDatabase.instance.addWorker(this); +// } + +// protected override void myOnLastSubscriber() +// { +// _strike_stream.onChange -= new ChangeDelegate(_handle_strikes); +// ViewStreamDatabase.instance.removeWorker(this); +// } + +// private void _handle_strikes(object newValue) +// { +// if (myLastValue == null) +// { +// BlueTable new_table = new BlueTable(_output_schema); +// int id = 0; +// foreach (IBlueRow r in (newValue as DataPacket).newRows) +// { +// DateTime exp = (DateTime)r["expiration"]; +// float strike = Convert.ToSingle (r["strike"]); +// new_table.addRow(new BlueRow(_output_schema, id++, exp, strike, true, true, (float)0, (int)0)); +// new_table.addRow(new BlueRow(_output_schema, id++, exp, strike, true, false, (float)0, (int)0)); +// new_table.addRow(new BlueRow(_output_schema, id++, exp, strike, false, true, (float)0, (int)0)); +// new_table.addRow(new BlueRow(_output_schema, id++, exp, strike, false, false, (float)0, (int)0)); +// } +// myFireEvent(new DataPacket(new_table, new_table, new BlueTable(_output_schema))); +// } +// } + +// private DateTime _last_dowork_time = DateTime.MinValue; +// public void doWork() +// { +// if (DateTime.Now - _last_dowork_time >= _fire_period) +// { +// _last_dowork_time = DateTime.Now; +// if (myLastValue != null) +// { +// _timer.start(); +// BlueTable new_table = new BlueTable(_output_schema); +// foreach (IBlueRow r in (myLastValue as DataPacket).newRows) +// { +// if (_rnd.Next(100) <= _row_change_percentage) +// { +// int size = (int)r["size"]; +// float price = (float)r["value"]; +// new_table.addRow(new BlueRow(_output_schema, r["id"], r["exp"], Convert.ToSingle(r["strike"]), r["isBid"], r["isCall"], (float)(price + 0.1), (int)(size + 1))); +// } +// else +// { +// new_table.addRow(r); +// } +// } +// myFireEvent(new DataPacket(new_table, new_table, (myLastValue as DataPacket).newRows)); +// _timer.stop(); +// BCG.Utilities.BlueEventLog.logEvent(String.Format("FakeFastOptionBBOStream {0}, doWork time = {1} msecs", _option_symbol, _timer.lastIntervalTime)); +// } +// } +// } +// } +// } diff --git a/src/client/spark/NMSheets/Outside/tc2/Interop/StreamAbstraction.cs b/src/client/spark/NMSheets/Outside/tc2/Interop/StreamAbstraction.cs new file mode 100644 index 000000000..90d17ac42 --- /dev/null +++ b/src/client/spark/NMSheets/Outside/tc2/Interop/StreamAbstraction.cs @@ -0,0 +1,86 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +using BCG.Utilities; +using BCG.Utilities.General; + +namespace BCG { + public class StreamAbstraction { + #region Trader based streams + + // public class ShellMMTNPendingReponseStream : ViewStream + // { + // public ShellMMTNPendingReponseStream(string trader, mbts.pubsub.PubsubHub hub) + // { + // ViewStream ros = ShellStreamFactory.getStream(typeof(CBOEMMTNStream), trader, hub); + // ros = new FilterStream(ros, String.Format("status='{0}'", bts.mmtn.FloorTrade.State.PENDING_TRADER_RESPONSE.ToString())); + // mySetRealSource(ros); + // } + // } + + // public class ShellMMTNStatusStream : ViewStream + // { + // public ShellMMTNStatusStream(string trader, mbts.pubsub.PubsubHub hub) + // { + // ViewStream ros = ShellStreamFactory.getStream(typeof(CBOEMMTNStream), trader, hub); + // ros = new FilterStream(ros, String.Format("status<>'{0}'", bts.mmtn.FloorTrade.State.PENDING_TRADER_RESPONSE.ToString())); + // mySetRealSource(ros); + // } + // } + + // #endregion + + // #region Misc + + // public class ShellSpreadMarketDepthStream : ViewStream + // { + // public ShellSpreadMarketDepthStream(string security_type, string security_name, string security_exchange) + // { + // mySetRealSource(new LiveMDProxy("Depth", "Spread", security_name, security_exchange)); + // } + // } + + // public class ShellFutureDepthStream : ViewStream + // { + // public ShellFutureDepthStream(string future_symbol, string exchange, DateTime exp) + // { + // ViewStream ros = new LiveMDProxy("Depth", "Future", future_symbol, exchange); + // ros = new FilterStream(ros, String.Format("security_expiration = {0}", exp)); + // mySetRealSource(ros); + // } + // } + + // public class ShellOrdersStream : ViewStream + // { + // public ShellOrdersStream(Blackboard bb, string user) + // { + // ViewStream ros = ShellStreamFactory.getStream(typeof(CombinedO2OrdersStream), bb, user); + // mySetRealSource(ros); + // } + // } + + // #endregion + + // #region Paramterless streams + + // public class ShellNameStream : ViewStream + // { + // public ShellNameStream() + // { + // ViewStream group_names_stream = new AddColumnsStream(new TableStream("bcggroup"), String.Format("type='{0}'", "symbol_group")); + // mySetRealSource(new MutableAppendStream(group_names_stream, new NameStream())); + // } + // } + + // public class OptionExpirationInfoStream : ViewStream + // { + // /// TODO Remove + // public OptionExpirationInfoStream() { + // } + //} + + #endregion + } +} \ No newline at end of file diff --git a/src/client/spark/NMSheets/Outside/tc2/Misc/ShellMiscSettings.cs b/src/client/spark/NMSheets/Outside/tc2/Misc/ShellMiscSettings.cs new file mode 100644 index 000000000..217418092 --- /dev/null +++ b/src/client/spark/NMSheets/Outside/tc2/Misc/ShellMiscSettings.cs @@ -0,0 +1,29 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace BCG { + [Serializable] + public class ShellMiscSettings : ICloneable { + private string _internal_accounts = String.Empty; + public string InternalAccounts { + get { return _internal_accounts; } + set { _internal_accounts = value; } + } + + private string _contra_traders = String.Empty; + public string ContraTraders { + get { return _contra_traders; } + set { _contra_traders = value; } + } + + private string _contra_firms = String.Empty; + public string ContraFirms { + get { return _contra_firms; } + set { _contra_firms = value; } + } + + public object Clone() { return MemberwiseClone(); } + } +} diff --git a/src/client/spark/NMSheets/Outside/tc2/Misc/ShellMiscSettingsTag.cs b/src/client/spark/NMSheets/Outside/tc2/Misc/ShellMiscSettingsTag.cs new file mode 100644 index 000000000..fb90fe6d4 --- /dev/null +++ b/src/client/spark/NMSheets/Outside/tc2/Misc/ShellMiscSettingsTag.cs @@ -0,0 +1,10 @@ +using mbts.bb; +using System; + +namespace BCG +{ + [Serializable] + public class ShellMiscSettingsTag : EqualsHelper, IConfigTag + { + } +} diff --git a/src/client/spark/NMSheets/Outside/tc2/PerfStatsLogger.cs b/src/client/spark/NMSheets/Outside/tc2/PerfStatsLogger.cs new file mode 100644 index 000000000..769a77143 --- /dev/null +++ b/src/client/spark/NMSheets/Outside/tc2/PerfStatsLogger.cs @@ -0,0 +1,44 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace BCG { + public class PerfStatsLogger { + private Dictionary> _entry_map = new Dictionary>(); + private readonly int _log_period_updates, _max_size; + private DateTime _last_write_time = DateTime.Now; + + public PerfStatsLogger() : this(100, 200) { } + + /// + /// log_period_updates tells how often are the stats logged + /// max_size is the max size of the sample before it is cleaned out + /// + /// + /// + public PerfStatsLogger(int log_period_updates, int max_size) { + _log_period_updates = log_period_updates; + _max_size = max_size; + } + + public void log(string id, string msg, double time) { + List logs = null; + if (!_entry_map.TryGetValue(id, out logs)) + _entry_map.Add(id, logs = new List()); + logs.Add(time); + if (logs.Count > 0 && logs.Count % _log_period_updates == 0) { + TimeSpan period = DateTime.Now - _last_write_time; + _last_write_time = DateTime.Now; + logs.Sort(); + double sum = 0; + logs.ForEach(d => sum += d); + bts.Log.Ui.info(String.Format("{0}\nsample_size={1} min={2:0.00} max={3:0.00} mean={4:0.00} median={5:0.00} upate period={6:0.00} updates per sec={7:0.00}", + msg, logs.Count, logs[0], logs[logs.Count - 1], sum / logs.Count, logs[logs.Count / 2], period.TotalMilliseconds, 1000.0 * logs.Count / period.TotalMilliseconds)); + } + if (logs.Count >= _max_size) + logs.Clear(); + } + } +} diff --git a/src/client/spark/NMSheets/Outside/tc2/Spread/Agents/SpreadManager.cs b/src/client/spark/NMSheets/Outside/tc2/Spread/Agents/SpreadManager.cs new file mode 100644 index 000000000..387072e4b --- /dev/null +++ b/src/client/spark/NMSheets/Outside/tc2/Spread/Agents/SpreadManager.cs @@ -0,0 +1,259 @@ +using System; +using System.Windows.Forms; +using System.Collections; +using System.Collections.Generic; +using BCG.Utilities; + +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 SpreadManager : IAgent { + // public enum SpreadInitialization { + // DoubleClickSystem = 0, + // SingleClickSytstem = 1, + // LeftClickBuyRightClickSell = 2, + // RightUpSwipeBuyRightDownSwipeSell = 3 + // } + + // private Blackboard myBB; + // private readonly string _user; + + // public SpreadManager(Blackboard bb, string user) { + // myBB = bb; + // _user = user; + // myBB.join(this); + // } + + // #region IAgent Members + + // public void begin() { } + + // public void change(object tag) { + // if (tag.Equals(new AddSpreadLegTag())) { + // AddSpreadLegMessage m = myBB.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 = myBB.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) + // myBB.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, Venue 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 = myBB.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 object mySearchLocking(object current) { + // object locked = myBB.read(new SpreadLockedTag(current)); + // if (current != null && locked != null && !(bool)locked) + // return current; + // else { + // ArrayList remove = new ArrayList(); + // object ret = null; + // foreach (object o in mySpreadIds.Keys) { + // locked = myBB.read(new SpreadLockedTag(o)); + // if (locked == null) { + // remove.Add(o); + // continue; + // } + // if (!(bool)locked) + // ret = o; + // } + // foreach (object o in remove) + // mySpreadIds.Remove(o); + // 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 { + // object currentSpreadId = myBB.read(new CurrentSpreadTag()); + // currentSpreadId = mySearchLocking(currentSpreadId); + // if (currentSpreadId != null) { + // SpreadSpec spreadSpec = myBB.read(new SpreadSpecTag(currentSpreadId)) as SpreadSpec; + // BlueEventLog.logAssert(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(myBB) ?? 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); + // myBB.write(new 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); + // myBB.write(new 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 newSpreadSpec, Control originForm, bool originatedExternally, SpreadInititialState initial_state, string user) { + // object newSpreadId = myGetNewSpreadId(); + // myBB.write(new SpreadLockedTag(newSpreadId), false); + // myBB.write(new SpreadSpecTag(newSpreadId), newSpreadSpec); + // myBB.write(new CurrentSpreadTag(), newSpreadId); + // myCreateSpreadSpecificAgents(myBB, newSpreadSpec, newSpreadId, originForm, originatedExternally, initial_state, user); + // return newSpreadId; + // } + + // private object myCreateBrandNewSpread(OptionContract newLegContract, PriceSpec newLegPriceSpec, int newLegSize, Control originForm, bool originatedExternally, SpreadInititialState initial_state, string user) { + // object newSpreadId = myGetNewSpreadId(); + // myBB.write(new SpreadLockedTag(newSpreadId), false); + // SpreadSpec newSpreadSpec = new SpreadSpec(new OptionContractPosition[] { new OptionContractPosition(newLegContract, newLegSize, newLegPriceSpec) }); + // //myBB.write(new SpreadInitialTradingSideHintTag(newSpreadId), hint); + // myBB.write(new SpreadSpecTag(newSpreadId), newSpreadSpec); + // //also create a spread form here + // myBB.write(new CurrentSpreadTag(), newSpreadId); + // myCreateSpreadSpecificAgents(myBB, newSpreadSpec, newSpreadId, originForm, originatedExternally, initial_state, user); + // return newSpreadId; + // } + + // private void myCreateSpreadSpecificAgents(Blackboard forBB, SpreadSpec newSpreadSpec, object usingTag, Control originForm, bool originatedExternally, SpreadInititialState initial_state, string user) { + // 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 { + // //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; + // BlueEventLog.logAssert(newLegPriceSpec.primaryDriverSymbol == existingPriceSpec.primaryDriverSymbol && + // newLegPriceSpec.driverExpiration == existingPriceSpec.driverExpiration); + // } + // return new OptionContractPosition(newLegContract, newLegSize, newLegPriceSpec); + // } + + // /// list of all open spreads + // private Hashtable mySpreadIds = new Hashtable(); + // private object myGetNewSpreadId() { + // Guid g = Guid.NewGuid(); + // mySpreadIds[g] = null; + // return g; + // } + // } + + +} diff --git a/src/client/spark/NMSheets/Outside/tc2/Spread/BlackboardStructure/AddSpreadLegTag.cs b/src/client/spark/NMSheets/Outside/tc2/Spread/BlackboardStructure/AddSpreadLegTag.cs new file mode 100644 index 000000000..99972c2c2 --- /dev/null +++ b/src/client/spark/NMSheets/Outside/tc2/Spread/BlackboardStructure/AddSpreadLegTag.cs @@ -0,0 +1,12 @@ +using mbts.bb; + +using System; + +namespace BCG { + /// + /// Specifies a new leg of a spread + /// + public class AddSpreadLegTag : EqualsHelper { + public AddSpreadLegTag() { } + } +} diff --git a/src/client/spark/NMSheets/Outside/tc2/Spread/BlackboardStructure/ExternalSpreadTradeRequestTag.cs b/src/client/spark/NMSheets/Outside/tc2/Spread/BlackboardStructure/ExternalSpreadTradeRequestTag.cs new file mode 100644 index 000000000..45de209ab --- /dev/null +++ b/src/client/spark/NMSheets/Outside/tc2/Spread/BlackboardStructure/ExternalSpreadTradeRequestTag.cs @@ -0,0 +1,21 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace BCG +{ + public class ExternalSpreadTradeRequestTag : ITag + { + public override bool Equals(object obj) + { + return obj != null && obj.GetType().Equals(GetType()); + } + + public override int GetHashCode() + { + return GetType().GetHashCode(); + } + + } +} diff --git a/src/client/spark/NMSheets/Outside/tc2/Spread/BlackboardStructure/KillSpreadTag.cs b/src/client/spark/NMSheets/Outside/tc2/Spread/BlackboardStructure/KillSpreadTag.cs new file mode 100644 index 000000000..30864fab7 --- /dev/null +++ b/src/client/spark/NMSheets/Outside/tc2/Spread/BlackboardStructure/KillSpreadTag.cs @@ -0,0 +1,18 @@ +using System; +using BCG; +using BCG.Utilities; +using mbts.bb; + +namespace BCG +{ + public class PostTradeTag : EqualsHelper { } + + /// + /// The object mapped by this tag identifies a spread + /// that should be terminated. + /// + + public class KillSpreadTag : EqualsHelper + {} + +} diff --git a/src/client/spark/NMSheets/Outside/tc2/Spread/BlackboardStructure/SpreadInitialTradingSideHintTag.cs b/src/client/spark/NMSheets/Outside/tc2/Spread/BlackboardStructure/SpreadInitialTradingSideHintTag.cs new file mode 100644 index 000000000..dd3441ad5 --- /dev/null +++ b/src/client/spark/NMSheets/Outside/tc2/Spread/BlackboardStructure/SpreadInitialTradingSideHintTag.cs @@ -0,0 +1,14 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace BCG +{ + public class SpreadInitialTradingSideHintTag : SpreadTag + { + public SpreadInitialTradingSideHintTag(object name) + : base(name) + { } + } +} diff --git a/src/client/spark/NMSheets/Outside/tc2/Spread/BlackboardStructure/SpreadLockedTag.cs b/src/client/spark/NMSheets/Outside/tc2/Spread/BlackboardStructure/SpreadLockedTag.cs new file mode 100644 index 000000000..dfa989097 --- /dev/null +++ b/src/client/spark/NMSheets/Outside/tc2/Spread/BlackboardStructure/SpreadLockedTag.cs @@ -0,0 +1,14 @@ +using System; +using System.Collections.Generic; +using System.Text; +using BCG.Utilities; + +namespace BCG +{ + public class SpreadLockedTag : SpreadTag + { + public SpreadLockedTag(object name) : base(name) + { + } + } +} diff --git a/src/client/spark/NMSheets/Outside/tc2/Spread/BlackboardStructure/SpreadSpecTag.cs b/src/client/spark/NMSheets/Outside/tc2/Spread/BlackboardStructure/SpreadSpecTag.cs new file mode 100644 index 000000000..e0904d207 --- /dev/null +++ b/src/client/spark/NMSheets/Outside/tc2/Spread/BlackboardStructure/SpreadSpecTag.cs @@ -0,0 +1,15 @@ +using System; +using BCG; +using BCG.Utilities; + +namespace BCG +{ + /// + /// Maps to a SpreadSpec object, describing a given spread. + /// + public class SpreadSpecTag : SpreadTag + { + public SpreadSpecTag (object name) : base(name) + {} + } +} diff --git a/src/client/spark/NMSheets/Outside/tc2/Spread/BlackboardStructure/SpreadSummaryDisplayTag.cs b/src/client/spark/NMSheets/Outside/tc2/Spread/BlackboardStructure/SpreadSummaryDisplayTag.cs new file mode 100644 index 000000000..8b2c64812 --- /dev/null +++ b/src/client/spark/NMSheets/Outside/tc2/Spread/BlackboardStructure/SpreadSummaryDisplayTag.cs @@ -0,0 +1,13 @@ +using mbts.bb; +using System; + +namespace BCG +{ + /// + /// Indiactes whether to display teh spread summary form or not + /// + public class SpreadSummaryDisplayTag : EqualsHelper + { + public SpreadSummaryDisplayTag() {} + } +} diff --git a/src/client/spark/NMSheets/Outside/tc2/Spread/BlackboardStructure/SpreadTag.cs b/src/client/spark/NMSheets/Outside/tc2/Spread/BlackboardStructure/SpreadTag.cs new file mode 100644 index 000000000..2316492ac --- /dev/null +++ b/src/client/spark/NMSheets/Outside/tc2/Spread/BlackboardStructure/SpreadTag.cs @@ -0,0 +1,44 @@ +using System; + +using BCG; +using BCG.Utilities; + +namespace BCG { + public class SpreadTag : NamedTag { + public SpreadTag(object name) + : base(name) { } + } + + public class NamedTag : ITag { + public readonly object name; + + public NamedTag(object name) { this.name = name; } + + public override bool Equals(object obj) { + return obj != null && + obj.GetType().Equals(this.GetType()) && + ((name == null && (obj as NamedTag).name == null) || ((name != null && (obj as NamedTag).name != null) && name.Equals((obj as NamedTag).name))); + } + + public override int GetHashCode() { return name == null ? base.GetHashCode() : name.GetHashCode(); } + + public override string ToString() { return this.GetType().Name + (name == null ? "" : (" " + name)); } + } + + public class KeyedTag : ITag { + public KeyedTag(T key) { + bts.Log.assert(key != null); + this.key = key; + } + + public readonly T key; + + public override bool Equals(object obj) { + return obj != null && obj.GetType().Equals(this.GetType()) && ((KeyedTag)obj).key.Equals(key); + } + + public override int GetHashCode() { + return key.GetHashCode(); + } + } +} diff --git a/src/client/spark/NMSheets/Outside/tc2/Spread/BlackboardStructure/SpreadValueTag.cs b/src/client/spark/NMSheets/Outside/tc2/Spread/BlackboardStructure/SpreadValueTag.cs new file mode 100644 index 000000000..16e184e0d --- /dev/null +++ b/src/client/spark/NMSheets/Outside/tc2/Spread/BlackboardStructure/SpreadValueTag.cs @@ -0,0 +1,16 @@ +using System; +using BCG; +using BCG.Utilities; + +namespace BCG +{ + /// + /// Maps to SpreadValue object that denotes the theos associated with + /// a given spread. + /// + public class SpreadValueTag : SpreadTag + { + public SpreadValueTag(object name) : base(name) + {} + } +} diff --git a/src/client/spark/NMSheets/Outside/tc2/Spread/BlackboardStructure/SpreadWindowMinimizeTag.cs b/src/client/spark/NMSheets/Outside/tc2/Spread/BlackboardStructure/SpreadWindowMinimizeTag.cs new file mode 100644 index 000000000..85f63e8cf --- /dev/null +++ b/src/client/spark/NMSheets/Outside/tc2/Spread/BlackboardStructure/SpreadWindowMinimizeTag.cs @@ -0,0 +1,11 @@ +using mbts.bb; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace BCG +{ + public class SpreadWindowMinimizeTag : EqualsHelper { } +} diff --git a/src/client/spark/NMSheets/Outside/tc2/Spread/GUI/SpreadLegDisplayOrder.cs b/src/client/spark/NMSheets/Outside/tc2/Spread/GUI/SpreadLegDisplayOrder.cs new file mode 100644 index 000000000..2d08e5f1e --- /dev/null +++ b/src/client/spark/NMSheets/Outside/tc2/Spread/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/NMSheets/Outside/tc2/Spread/GUI/TCNumPad.cs b/src/client/spark/NMSheets/Outside/tc2/Spread/GUI/TCNumPad.cs new file mode 100644 index 000000000..69e4aa0da --- /dev/null +++ b/src/client/spark/NMSheets/Outside/tc2/Spread/GUI/TCNumPad.cs @@ -0,0 +1,426 @@ +using System; +using System.Drawing; +using System.Collections; +using System.ComponentModel; +using System.Windows.Forms; + +namespace BCG +{ + public class TCNumPad : Form + { + private string mySeparator; + private Keys[] mySeparatorKeyCodes; + + private System.Windows.Forms.Panel myNumPanel; + private System.Windows.Forms.TextBox myDisplayText; + private System.Windows.Forms.Button myCancelButton; + private System.Windows.Forms.Button myOkButton; + private System.Windows.Forms.Button myButton7; + private System.Windows.Forms.Button myButton8; + private System.Windows.Forms.Button myButton9; + private System.Windows.Forms.Button myButton4; + private System.Windows.Forms.Button myButton5; + private System.Windows.Forms.Button myButton6; + private System.Windows.Forms.Button myButton1; + private System.Windows.Forms.Button myButton2; + private System.Windows.Forms.Button myButton3; + private System.Windows.Forms.Button myButtonCE; + private System.Windows.Forms.Button myButtonDot; + private System.Windows.Forms.Button myButton0; + /// + /// Required designer variable. + /// + private System.ComponentModel.Container components = null; + + public TCNumPad () + {myInit("value",".");} + + public TCNumPad (string caption) + {myInit(caption, ".");} + + public TCNumPad (string caption, string separator) + {myInit(caption, separator);} + + private void myInit(string caption, string separator) + { + InitializeComponent(); + Text = caption; + + mySeparator = separator; + myButtonDot.Text = mySeparator; + + if (mySeparator == ".") + mySeparatorKeyCodes = new Keys[] + { + Keys.Decimal,Keys.OemPeriod + }; + else + mySeparatorKeyCodes = new Keys[] + { + Keys.OemMinus,Keys.Subtract + }; + } + + private string myCE = "CE"; + private bool myIsCE(string c) + { + return c.Equals(myCE); + } + + /// + /// Clean up any resources being used. + /// + protected override void Dispose( bool disposing ) + { + if( disposing ) + { + if(components != null) + { + components.Dispose(); + } + } + 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.myNumPanel = new System.Windows.Forms.Panel(); + this.myButton0 = new System.Windows.Forms.Button(); + this.myButtonDot = new System.Windows.Forms.Button(); + this.myButtonCE = new System.Windows.Forms.Button(); + this.myButton3 = new System.Windows.Forms.Button(); + this.myButton2 = new System.Windows.Forms.Button(); + this.myButton1 = new System.Windows.Forms.Button(); + this.myButton6 = new System.Windows.Forms.Button(); + this.myButton5 = new System.Windows.Forms.Button(); + this.myButton4 = new System.Windows.Forms.Button(); + this.myButton9 = new System.Windows.Forms.Button(); + this.myButton8 = new System.Windows.Forms.Button(); + this.myButton7 = new System.Windows.Forms.Button(); + this.myDisplayText = new System.Windows.Forms.TextBox(); + this.myCancelButton = new System.Windows.Forms.Button(); + this.myOkButton = new System.Windows.Forms.Button(); + this.myNumPanel.SuspendLayout(); + this.SuspendLayout(); + // + // myNumPanel + // + this.myNumPanel.Controls.Add(this.myButton0); + this.myNumPanel.Controls.Add(this.myButtonDot); + this.myNumPanel.Controls.Add(this.myButtonCE); + this.myNumPanel.Controls.Add(this.myButton3); + this.myNumPanel.Controls.Add(this.myButton2); + this.myNumPanel.Controls.Add(this.myButton1); + this.myNumPanel.Controls.Add(this.myButton6); + this.myNumPanel.Controls.Add(this.myButton5); + this.myNumPanel.Controls.Add(this.myButton4); + this.myNumPanel.Controls.Add(this.myButton9); + this.myNumPanel.Controls.Add(this.myButton8); + this.myNumPanel.Controls.Add(this.myButton7); + this.myNumPanel.Location = new System.Drawing.Point(0, 24); + this.myNumPanel.Name = "myNumPanel"; + this.myNumPanel.Size = new System.Drawing.Size(112, 117); + this.myNumPanel.TabIndex = 0; + // + // myButton0 + // + this.myButton0.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); + this.myButton0.Location = new System.Drawing.Point(4, 88); + this.myButton0.Name = "myButton0"; + this.myButton0.Size = new System.Drawing.Size(32, 25); + this.myButton0.TabIndex = 9; + this.myButton0.Text = "0"; + this.myButton0.Click += new System.EventHandler(this.l_Click); + // + // myButtonDot + // + this.myButtonDot.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); + this.myButtonDot.Location = new System.Drawing.Point(40, 88); + this.myButtonDot.Name = "myButtonDot"; + this.myButtonDot.Size = new System.Drawing.Size(32, 25); + this.myButtonDot.TabIndex = 10; + this.myButtonDot.Text = "."; + this.myButtonDot.Click += new System.EventHandler(this.l_Click); + // + // myButtonCE + // + this.myButtonCE.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); + this.myButtonCE.ForeColor = System.Drawing.Color.Red; + this.myButtonCE.Location = new System.Drawing.Point(76, 88); + this.myButtonCE.Name = "myButtonCE"; + this.myButtonCE.Size = new System.Drawing.Size(32, 25); + this.myButtonCE.TabIndex = 11; + this.myButtonCE.Text = "CE"; + this.myButtonCE.Click += new System.EventHandler(this.l_Click); + // + // myButton3 + // + this.myButton3.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); + this.myButton3.Location = new System.Drawing.Point(76, 60); + this.myButton3.Name = "myButton3"; + this.myButton3.Size = new System.Drawing.Size(32, 25); + this.myButton3.TabIndex = 8; + this.myButton3.Text = "3"; + this.myButton3.Click += new System.EventHandler(this.l_Click); + // + // myButton2 + // + this.myButton2.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); + this.myButton2.Location = new System.Drawing.Point(40, 60); + this.myButton2.Name = "myButton2"; + this.myButton2.Size = new System.Drawing.Size(32, 25); + this.myButton2.TabIndex = 7; + this.myButton2.Text = "2"; + this.myButton2.Click += new System.EventHandler(this.l_Click); + // + // myButton1 + // + this.myButton1.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); + this.myButton1.Location = new System.Drawing.Point(4, 60); + this.myButton1.Name = "myButton1"; + this.myButton1.Size = new System.Drawing.Size(32, 25); + this.myButton1.TabIndex = 6; + this.myButton1.Text = "1"; + this.myButton1.Click += new System.EventHandler(this.l_Click); + // + // myButton6 + // + this.myButton6.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); + this.myButton6.Location = new System.Drawing.Point(76, 32); + this.myButton6.Name = "myButton6"; + this.myButton6.Size = new System.Drawing.Size(32, 25); + this.myButton6.TabIndex = 5; + this.myButton6.Text = "6"; + this.myButton6.Click += new System.EventHandler(this.l_Click); + // + // myButton5 + // + this.myButton5.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); + this.myButton5.Location = new System.Drawing.Point(40, 32); + this.myButton5.Name = "myButton5"; + this.myButton5.Size = new System.Drawing.Size(32, 25); + this.myButton5.TabIndex = 4; + this.myButton5.Text = "5"; + this.myButton5.Click += new System.EventHandler(this.l_Click); + // + // myButton4 + // + this.myButton4.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); + this.myButton4.Location = new System.Drawing.Point(4, 32); + this.myButton4.Name = "myButton4"; + this.myButton4.Size = new System.Drawing.Size(32, 25); + this.myButton4.TabIndex = 3; + this.myButton4.Text = "4"; + this.myButton4.Click += new System.EventHandler(this.l_Click); + // + // myButton9 + // + this.myButton9.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); + this.myButton9.Location = new System.Drawing.Point(76, 4); + this.myButton9.Name = "myButton9"; + this.myButton9.Size = new System.Drawing.Size(32, 24); + this.myButton9.TabIndex = 2; + this.myButton9.Text = "9"; + this.myButton9.Click += new System.EventHandler(this.l_Click); + // + // myButton8 + // + this.myButton8.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); + this.myButton8.Location = new System.Drawing.Point(40, 4); + this.myButton8.Name = "myButton8"; + this.myButton8.Size = new System.Drawing.Size(32, 24); + this.myButton8.TabIndex = 1; + this.myButton8.Text = "8"; + this.myButton8.Click += new System.EventHandler(this.l_Click); + // + // myButton7 + // + this.myButton7.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); + this.myButton7.Location = new System.Drawing.Point(4, 4); + this.myButton7.Name = "myButton7"; + this.myButton7.Size = new System.Drawing.Size(32, 24); + this.myButton7.TabIndex = 0; + this.myButton7.Text = "7"; + this.myButton7.Click += new System.EventHandler(this.l_Click); + // + // myDisplayText + // + this.myDisplayText.BackColor = System.Drawing.Color.FromArgb(((System.Byte)(255)), ((System.Byte)(224)), ((System.Byte)(192))); + this.myDisplayText.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; + this.myDisplayText.Dock = System.Windows.Forms.DockStyle.Top; + this.myDisplayText.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); + this.myDisplayText.Location = new System.Drawing.Point(0, 0); + this.myDisplayText.Name = "myDisplayText"; + this.myDisplayText.ReadOnly = true; + this.myDisplayText.Size = new System.Drawing.Size(114, 21); + this.myDisplayText.TabIndex = 14; + this.myDisplayText.Text = ""; + this.myDisplayText.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; + // + // myCancelButton + // + this.myCancelButton.DialogResult = System.Windows.Forms.DialogResult.Cancel; + this.myCancelButton.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); + this.myCancelButton.Location = new System.Drawing.Point(40, 144); + this.myCancelButton.Name = "myCancelButton"; + this.myCancelButton.Size = new System.Drawing.Size(68, 25); + this.myCancelButton.TabIndex = 13; + this.myCancelButton.Text = "Cancel"; + // + // myOkButton + // + this.myOkButton.DialogResult = System.Windows.Forms.DialogResult.OK; + this.myOkButton.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); + this.myOkButton.Location = new System.Drawing.Point(4, 144); + this.myOkButton.Name = "myOkButton"; + this.myOkButton.Size = new System.Drawing.Size(32, 25); + this.myOkButton.TabIndex = 12; + this.myOkButton.Text = "OK"; + // + // TCNumPad + // + this.AcceptButton = this.myOkButton; + this.AutoScaleBaseSize = new System.Drawing.Size(5, 14); + this.BackColor = System.Drawing.SystemColors.Control; + this.CancelButton = this.myCancelButton; + this.ClientSize = new System.Drawing.Size(114, 175); + this.Controls.Add(this.myCancelButton); + this.Controls.Add(this.myOkButton); + this.Controls.Add(this.myDisplayText); + this.Controls.Add(this.myNumPanel); + this.ForeColor = System.Drawing.SystemColors.ControlText; + this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; + this.KeyPreview = true; + this.MaximizeBox = false; + this.MinimizeBox = false; + this.Name = "TCNumPad"; + this.StartPosition = System.Windows.Forms.FormStartPosition.Manual; + this.Text = "Value"; + this.TopMost = true; + this.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.myTCNumPad_KeyPress); + this.KeyUp += new System.Windows.Forms.KeyEventHandler(this.myTCNumPad_KeyUp); + this.myNumPanel.ResumeLayout(false); + this.ResumeLayout(false); + + } + #endregion + + private void l_Click(object sender, EventArgs e) + { + string s = ((Button)sender).Text; + myHandleInput(s); + } + + public double asNumber + { + get + { + try + { + return Convert.ToDouble(myGetNumberString(myDisplayText.Text)); + } + catch (Exception) + {return 0;} + } + set + { + myDisplayText.Text = value.ToString("D2"); + } + } + + public string asText + { + get + { + return + (myDisplayText.Text.StartsWith(mySeparator)? "0" : "") + myDisplayText.Text; + } + } + + private string myGetNumberString (string fromInputString) + { + string ss = + myDisplayText.Text.Replace(mySeparator,"."); + if (ss.StartsWith(".")) + return "0" + ss; + else + return ss; + } + + + private void myHandleInput(string s) + { + string oldDisplay = myDisplayText.Text; + + if ( myIsCE(s) ) + { + if ( myDisplayText.Text.Length > 0 ) + { + myDisplayText.Text = + myDisplayText.Text.Substring(0, myDisplayText.Text.Length-1); + } + } + else + { + myDisplayText.Text = myDisplayText.Text + s; + } + + double tmp; + if ( myDisplayText.Text != string.Empty && + !Double.TryParse(myGetNumberString(myDisplayText.Text), + System.Globalization.NumberStyles.Any, + System.Globalization.NumberFormatInfo.CurrentInfo, out tmp)) + { + MessageBox.Show(this, "Invalid input: " + s, "TC2 NumPad", + MessageBoxButtons.OK, MessageBoxIcon.Error); + myDisplayText.Text = oldDisplay; + } + } + + protected override bool ProcessCmdKey(ref Message msg, Keys keyData) + { + if (keyData.Equals(Keys.Enter)) + { + DialogResult = DialogResult.OK; + return true; + } + else + return base.ProcessCmdKey (ref msg, keyData); + } + + public DialogResult myShowDialog () + { + Top = Control.MousePosition.Y; + Left = Control.MousePosition.X; + return ShowDialog (); + } + + private void myTCNumPad_KeyUp(object sender, KeyEventArgs e) + { + if ( e.KeyCode >= Keys.D0 && e.KeyCode <= Keys.D9 || + e.KeyCode >= Keys.NumPad0 && e.KeyCode <= Keys.NumPad9 ) + { + string keyEnum = e.KeyCode.ToString(); + myHandleInput(keyEnum.Substring(keyEnum.Length-1,1)); + } + else if (Array.IndexOf(mySeparatorKeyCodes,e.KeyCode) != -1) + { + myHandleInput(mySeparator); + } + else if (e.KeyCode == Keys.Back) + { + myHandleInput(myCE); + } + } + + private void myTCNumPad_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e) + { + e.Handled = true; + } + } +} diff --git a/src/client/spark/NMSheets/Outside/tc2/Spread/GUI/TCNumPad.resx b/src/client/spark/NMSheets/Outside/tc2/Spread/GUI/TCNumPad.resx new file mode 100644 index 000000000..d58980a38 --- /dev/null +++ b/src/client/spark/NMSheets/Outside/tc2/Spread/GUI/TCNumPad.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/NMSheets/Outside/tc2/Spread/GUI/WindowStartupLocation.cs b/src/client/spark/NMSheets/Outside/tc2/Spread/GUI/WindowStartupLocation.cs new file mode 100644 index 000000000..16d82712e --- /dev/null +++ b/src/client/spark/NMSheets/Outside/tc2/Spread/GUI/WindowStartupLocation.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 WindowStartupLocation + { + SystemDetermined = 0, + LastWindowLocation = 1 + } +} diff --git a/src/client/spark/NMSheets/Outside/tc2/Spread/Trading/LastContraTag.cs b/src/client/spark/NMSheets/Outside/tc2/Spread/Trading/LastContraTag.cs new file mode 100644 index 000000000..4542181ac --- /dev/null +++ b/src/client/spark/NMSheets/Outside/tc2/Spread/Trading/LastContraTag.cs @@ -0,0 +1,14 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace BCG +{ + /// Corresponding data is Pair of contra trader/firm in that order + [Serializable] + public class LastContraTag : ProductTag, IConfigTag + { + public LastContraTag(string option_symbol) : base(option_symbol) { } + } +} diff --git a/src/client/spark/NMSheets/Outside/tc2/Spread/Trading/SpreadMDTag.cs b/src/client/spark/NMSheets/Outside/tc2/Spread/Trading/SpreadMDTag.cs new file mode 100644 index 000000000..fd6afe6d1 --- /dev/null +++ b/src/client/spark/NMSheets/Outside/tc2/Spread/Trading/SpreadMDTag.cs @@ -0,0 +1,21 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace BCG +{ + public class SpreadMDTag : SpreadTag + { + public SpreadMDTag(object name) + : base(name) + { } + } + + public class SpreadWorkingOrderTag : SpreadTag + { + public SpreadWorkingOrderTag(object name) + : base(name) + { } + } +} diff --git a/src/client/spark/NMSheets/Outside/tc2/TC2Settings.cs b/src/client/spark/NMSheets/Outside/tc2/TC2Settings.cs new file mode 100644 index 000000000..612d7947f --- /dev/null +++ b/src/client/spark/NMSheets/Outside/tc2/TC2Settings.cs @@ -0,0 +1,115 @@ +using System; +using System.Collections.Generic; + +using BCG.Utilities; + +namespace BCG { + + public class TC2Settings// : ConfigurationRequest + { + + #region Default values will likely work + + /// + /// this is the crazy thing that westrade wants, + /// where the front month offset is added to the + /// spread driver display + /// + private Dictionary _add_offset_to_spread_driver = new Dictionary(); + public bool addOffsetToSpreadDriver(string option_symbol) { + bool rv = false; + _add_offset_to_spread_driver.TryGetValue(option_symbol, out rv); + return rv; + } + + protected bool _enable_fill_alerter = true; + public bool enableFillAlerter { + get { return _enable_fill_alerter; } + set { _enable_fill_alerter = value; } + } + + protected string _scroll_mode = SheetsScrollMode.Mixed.ToString(); + public string ScrollMode { + get { return _scroll_mode; } + set { _scroll_mode = value; } + } + + public SheetsScrollMode get_scroll_mode() { + try { + return (SheetsScrollMode)Enum.Parse(typeof(SheetsScrollMode), ScrollMode.Trim(), true); + } catch { + return SheetsScrollMode.Classic; + } + } + + private bool _use_direct_orders_stream = false; + public bool useDirectOrderStream { + get { return _use_direct_orders_stream; } + set { _use_direct_orders_stream = value; } + } + + private bool _allow_spread_md = true; + public bool allowSpreadMD { + get { return _allow_spread_md; } + set { _allow_spread_md = value; } + } + + private bool _O2_displayLocalOrders = true; + public bool O2_displayLocalOrders { + get { return _O2_displayLocalOrders; } + set { _O2_displayLocalOrders = value; } + } + + private string myPaintMethod = "gdi32"; + public string paintMethod { + get { return myPaintMethod; } + set { myPaintMethod = value; } + } + + private double myHorizontalBitmapGrowthCushion = 1.10; + public double horizontalBitmapGrowthCushion { + get { return myHorizontalBitmapGrowthCushion; } + set { myHorizontalBitmapGrowthCushion = value; } + } + + private double myVerticalBitmapGrowthCushion = 1.10; + public double verticalBitmapGrowthCushion { + get { return myVerticalBitmapGrowthCushion; } + set { myVerticalBitmapGrowthCushion = value; } + } + + private double myDeltaRoundingThreshold = 10; + public double deltaRoundingThreshold { + get { return myDeltaRoundingThreshold; } + set { myDeltaRoundingThreshold = value; } + } + + #endregion + + #region Hard to get good defaults + + protected string _theo_shift_col_name = String.Empty; + public string TheoShiftColumnName { + get { return _theo_shift_col_name; } + set { _theo_shift_col_name = value; } + } + + #endregion + + // public override bool isValid() + // { + // return true; + // } + + private static TC2Settings myInstance; + public static TC2Settings instance { + get { + if (myInstance == null) { + myInstance = new TC2Settings(); + //ConfigurationRequester.request(typeof(TC2Settings)) as TC2Settings; + } + return myInstance; + } + } + } +} \ No newline at end of file diff --git a/src/client/spark/NMSheets/Outside/tc2/TaskingConsolidatedData.cs b/src/client/spark/NMSheets/Outside/tc2/TaskingConsolidatedData.cs new file mode 100644 index 000000000..01f1d677b --- /dev/null +++ b/src/client/spark/NMSheets/Outside/tc2/TaskingConsolidatedData.cs @@ -0,0 +1,61 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using mbts.tasks; +using mbts.engine; +using bts.api; +using System.Reactive.Concurrency; + +namespace BCG { + public class TaskingConsolidatedData { + + + public TaskingConsolidatedData(IEnumerable input_tasks, + object input_securities, + object eye_output, + object quoter_output) { + } + public readonly static TaskingConsolidatedData empty = new TaskingConsolidatedData(Enumerable.Empty(), + null, null, null); + // public TaskingConsolidatedData with(IEnumerable input_tasks = null, + // IEnumerable input_securities = null, + // IEnumerable eye_output = null, + // IEnumerable quoter_output = null) { + // return new TaskingConsolidatedData(input_tasks ?? this._input_tasks, input_securities ?? this._input_securities, + // eye_output ?? _eye_output, quoter_output ?? _quoter_output); + // } + + public IEnumerable get_tasks(TaskType task_type) { return new TaskLiveData[] { }; } + + public TaskLiveData get_task_by_name(TaskType task_type, string name) { + IEnumerable live_tasks = get_tasks(task_type); + return live_tasks.FirstOrDefault(lt => lt.task.common.name == name); + } + + public IEnumerable get_security_owning_tasks(IEnumerable secside_keys, TaskType t_type) { + HashSet rv = new HashSet(); + return rv; + } + + public HashSet get_set_securities(TaskType task_type, bool is_on_only = false) { + return new HashSet(); + } + + public TaskSecurityEyeData get_eye_data(uint key, Side side) { return get_eye_data(new SecuritySideKey(key, side)); } + public TaskSecurityEyeData get_eye_data(SecuritySideKey key) { + return new TaskSecurityEyeData(); + } + + + public TaskSecurityQuoterData get_quoter_data(uint key, Side side) { return get_quoter_data(new SecuritySideKey(key, side)); } + public TaskSecurityQuoterData get_quoter_data(SecuritySideKey key) { + return new TaskSecurityQuoterData(); + } + + public TaskLiveData get_security_task(SecuritySideKey key, TaskType task_type) { + return null; + } + } +} diff --git a/src/client/spark/NMSheets/Settings/ButtonListControl.xaml b/src/client/spark/NMSheets/Settings/ButtonListControl.xaml new file mode 100644 index 000000000..f57c343bf --- /dev/null +++ b/src/client/spark/NMSheets/Settings/ButtonListControl.xaml @@ -0,0 +1,32 @@ + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/client/spark/NMSheets/Settings/ButtonListControl.xaml.cs b/src/client/spark/NMSheets/Settings/ButtonListControl.xaml.cs new file mode 100644 index 000000000..98e0d628f --- /dev/null +++ b/src/client/spark/NMSheets/Settings/ButtonListControl.xaml.cs @@ -0,0 +1,81 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Data; +using System.Windows.Documents; +using System.Windows.Input; +using System.Windows.Media; +using System.Windows.Media.Imaging; +using System.Windows.Navigation; +using System.Windows.Shapes; + +namespace BCG +{ + /// + /// Interaction logic for ButtonListControl.xaml + /// + public partial class ButtonListControl : ContentControl + { + public ButtonListControl(IEnumerable items, System.Windows.Controls.Orientation orientation, Action on_click, Thickness margin, Func formatter = null) + { + DataContext = new ButtonListControlVM(items, orientation, on_click, margin, formatter); + InitializeComponent(); + } + + public void set_items(IEnumerable items) + { + ((ButtonListControlVM)DataContext).set_items(items); + } + } + + class ButtonListControlVM : mbts.ui.shell.ViewModelBase + { + private readonly Func _formatter; + public ButtonListControlVM(IEnumerable items, Orientation orientation, Action on_click, Thickness margin, Func formatter) + { + this.orientation = orientation; + this.on_click = on_click; + button_margin = margin; + _formatter = formatter; + set_items(items); + } + + public Thickness button_margin { get; private set; } + public Orientation orientation { get; private set; } + public List items { get; private set; } + + private Action on_click; + + public void set_items(IEnumerable items) + { + if (items != null) + { + List n_items = new List(); + foreach (object i in items) + n_items.Add(new MyButton(i, on_click, button_margin, _formatter)); + this.items = n_items; + RaisePropertyChanged("items"); + } + } + + public class MyButton + { + private readonly string _text; + public MyButton(object val, Action click_action, Thickness margin, Func formatter) + { + _text = formatter != null ? formatter(val) : val.ToString(); + //value = val; + this.margin = margin; + on_click = new mbts.ui.DelegateCommand((o) => { if (click_action != null) click_action(val); }); + } + + public object value { get { return _text; } private set { } } + public ICommand on_click { get; private set; } + public Thickness margin { get; private set; } + } + } +} diff --git a/src/client/spark/NMSheets/Settings/NMSheetColumnConfiguration.cs b/src/client/spark/NMSheets/Settings/NMSheetColumnConfiguration.cs new file mode 100644 index 000000000..07efade40 --- /dev/null +++ b/src/client/spark/NMSheets/Settings/NMSheetColumnConfiguration.cs @@ -0,0 +1,72 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.ComponentModel; + +namespace BCG +{ + [Serializable] + public class NMSheetColumnConfiguration + { + public NMSheetColumnName column_name; + + private string _column_name_text = String.Empty; + [DisplayName("Column Name")] + [Browsable (false)] + public string column_name_text + { + get { return _column_name_text; } + } + + [Category("Colors and Fonts")] + [Description("Alternating Expirations can have different background colors, this is controlled by Alternating Background Color 1 and Alternating Background Color 2")] + [DisplayName("Alternating Background Color 1")] + public System.Drawing.Color back_color_1 { get; set; } + + [Category("Colors and Fonts")] + [Description("Alternating Expirations can have different background colors, this is controlled by Alternating Background Color 1 and Alternating Background Color 2")] + [DisplayName("Alternating Background Color 2")] + public System.Drawing.Color back_color_2 { get; set; } + + [Category("Colors and Fonts")] + [Description("Alternating Expirations can have different text colors, this is controlled by Alternating Text Color 1 and Alternating Text Color 2")] + [DisplayName("Alternating Text Color 1")] + public System.Drawing.Color font_color_1 { get; set; } + + [Category("Colors and Fonts")] + [Description("Alternating Expirations can have different text colors, this is controlled by Alternating Text Color 1 and Alternating Text Color 2")] + [DisplayName("Alternating Text Color 2")] + public System.Drawing.Color font_color_2 { get; set; } + + [Category("Colors and Fonts")] + [DisplayName("Font")] + public System.Drawing.Font font { get; set; } + + [DisplayName("Visibility")] + public bool is_visibile { get; set; } + + [DisplayName("Formatting")] + public BCG.Utilities.General.TickConverter2.TickType display_format { get; set; } + + private Nullable _minimum_width = 12; + [DisplayName("Minimum Width")] + public Nullable minimum_width + { + get { return _minimum_width.HasValue ? _minimum_width.Value : 12; } + set { _minimum_width = value.HasValue ? value.Value : 12; } + } + + public NMSheetColumnConfiguration() + { + back_color_1 = System.Drawing.Color.LightBlue; + back_color_2 = back_color_1; + font_color_1 = System.Drawing.Color.Black; + font_color_2 = font_color_1; + font = new System.Drawing.Font("Tahoma", 7); + display_format = Utilities.General.TickConverter2.TickType.tickDecimal2; + is_visibile = true; + } + } +} diff --git a/src/client/spark/NMSheets/Settings/NMSheetColumnDisplayHelper.cs b/src/client/spark/NMSheets/Settings/NMSheetColumnDisplayHelper.cs new file mode 100644 index 000000000..ebea40e70 --- /dev/null +++ b/src/client/spark/NMSheets/Settings/NMSheetColumnDisplayHelper.cs @@ -0,0 +1,53 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace BCG +{ + static class NMSheetColumnDisplayHelper + { + private static Dictionary _column_display_dict; + + static NMSheetColumnDisplayHelper() + { + _column_display_dict = new Dictionary(); + foreach (NMSheetColumnName nmscn in typeof(NMSheetColumnName).GetEnumValues()) + _column_display_dict.Add(nmscn, _convert_nms_column_name_enum(nmscn)); + } + + private static string _convert_nms_column_name_enum(NMSheetColumnName nmscn) + { + string spaces = nmscn.ToString().Replace('_', ' '); + string[] split = nmscn.ToString().Split('_'); + string rv = string.Empty; + for(int i = 0; i < split.Length; i++) + { + Char first_letter = Char.ToUpper(split[i][0]); + string upper_case_word = first_letter.ToString(); + for (int j = 1; j < split[i].Length; j++) + upper_case_word += split[i][j]; + rv += upper_case_word + " "; + } + rv = rv.Substring(0, rv.Length - 1); + /// The code below is to catch for the oddballs + /// where the name of the enum is either too + /// code-like or the concept has slightly changed + rv = rv.Replace("Quoteset", "Edge Surface"); + rv = rv.Replace("Ee", "EE"); + return rv; + } + + public static string get_column_display_string(NMSheetColumnName column_name) + { + return _column_display_dict[column_name]; + } + + public static string get_columntype_display_string(NMSheetColumnType column_type) + { + return column_type == NMSheetColumnType.Quoteset ? "Edge Surface" : column_type.ToString(); + + } + } +} diff --git a/src/client/spark/NMSheets/Settings/NMSheetColumnName.cs b/src/client/spark/NMSheets/Settings/NMSheetColumnName.cs new file mode 100644 index 000000000..7f93eb81f --- /dev/null +++ b/src/client/spark/NMSheets/Settings/NMSheetColumnName.cs @@ -0,0 +1,131 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace BCG +{ + public enum NMSheetColumnName + { + /// Because of the NMSheetColumnConfiguration containing this + /// enum in it, all efforts to organize this in 113 (2/9/15) failed (backwards compatibility) + /// So adding a string to NMSheetColumnConfiguration to identify the column + /// will break the dependence on the enum order + /// theos/greeks + call_theo = 0, + put_theo, + call_delta, + put_delta, + call_gamma, + put_gamma, + call_vega, + put_vega, + vol, + straddle, + vol_change, + call_shift, + put_shift, + call_shifted_theo, + put_shifted_theo, + + /// security + strike, + standard_strike, + + /// position + call_position, + put_position, + + /// presave + presave_call_theo, + presave_call_theo_diff, + presave_put_theo, + presave_put_theo_diff, + + /// bbo + call_bid_price, + call_bid_size, + call_ask_price, + call_ask_size, + put_bid_price, + put_bid_size, + put_ask_price, + put_ask_size, + + /// quoteset mid market + call_quoteset_mid_price, + put_quoteset_mid_price, + quoteset_mid_price_straddle, + + /// quoteset edge/size resolved for overrides + call_quoteset_resolved_bid_edge, + put_quoteset_resolved_bid_edge, + call_quoteset_resolved_ask_edge, + put_quoteset_resolved_ask_edge, + + call_quoteset_resolved_bid_size, + put_quoteset_resolved_bid_size, + call_quoteset_resolved_ask_size, + put_quoteset_resolved_ask_size, + + /// quoter edge/size, as communicated by the quoter + call_quoter_set_bid_edge, + put_quoter_set_bid_edge, + call_quoter_set_ask_edge, + put_quoter_set_ask_edge, + + call_quoter_set_bid_size, + call_quoter_set_ask_size, + put_quoter_set_bid_size, + put_quoter_set_ask_size, + + /// quoter price/size, as communicated by the quoter + call_quoter_bid_price, + put_quoter_bid_price, + call_quoter_ask_price, + put_quoter_ask_price, + + call_quoter_bid_size, + put_quoter_bid_size, + call_quoter_ask_size, + put_quoter_ask_size, + + /// quotesets again (the enum number being stored in setting prevents us from inserting them) + call_quoteset_mid_theo_diff, + put_quoteset_mid_theo_diff, + + /*******************************************Eye******************************************/ + /// EE edge/size (input to the EE) + call_ee_set_bid_edge, + put_ee_set_bid_edge, + call_ee_set_ask_edge, + put_ee_set_ask_edge, + + call_ee_set_bid_size, + call_ee_set_ask_size, + put_ee_set_bid_size, + put_ee_set_ask_size, + + /// EE price (output from the EE) + call_ee_bid_price, + put_ee_bid_price, + call_ee_ask_price, + put_ee_ask_price, + + straddle_change, + } + + public enum NMSheetColumnType + { + Security, + Greeks, + BBO, + Position, + Quoter, + Quoteset, + Presave, + EE + } + +} diff --git a/src/client/spark/NMSheets/Settings/NMSheetContextMenu.xaml b/src/client/spark/NMSheets/Settings/NMSheetContextMenu.xaml new file mode 100644 index 000000000..66aac26e5 --- /dev/null +++ b/src/client/spark/NMSheets/Settings/NMSheetContextMenu.xaml @@ -0,0 +1,89 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/client/spark/NMSheets/Settings/NMSheetContextMenu.xaml.cs b/src/client/spark/NMSheets/Settings/NMSheetContextMenu.xaml.cs new file mode 100644 index 000000000..a9d1d2066 --- /dev/null +++ b/src/client/spark/NMSheets/Settings/NMSheetContextMenu.xaml.cs @@ -0,0 +1,83 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Controls.Primitives; +using System.Windows.Data; +using System.Windows.Documents; +using System.Windows.Input; +using System.Windows.Media; +using System.Windows.Media.Imaging; +using System.Windows.Navigation; +using System.Windows.Shapes; +using mbts.ui; +using mbts.ui.shell; + +namespace BCG +{ + /// + /// Interaction logic for NMSheetContextMenu.xaml + /// + public partial class NMSheetContextMenu : ContextMenu + { + public NMSheetContextMenu() { + InitializeComponent(); + DataContext = new NMSheetContextMenuVM(); + } + + public void launch(List expirations, DateTime selected_expiration) + { + ((NMSheetContextMenuVM)DataContext).set_items(Resources, expirations, selected_expiration); + IsOpen = true; + } + } + + class NMSheetContextMenuExpirationVM + { + public NMSheetContextMenuExpirationVM(DateTime expiration, bool is_bold) + { + _expiration = expiration; + font_weight = is_bold ? FontWeights.Bold : FontWeights.Regular; + } + private DateTime _expiration; + public FontWeight font_weight { get; set; } + public string exp_str { get { return _expiration.ToShortDateString(); } } + } + + class NMSheetContextMenuVM : ViewModelBase + { + public void set_items(ResourceDictionary resources, List expirations, DateTime selected_exp) { + List items = new List(); + items.Add(resources["Quoter"]); + items.Add(new Separator()); + items.Add(resources["ATM"]); + items.Add(resources["Card"]); + items.Add(new Separator()); + foreach (DateTime exp in expirations) { + MenuItem mi = new MenuItem() { Header = exp.ToShortDateString() }; + if (exp == selected_exp) + mi.FontWeight = FontWeights.Bold; + items.Add(mi); + } + items.Add(resources["Spread Summary"]); + items.Add(resources["Minimize All Open Spreads"]); + items.Add(new Separator()); + items.Add(resources["Sheets Settings"]); + menu_items = items; + } + private List _menu_items; + public List menu_items { get { return _menu_items; } set { _menu_items = value; RaisePropertyChanged("menu_items"); } } + + public bool show_delta { get; set; } + public bool show_gamma { get; set; } + + private List _expirations; + public List expirations { get { return _expirations; } set { _expirations = value; RaisePropertyChanged("expirations"); } } + + public object zoom_in_icon { get { return Icons.Zoom_In; } } + public object zoom_out_icon { get { return Icons.Zoom_Out; } } + } +} diff --git a/src/client/spark/NMSheets/Settings/NMSheetSettingATM.cs b/src/client/spark/NMSheets/Settings/NMSheetSettingATM.cs new file mode 100644 index 000000000..7c2e4a684 --- /dev/null +++ b/src/client/spark/NMSheets/Settings/NMSheetSettingATM.cs @@ -0,0 +1,25 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using mbts.ui; + +namespace BCG +{ + [Serializable] + public class NMSheetSettingATM + { + [System.ComponentModel.DisplayName("ATM Strike Row Back Color")] + public System.Drawing.Color atm_strike_row_row_back_color { get; set; } + + [System.ComponentModel.DisplayName("Select Nearest Strike Only")] + public bool select_atm_nearest_strike_only { get; set; } + + public NMSheetSettingATM() + { + atm_strike_row_row_back_color = BTSColors.MarketData.atm_background; + select_atm_nearest_strike_only = true; + } + } +} diff --git a/src/client/spark/NMSheets/Settings/NMSheetSettingAlert.cs b/src/client/spark/NMSheets/Settings/NMSheetSettingAlert.cs new file mode 100644 index 000000000..997b50eaf --- /dev/null +++ b/src/client/spark/NMSheets/Settings/NMSheetSettingAlert.cs @@ -0,0 +1,196 @@ +using System; +using System.Collections.Generic; +using System.Drawing; +using System.Drawing.Design; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.ComponentModel; +using mbts.ui; + +namespace BCG +{ + public enum CrossAlertPaintMode + { + Theo, + Price, + None, + QuotesetMid + } + + [Serializable] + public class NMSheetSettingAlert + { + #region Cross Alerts + + private const int _n_max_alert_ticks = 3; + [Category("Cross Alerts")] + [Description("Cross Alerts can be painted either on the Theo, BBO Price, Edge Surface Mid or turned off.")] + [DisplayName("Cross Alert Display Value")] + public CrossAlertPaintMode alert_display_value { get; set; } + + [Category("Cross Alerts")] + [Description("The highlight color when the Theo cross the Market Ask Price")] + [DisplayName("Cross Buy Color")] + public Color buy_alert_color {get;set;} + + [Category("Cross Alerts")] + [Description("The highlight color when the Theo cross the Market Bid Price")] + [DisplayName("Cross Sell Color")] + public Color sell_alert_color {get;set;} + + private Nullable _n_proximity_alert_max_ticks = 0; + [Category("Cross Alerts")] + [Description("The number of driver ticks that controls the Proximity Alert Coloring")] + [DisplayName("Prxomity Alert Number of Ticks")] + public Nullable n_proximity_alert_max_ticks + { + get { return _n_proximity_alert_max_ticks.HasValue ? Math.Min (_n_proximity_alert_max_ticks.Value, _n_max_alert_ticks) : 0; } + set { _n_proximity_alert_max_ticks = value.HasValue ? Math.Min(value.Value, _n_max_alert_ticks) : 0; } + } + + private Nullable _proximity_buy_alert_color = ColorRetriever.convert_color(BTSColors.Greeks.proximity_buy); + [Category("Cross Alerts")] + [Description("The highlight color when the Theo comes Within N Ticks of crossing the Market Ask Price")] + [DisplayName("Proximity Buy Color")] + [Editor(typeof(ColorEditor), typeof(UITypeEditor))] + public Nullable proximity_buy_alert_color + { + get { return _proximity_buy_alert_color.HasValue ? _proximity_buy_alert_color.Value : ColorRetriever.convert_color(BTSColors.Greeks.proximity_buy); } + set { _proximity_buy_alert_color = value.HasValue ? value.Value : ColorRetriever.convert_color(BTSColors.Greeks.proximity_buy); } + } + + private Nullable _proximity_sell_alert_color = ColorRetriever.convert_color(BTSColors.Greeks.proximity_sell); + [Category("Cross Alerts")] + [Description("The highlight color when the Theo comes Within N Ticks of crossing the Market Bid Price")] + [DisplayName("Proximity Sell Color")] + [Editor(typeof(ColorEditor), typeof(UITypeEditor))] + public Nullable proximity_sell_alert_color + { + get { return _proximity_sell_alert_color.HasValue ? _proximity_sell_alert_color.Value : ColorRetriever.convert_color(BTSColors.Greeks.proximity_sell); } + set { _proximity_sell_alert_color = value.HasValue ? value.Value : ColorRetriever.convert_color(BTSColors.Greeks.proximity_sell); } + } + + private Nullable _use_quoteset_mid_for_cross_alerts = false; + [Category("Cross Alerts")] + [Description("This enables the Mid Point of the Edge Surface Bid/Ask Price to be used for Cross Alerts")] + [DisplayName("Use Edge Surface Mid For Cross Alerts")] + public Nullable use_quoteset_mid_for_cross_alerts + { + get { return _use_quoteset_mid_for_cross_alerts.HasValue ? _use_quoteset_mid_for_cross_alerts.Value : false; } + set { _use_quoteset_mid_for_cross_alerts = value.HasValue ? value.Value : false; } + } + + [Browsable(false)] + [Category("Cross Alerts")] + [DisplayName("Cross Threshold")] + [Description("This is currently not used.")] + public double cross_over { get; set; } + + #endregion + + private Nullable _trade_alert_color = BTSColors.MarketData.trade_alert; + [Browsable(false)] + [Category("Trade Alerts")] + [Description("The highlight color when a trade goes off.")] + [DisplayName("Trade Alert Color")] + [Editor(typeof(ColorEditor), typeof(UITypeEditor))] + public Nullable trade_alert_color + { + get { return (_trade_alert_color != null && _trade_alert_color.HasValue) ? _trade_alert_color : (Color) BTSColors.MarketData.trade_alert; } + set { _trade_alert_color = (value != null && value.HasValue) ? value.Value : (Color)BTSColors.MarketData.trade_alert; } + } + + private Nullable _trade_price_over_theo_alert_color = BTSColors.MarketData.trade_price_over_theo; + [Category("Trade Alerts")] + [Description("The highlight color when a trade goes off with a price >= theo price.")] + [DisplayName("Trade Price Over Theo Alert Color")] + [Editor(typeof(ColorEditor), typeof(UITypeEditor))] + public Nullable trade_price_over_theo_alert_color + { + get { return (_trade_price_over_theo_alert_color != null && _trade_price_over_theo_alert_color.HasValue) ? _trade_price_over_theo_alert_color :(Color)BTSColors.MarketData.trade_price_over_theo; } + set { _trade_price_over_theo_alert_color = (value != null && value.HasValue) ? value.Value :(Color)BTSColors.MarketData.trade_price_over_theo; } + } + + private Nullable _trade_price_under_theo_alert_color = BTSColors.MarketData.trade_price_under_theo; + [Category("Trade Alerts")] + [Description("The highlight color when a trade goes off with a price < theo price.")] + [DisplayName("Trade Price Under Theo Alert Color")] + [Editor(typeof(ColorEditor), typeof(UITypeEditor))] + public Nullable trade_price_under_theo_alert_color + { + get { return (_trade_price_under_theo_alert_color != null && _trade_price_under_theo_alert_color.HasValue) ? _trade_price_under_theo_alert_color : (Color)BTSColors.MarketData.trade_price_under_theo; } + set { _trade_price_under_theo_alert_color = (value != null && value.HasValue) ? value.Value : (Color)BTSColors.MarketData.trade_price_under_theo; } + } + + private Nullable _trade_alert_size = 100; + [Category("Trade Alerts")] + [Description("The minimum size for the alert to go off.")] + [DisplayName("Trade Alert Minimum Size")] + public Nullable trade_alert_size + { + get { return (_trade_alert_size != null && _trade_alert_size.HasValue) ? _trade_alert_size.Value : 100; } + set { _trade_alert_size = (value != null && value.HasValue) ? value.Value : 100; } + } + + private Nullable _trade_alert_time_seconds = 5; + [Category("Trade Alerts")] + [Description("The time in seconds for alert to display.")] + [DisplayName("Trade Alert Time Seconds")] + public Nullable trade_alert_time_seconds + { + get { return (_trade_alert_time_seconds != null && _trade_alert_time_seconds.HasValue) ? _trade_alert_time_seconds.Value : 5; } + set { _trade_alert_time_seconds = (value != null && value.HasValue) ? value.Value : 5; } + } + + private Nullable _minimum_edge = 0.0; + [Browsable(false)] + [Category("Trade Alerts")] + [Description("This is currently not used.")] + [DisplayName("Trade Minimum Edge")] + public Nullable minimum_edge + { + get { return (_minimum_edge != null && _minimum_edge.HasValue) ? _minimum_edge.Value : 0.0; } + set { _minimum_edge = (value != null && value.HasValue) ? value.Value : 0.0; } + } + + private Nullable _vol_change_flash_seconds = 5.0; + [Category("Vol Change")] + [Description("Seconds that the Icon in the top left of the Window will flash when volatility changes.")] + [DisplayName("Flash Time (Secs)")] + public Nullable vol_change_flash_seconds { + get { return (_vol_change_flash_seconds != null && _vol_change_flash_seconds.HasValue) ? _vol_change_flash_seconds.Value : 5.0; } + set { _vol_change_flash_seconds = (value != null && value.HasValue) ? value.Value : 5.0; } + } + + private Nullable _ee_on_color = BTSColors.Tasking.eye_on; + [Category("Electronic Eye")] + [Description("The highlight color when a contract is part of an ON Electronic Eye Task.")] + [DisplayName("Electronic Eye On Color")] + [Editor(typeof(ColorEditor), typeof(UITypeEditor))] + public Nullable ee_on_color + { + get { return (_ee_on_color != null && _ee_on_color.HasValue) ? _ee_on_color : (Color)BTSColors.Tasking.eye_on; } + set { _ee_on_color = (value != null && value.HasValue) ? value.Value : (Color)BTSColors.Tasking.eye_on; } + } + + private Nullable _ee_fire_color = BTSColors.Tasking.eye_cross; + [Category("Electronic Eye")] + [Description("The highlight color when the Electronic Eye Price crosses the Market.")] + [DisplayName("Electronic Eye Cross Color")] + [Editor(typeof(ColorEditor), typeof(UITypeEditor))] + public Nullable ee_fire_color + { + get { return (_ee_fire_color != null && _ee_fire_color.HasValue) ? _ee_fire_color : (Color)BTSColors.Tasking.eye_cross; } + set { _ee_fire_color = (value != null && value.HasValue) ? value.Value : (Color)BTSColors.Tasking.eye_cross; } + } + + public NMSheetSettingAlert() + { + alert_display_value = CrossAlertPaintMode.Price; + buy_alert_color = BTSColors.Greeks.cross_buy; + sell_alert_color = BTSColors.Greeks.cross_sell; + cross_over = 0.0; + } + } +} diff --git a/src/client/spark/NMSheets/Settings/NMSheetSettingCheckboxListControl.Designer.cs b/src/client/spark/NMSheets/Settings/NMSheetSettingCheckboxListControl.Designer.cs new file mode 100644 index 000000000..911d5fa53 --- /dev/null +++ b/src/client/spark/NMSheets/Settings/NMSheetSettingCheckboxListControl.Designer.cs @@ -0,0 +1,59 @@ +namespace BCG +{ + partial class NMSheetSettingCheckboxListControl + { + /// + /// 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._checklist_box_items = new System.Windows.Forms.CheckedListBox(); + this.SuspendLayout(); + // + // _checklist_box_items + // + this._checklist_box_items.BorderStyle = System.Windows.Forms.BorderStyle.None; + this._checklist_box_items.Dock = System.Windows.Forms.DockStyle.Fill; + this._checklist_box_items.FormattingEnabled = true; + this._checklist_box_items.Location = new System.Drawing.Point(0, 0); + this._checklist_box_items.Name = "_checklist_box_items"; + this._checklist_box_items.Size = new System.Drawing.Size(202, 202); + this._checklist_box_items.TabIndex = 1; + // + // NMSheetSettingCheckboxListControl + // + this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.Controls.Add(this._checklist_box_items); + this.Name = "NMSheetSettingCheckboxListControl"; + this.Size = new System.Drawing.Size(202, 202); + this.ResumeLayout(false); + + } + + #endregion + + private System.Windows.Forms.CheckedListBox _checklist_box_items; + } +} diff --git a/src/client/spark/NMSheets/Settings/NMSheetSettingCheckboxListControl.cs b/src/client/spark/NMSheets/Settings/NMSheetSettingCheckboxListControl.cs new file mode 100644 index 000000000..1507ee49b --- /dev/null +++ b/src/client/spark/NMSheets/Settings/NMSheetSettingCheckboxListControl.cs @@ -0,0 +1,46 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Drawing; +using System.Data; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; +using mbts.ui.dpi; + +namespace BCG +{ + public partial class NMSheetSettingCheckboxListControl : UserControl + { + private NMSheetSettingCheckboxListControl() + { + InitializeComponent(); + _checklist_box_items.Dock = DockStyle.Fill; + _checklist_box_items.CheckOnClick = true; + _checklist_box_items.MultiColumn = true; + _checklist_box_items.ColumnWidth = (128).MultipliedByDPIRatio(); + //_checklist_box_items.Sorted = true; + } + + public NMSheetSettingCheckboxListControl(System.Collections.IEnumerable complete_list, System.Collections.IEnumerable selected_items) + : this () + { + HashSet selected_items_hash = new HashSet(); + foreach (object o in selected_items) + selected_items_hash.Add(o); + foreach (object o in complete_list) + _checklist_box_items.Items.Add(o, !selected_items_hash.Contains(o)); + } + + public List get_unselected_items() + { + List rv = new List(); + int i = 0; + foreach (object o in _checklist_box_items.Items) + if (!_checklist_box_items.GetItemChecked (i++)) + rv.Add (o); + return rv; + } + } +} diff --git a/src/client/spark/NMSheets/Settings/NMSheetSettingCheckboxListControl.resx b/src/client/spark/NMSheets/Settings/NMSheetSettingCheckboxListControl.resx new file mode 100644 index 000000000..1af7de150 --- /dev/null +++ b/src/client/spark/NMSheets/Settings/NMSheetSettingCheckboxListControl.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/NMSheets/Settings/NMSheetSettingColumnOrderControl.Designer.cs b/src/client/spark/NMSheets/Settings/NMSheetSettingColumnOrderControl.Designer.cs new file mode 100644 index 000000000..a5cf1c05b --- /dev/null +++ b/src/client/spark/NMSheets/Settings/NMSheetSettingColumnOrderControl.Designer.cs @@ -0,0 +1,37 @@ +namespace BCG +{ + partial class NMSheetSettingColumnOrderControl + { + /// + /// 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() + { + components = new System.ComponentModel.Container(); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + } + + #endregion + } +} diff --git a/src/client/spark/NMSheets/Settings/NMSheetSettingColumnOrderControl.cs b/src/client/spark/NMSheets/Settings/NMSheetSettingColumnOrderControl.cs new file mode 100644 index 000000000..b91d4e469 --- /dev/null +++ b/src/client/spark/NMSheets/Settings/NMSheetSettingColumnOrderControl.cs @@ -0,0 +1,108 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Drawing; +using System.Data; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace BCG +{ + public partial class NMSheetSettingColumnOrderControl : UserControl + { + private CheckedListBox _listbox_columns; + private NMSheetSettings _nmsheet_settings; + private readonly Dictionary _column_name_to_setting_map = new Dictionary(); + private readonly bool _main_col_ordering; + + public NMSheetSettingColumnOrderControl(NMSheetSettings nmsheet_settings, bool main_col_ordering) + { + InitializeComponent(); + _nmsheet_settings = nmsheet_settings; + _main_col_ordering = main_col_ordering; + _init_listbox(); + for (int i = 0; i < _col_org.column_configuration_list.Count; i++) + { + NMSheetColumnConfiguration col_conf = _col_org.column_configuration_list[i]; + string display_name = NMSheetColumnDisplayHelper.get_column_display_string(col_conf.column_name); + _column_name_to_setting_map.Add(display_name, col_conf); + _listbox_columns.Items.Add(display_name); + if (col_conf.is_visibile) + _listbox_columns.SetItemChecked(i, true); + } + } + + private NMSheetSettingColumnOrganization _col_org { get { return _main_col_ordering ? _nmsheet_settings.setting_column_organization : _nmsheet_settings.setting_export_data_column_organization; } } + + private void _init_listbox() + { + _listbox_columns = new CheckedListBox() { Dock = DockStyle.Fill }; + _listbox_columns.CheckOnClick = true; + _listbox_columns.ItemCheck += _listbox_columns_ItemCheck; + _listbox_columns.AllowDrop = true; + _listbox_columns.DragDrop += _listbox_columns_DragDrop; + _listbox_columns.DragOver += _listbox_columns_DragOver; + _listbox_columns.MouseDown += _listbox_columns_MouseDown; + Controls.Add(_listbox_columns); + } + + private void _listbox_columns_ItemCheck(object sender, ItemCheckEventArgs e) + { + string value = (string)_listbox_columns.Items[e.Index]; + _column_name_to_setting_map[value].is_visibile = e.NewValue == CheckState.Checked; + } + + private void _listbox_columns_DragDrop(object sender, DragEventArgs e) + { + if (e.Data.GetDataPresent(DataFormats.StringFormat)) + { + string val = (string)e.Data.GetData(DataFormats.StringFormat); + int new_index = _listbox_columns.IndexFromPoint(_listbox_columns.PointToClient(new Point(e.X, e.Y))); + int old_index = _listbox_columns.Items.IndexOf(val); + if (old_index != new_index && new_index >= 0) + { + List columns = new List(); + foreach (object col in _listbox_columns.Items) + columns.Add((string)col); + _listbox_columns.SuspendLayout(); + _listbox_columns.Items.Remove(val); + if (new_index >= _listbox_columns.Items.Count) + _listbox_columns.Items.Add(val); + else if (new_index >= 0) + _listbox_columns.Items.Insert(new_index, val); + _listbox_columns.SetItemChecked(new_index, _pre_drop_check_state); + _listbox_columns.Refresh(); + _copy_column_order_to_settings(); + } + } + } + + private void _listbox_columns_DragOver(object sender, DragEventArgs e) { e.Effect = DragDropEffects.All; } + + private bool _pre_drop_check_state; + private void _listbox_columns_MouseDown(object sender, MouseEventArgs e) + { + int index = _listbox_columns.IndexFromPoint(e.Location); + if (index >= 0 && index < _listbox_columns.Items.Count && e.Button == System.Windows.Forms.MouseButtons.Left && e.Location.X >= 10) + { + _pre_drop_check_state = _listbox_columns.CheckedIndices.Contains(index); + string val = (string)_listbox_columns.Items[index]; + _listbox_columns.DoDragDrop(val, DragDropEffects.All); + _listbox_columns.SelectedItem = val; + } + } + + private void _copy_column_order_to_settings() + { + List col_confs = new List(); + foreach (object item in _listbox_columns.Items) + col_confs.Add(_column_name_to_setting_map[(string)item]); + if (_main_col_ordering) + _nmsheet_settings.setting_column_organization = new NMSheetSettingColumnOrganization() { column_configuration_list = col_confs }; + else + _nmsheet_settings.setting_export_data_column_organization = new NMSheetSettingColumnOrganization() { column_configuration_list = col_confs }; + } + } +} diff --git a/src/client/spark/NMSheets/Settings/NMSheetSettingColumnOrganization.cs b/src/client/spark/NMSheets/Settings/NMSheetSettingColumnOrganization.cs new file mode 100644 index 000000000..70ffcecdd --- /dev/null +++ b/src/client/spark/NMSheets/Settings/NMSheetSettingColumnOrganization.cs @@ -0,0 +1,323 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Drawing; +using mbts.ui; + +namespace BCG { + [Serializable] + public class NMSheetSettingColumnOrganization { + public class NMSheetColumnInfo { + public readonly NMSheetColumnType col_type; + public readonly bool is_call, is_put, is_bid, is_ask; + public NMSheetColumnInfo(NMSheetColumnType the_col_type, + bool the_is_call, bool the_is_put, + bool the_is_bid, bool the_is_ask) { + col_type = the_col_type; + is_call = the_is_call; + is_put = the_is_put; + is_bid = the_is_bid; + is_ask = the_is_ask; + } + } + + private static IDictionary> _col_type_map = null; + private static NMSheetColumnInfo[] _col_basic_info = null; + + private static void _init() { + if (_col_type_map == null) { + lock (typeof(NMSheetSettingColumnOrganization)) { + _col_type_map = new Dictionary>(); + _col_type_map.Add(NMSheetColumnType.Security, new HashSet(new NMSheetColumnName[] { NMSheetColumnName.strike })); + _col_type_map.Add(NMSheetColumnType.BBO, new HashSet(new NMSheetColumnName[] + { + NMSheetColumnName.call_bid_price, + NMSheetColumnName.put_bid_price, + NMSheetColumnName.call_bid_size, + NMSheetColumnName.put_bid_size, + NMSheetColumnName.call_ask_price, + NMSheetColumnName.put_ask_price, + NMSheetColumnName.call_ask_size, + NMSheetColumnName.put_ask_size, + })); + _col_type_map.Add(NMSheetColumnType.Greeks, new HashSet(new NMSheetColumnName[] + { + NMSheetColumnName.call_theo, + NMSheetColumnName.put_theo, + NMSheetColumnName.call_delta, + NMSheetColumnName.put_delta, + NMSheetColumnName.call_gamma, + NMSheetColumnName.put_gamma, + NMSheetColumnName.call_vega, + NMSheetColumnName.put_vega, + NMSheetColumnName.vol, + NMSheetColumnName.straddle, + NMSheetColumnName.standard_strike, + NMSheetColumnName.vol_change, + NMSheetColumnName.straddle_change, + NMSheetColumnName.call_shifted_theo, + NMSheetColumnName.put_shifted_theo, + NMSheetColumnName.call_shift, + NMSheetColumnName.put_shift + })); + _col_type_map.Add(NMSheetColumnType.Position, new HashSet(new NMSheetColumnName[] + { + NMSheetColumnName.call_position, + NMSheetColumnName.put_position, + })); + _col_type_map.Add(NMSheetColumnType.Quoter, new HashSet(new NMSheetColumnName[] + { + /// final ee edge/size + NMSheetColumnName.call_quoter_set_bid_edge, + NMSheetColumnName.put_quoter_set_bid_edge, + NMSheetColumnName.call_quoter_set_ask_edge, + NMSheetColumnName.put_quoter_set_ask_edge, + + NMSheetColumnName.call_quoter_set_bid_size, + NMSheetColumnName.put_quoter_set_bid_size, + NMSheetColumnName.call_quoter_set_ask_size, + NMSheetColumnName.put_quoter_set_ask_size, + + /// quoter price/size + NMSheetColumnName.call_quoter_bid_price, + NMSheetColumnName.put_quoter_bid_price, + NMSheetColumnName.call_quoter_ask_price, + NMSheetColumnName.put_quoter_ask_price, + + NMSheetColumnName.call_quoter_bid_size, + NMSheetColumnName.put_quoter_bid_size, + NMSheetColumnName.call_quoter_ask_size, + NMSheetColumnName.put_quoter_ask_size + })); + _col_type_map.Add(NMSheetColumnType.EE, new HashSet(new NMSheetColumnName[] + { + /// ee final edge/size + NMSheetColumnName.call_ee_set_bid_edge, + NMSheetColumnName.put_ee_set_bid_edge, + NMSheetColumnName.call_ee_set_ask_edge, + NMSheetColumnName.put_ee_set_ask_edge, + + NMSheetColumnName.call_ee_set_bid_size, + NMSheetColumnName.put_ee_set_bid_size, + NMSheetColumnName.call_ee_set_ask_size, + NMSheetColumnName.put_ee_set_ask_size, + + /// ee price/size + NMSheetColumnName.call_ee_bid_price, + NMSheetColumnName.put_ee_bid_price, + NMSheetColumnName.call_ee_ask_price, + NMSheetColumnName.put_ee_ask_price, + })); + _col_type_map.Add(NMSheetColumnType.Quoteset, new HashSet(new NMSheetColumnName[] + { + /// quoteset + NMSheetColumnName.call_quoteset_mid_price, + NMSheetColumnName.put_quoteset_mid_price, + + NMSheetColumnName.call_quoteset_mid_theo_diff, + NMSheetColumnName.put_quoteset_mid_theo_diff, + + NMSheetColumnName.quoteset_mid_price_straddle, + + NMSheetColumnName.call_quoteset_resolved_bid_edge, + NMSheetColumnName.put_quoteset_resolved_bid_edge, + NMSheetColumnName.call_quoteset_resolved_ask_edge, + NMSheetColumnName.put_quoteset_resolved_ask_edge, + + NMSheetColumnName.call_quoteset_resolved_bid_size, + NMSheetColumnName.put_quoteset_resolved_bid_size, + NMSheetColumnName.call_quoteset_resolved_ask_size, + NMSheetColumnName.put_quoteset_resolved_ask_size + })); + _col_type_map.Add(NMSheetColumnType.Presave, new HashSet(new NMSheetColumnName[] + { + NMSheetColumnName.presave_call_theo, + NMSheetColumnName.presave_put_theo, + NMSheetColumnName.presave_call_theo_diff, + NMSheetColumnName.presave_put_theo_diff, + })); + + _col_basic_info = new NMSheetColumnInfo[Enum.GetNames(typeof(NMSheetColumnName)).Length]; + int col_no = 0; + foreach (string col_name in Enum.GetNames(typeof(NMSheetColumnName))) { + NMSheetColumnName col = (NMSheetColumnName)Enum.Parse(typeof(NMSheetColumnName), col_name, true); + if (col_name == NMSheetColumnName.strike.ToString() || col_name == NMSheetColumnName.vol.ToString()) + _col_basic_info[col_no++] = new NMSheetColumnInfo(NMSheetColumnType.Security, true, true, false, false); + else + _col_basic_info[col_no++] = new NMSheetColumnInfo(get_col_type(col), col_name.Contains("call"), col_name.Contains("put"), col_name.Contains("bid"), col_name.Contains("ask")); + } + } + } + } + + public List column_configuration_list = new List(); + + public NMSheetSettingColumnOrganization(string option_symbol) { + _init(); + Utilities.General.TickConverter2.TickType price_tick_type = Utilities.General.TickConverter2.TickType.tickDecimal2; + Utilities.General.TickConverter2.TickType theo_tick_type = Utilities.General.TickConverter2.TickType.tickDecimal2; + Utilities.General.TickConverter2.TickType strike_tick_type = Utilities.General.TickConverter2.TickType.tickDecimal2Strike; + if (!String.IsNullOrEmpty(option_symbol)) { + price_tick_type = Utilities.General.TickConverter2.TickType.tickDecimal3; // TODO TickTypeResolver.getTickType(option_symbol, TickTypeResolver.ValueType.price); + theo_tick_type = Utilities.General.TickConverter2.TickType.tickDecimal3; // TODO TickTypeResolver.getTickType(option_symbol, TickTypeResolver.ValueType.theo); + strike_tick_type = Utilities.General.TickConverter2.TickType.tickDecimal2Strike; // TODO TickTypeResolver.getTickType(option_symbol, TickTypeResolver.ValueType.strike); + } + + /// call + column_configuration_list.Add(new NMSheetColumnConfiguration() { column_name = NMSheetColumnName.call_position, back_color_1 = BTSColors.Position.default_background, back_color_2 = BTSColors.Position.default_background, font_color_1 = BTSColors.Position.default_text, font_color_2 = BTSColors.Position.default_text, display_format = Utilities.General.TickConverter2.TickType.tickDecimal0, is_visibile = false }); + + /// ee bid + column_configuration_list.Add(new NMSheetColumnConfiguration() { column_name = NMSheetColumnName.call_ee_set_bid_edge, back_color_1 = BTSColors.Quoter.set_background, back_color_2 = BTSColors.Quoter.set_background, font_color_1 = BTSColors.Quoter.default_text, font_color_2 = BTSColors.Quoter.default_text, display_format = theo_tick_type, is_visibile = true }); + column_configuration_list.Add(new NMSheetColumnConfiguration() { column_name = NMSheetColumnName.call_ee_set_bid_size, back_color_1 = BTSColors.Quoter.set_background, back_color_2 = BTSColors.Quoter.set_background, font_color_1 = BTSColors.Quoter.default_text, font_color_2 = BTSColors.Quoter.default_text, display_format = Utilities.General.TickConverter2.TickType.tickDecimal0, is_visibile = true }); + column_configuration_list.Add(new NMSheetColumnConfiguration() { column_name = NMSheetColumnName.call_ee_bid_price, back_color_1 = BTSColors.Quoter.default_background, back_color_2 = BTSColors.Quoter.default_background, font_color_1 = BTSColors.Quoter.bid_text, font_color_2 = BTSColors.Quoter.bid_text, display_format = theo_tick_type, is_visibile = true }); + + /// quoter bid + column_configuration_list.Add(new NMSheetColumnConfiguration() { column_name = NMSheetColumnName.call_quoteset_resolved_bid_edge, back_color_1 = BTSColors.Quoteset.default_background, back_color_2 = BTSColors.Quoteset.default_background, font_color_1 = BTSColors.Quoteset.default_text, font_color_2 = BTSColors.Quoteset.default_text, display_format = theo_tick_type, is_visibile = false }); + column_configuration_list.Add(new NMSheetColumnConfiguration() { column_name = NMSheetColumnName.call_quoteset_resolved_bid_size, back_color_1 = BTSColors.Quoteset.default_background, back_color_2 = BTSColors.Quoteset.default_background, font_color_1 = BTSColors.Quoteset.default_text, font_color_2 = BTSColors.Quoteset.default_text, display_format = Utilities.General.TickConverter2.TickType.tickDecimal0, is_visibile = false }); + column_configuration_list.Add(new NMSheetColumnConfiguration() { column_name = NMSheetColumnName.call_quoter_set_bid_edge, back_color_1 = BTSColors.Quoter.set_background, back_color_2 = BTSColors.Quoter.set_background, font_color_1 = BTSColors.Quoter.default_text, font_color_2 = BTSColors.Quoter.default_text, display_format = theo_tick_type, is_visibile = false }); + column_configuration_list.Add(new NMSheetColumnConfiguration() { column_name = NMSheetColumnName.call_quoter_set_bid_size, back_color_1 = BTSColors.Quoter.set_background, back_color_2 = BTSColors.Quoter.set_background, font_color_1 = BTSColors.Quoter.default_text, font_color_2 = BTSColors.Quoter.default_text, display_format = Utilities.General.TickConverter2.TickType.tickDecimal0, is_visibile = false }); + column_configuration_list.Add(new NMSheetColumnConfiguration() { column_name = NMSheetColumnName.call_quoter_bid_price, back_color_1 = BTSColors.Quoter.default_background, back_color_2 = BTSColors.Quoter.default_background, font_color_1 = BTSColors.Quoter.bid_text, font_color_2 = BTSColors.Quoter.bid_text, display_format = theo_tick_type, is_visibile = false }); + column_configuration_list.Add(new NMSheetColumnConfiguration() { column_name = NMSheetColumnName.call_quoter_bid_size, back_color_1 = BTSColors.Quoter.default_background, back_color_2 = BTSColors.Quoter.default_background, font_color_1 = BTSColors.Quoter.bid_text, font_color_2 = BTSColors.Quoter.bid_text, display_format = Utilities.General.TickConverter2.TickType.tickDecimal0, is_visibile = false }); + + /// call bid bbo + column_configuration_list.Add(new NMSheetColumnConfiguration() { column_name = NMSheetColumnName.call_bid_size, back_color_1 = BTSColors.MarketData.default_background, back_color_2 = BTSColors.MarketData.default_background, font_color_1 = BTSColors.MarketData.bid_text, font_color_2 = BTSColors.MarketData.bid_text, display_format = Utilities.General.TickConverter2.TickType.tickDecimal0 }); + column_configuration_list.Add(new NMSheetColumnConfiguration() { column_name = NMSheetColumnName.call_bid_price, back_color_1 = BTSColors.MarketData.default_background, back_color_2 = BTSColors.MarketData.default_background, font_color_1 = BTSColors.MarketData.bid_text, font_color_2 = BTSColors.MarketData.bid_text, display_format = price_tick_type }); + + column_configuration_list.Add(new NMSheetColumnConfiguration() { column_name = NMSheetColumnName.call_quoteset_mid_price, back_color_1 = BTSColors.Quoteset.mid_price_background, back_color_2 = BTSColors.Quoteset.mid_price_background, font_color_1 = BTSColors.Quoteset.default_text, font_color_2 = BTSColors.Quoteset.default_text, display_format = theo_tick_type, font = new Font("Tahoma", 8), is_visibile = false }); + column_configuration_list.Add(new NMSheetColumnConfiguration() { column_name = NMSheetColumnName.call_quoteset_mid_theo_diff, back_color_1 = BTSColors.Quoteset.default_background, back_color_2 = BTSColors.Quoteset.default_background, font_color_1 = BTSColors.Quoteset.default_text, font_color_2 = BTSColors.Quoteset.default_text, display_format = theo_tick_type, font = new Font("Tahoma", 7), is_visibile = false }); + + /// call greeks + column_configuration_list.Add(new NMSheetColumnConfiguration() { column_name = NMSheetColumnName.call_theo, back_color_1 = BTSColors.Greeks.live_theo, back_color_2 = BTSColors.Greeks.live_theo, font_color_1 = BTSColors.Greeks.default_text, font_color_2 = BTSColors.Greeks.default_text, display_format = theo_tick_type, font = new Font("Tahoma", 8) }); + column_configuration_list.Add(new NMSheetColumnConfiguration() { column_name = NMSheetColumnName.presave_call_theo, back_color_1 = BTSColors.Presave.default_background, back_color_2 = BTSColors.Presave.default_background, font_color_1 = BTSColors.Presave.default_text, font_color_2 = BTSColors.Presave.default_text, display_format = theo_tick_type, is_visibile = false }); + column_configuration_list.Add(new NMSheetColumnConfiguration() { column_name = NMSheetColumnName.presave_call_theo_diff, back_color_1 = BTSColors.Presave.default_background, back_color_2 = BTSColors.Presave.default_background, font_color_1 = BTSColors.Presave.default_text, font_color_2 = BTSColors.Presave.default_text, display_format = theo_tick_type, is_visibile = false }); + column_configuration_list.Add(new NMSheetColumnConfiguration() { column_name = NMSheetColumnName.call_delta, back_color_1 = BTSColors.Greeks.delta, back_color_2 = BTSColors.Greeks.delta, font_color_1 = BTSColors.Greeks.default_text, font_color_2 = BTSColors.Greeks.default_text, display_format = Utilities.General.TickConverter2.TickType.tickDecimal0 }); + column_configuration_list.Add(new NMSheetColumnConfiguration() { column_name = NMSheetColumnName.call_gamma, back_color_1 = BTSColors.Greeks.default_background, back_color_2 = BTSColors.Greeks.default_background, font_color_1 = BTSColors.Greeks.default_text, font_color_2 = BTSColors.Greeks.default_text, is_visibile = false }); + column_configuration_list.Add(new NMSheetColumnConfiguration() { column_name = NMSheetColumnName.call_vega, back_color_1 = BTSColors.Greeks.default_background, back_color_2 = BTSColors.Greeks.default_background, font_color_1 = BTSColors.Greeks.default_text, font_color_2 = BTSColors.Greeks.default_text, is_visibile = false }); + + /// call ask bbo + column_configuration_list.Add(new NMSheetColumnConfiguration() { column_name = NMSheetColumnName.call_ask_price, back_color_1 = BTSColors.MarketData.default_background, back_color_2 = BTSColors.MarketData.default_background, font_color_1 = BTSColors.MarketData.ask_text, font_color_2 = BTSColors.MarketData.ask_text, display_format = price_tick_type }); + column_configuration_list.Add(new NMSheetColumnConfiguration() { column_name = NMSheetColumnName.call_ask_size, back_color_1 = BTSColors.MarketData.default_background, back_color_2 = BTSColors.MarketData.default_background, font_color_1 = BTSColors.MarketData.ask_text, font_color_2 = BTSColors.MarketData.ask_text, display_format = Utilities.General.TickConverter2.TickType.tickDecimal0 }); + + /// quoter ask + column_configuration_list.Add(new NMSheetColumnConfiguration() { column_name = NMSheetColumnName.call_quoter_ask_price, back_color_1 = BTSColors.Quoter.default_background, back_color_2 = BTSColors.Quoter.default_background, font_color_1 = BTSColors.Quoter.ask_text, font_color_2 = BTSColors.Quoter.ask_text, display_format = theo_tick_type, is_visibile = false }); + column_configuration_list.Add(new NMSheetColumnConfiguration() { column_name = NMSheetColumnName.call_quoter_ask_size, back_color_1 = BTSColors.Quoter.default_background, back_color_2 = BTSColors.Quoter.default_background, font_color_1 = BTSColors.Quoter.ask_text, font_color_2 = BTSColors.Quoter.ask_text, display_format = Utilities.General.TickConverter2.TickType.tickDecimal0, is_visibile = false }); + column_configuration_list.Add(new NMSheetColumnConfiguration() { column_name = NMSheetColumnName.call_quoteset_resolved_ask_edge, back_color_1 = BTSColors.Quoteset.default_background, back_color_2 = BTSColors.Quoteset.default_background, font_color_1 = BTSColors.Quoteset.default_text, font_color_2 = BTSColors.Quoteset.default_text, display_format = theo_tick_type, is_visibile = false }); + column_configuration_list.Add(new NMSheetColumnConfiguration() { column_name = NMSheetColumnName.call_quoteset_resolved_ask_size, back_color_1 = BTSColors.Quoteset.default_background, back_color_2 = BTSColors.Quoteset.default_background, font_color_1 = BTSColors.Quoteset.default_text, font_color_2 = BTSColors.Quoteset.default_text, display_format = Utilities.General.TickConverter2.TickType.tickDecimal0, is_visibile = false }); + column_configuration_list.Add(new NMSheetColumnConfiguration() { column_name = NMSheetColumnName.call_quoter_set_ask_edge, back_color_1 = BTSColors.Quoter.set_background, back_color_2 = BTSColors.Quoter.set_background, font_color_1 = BTSColors.Quoter.default_text, font_color_2 = BTSColors.Quoter.default_text, display_format = theo_tick_type, is_visibile = false }); + column_configuration_list.Add(new NMSheetColumnConfiguration() { column_name = NMSheetColumnName.call_quoter_set_ask_size, back_color_1 = BTSColors.Quoter.set_background, back_color_2 = BTSColors.Quoter.set_background, font_color_1 = BTSColors.Quoter.default_text, font_color_2 = BTSColors.Quoter.default_text, display_format = Utilities.General.TickConverter2.TickType.tickDecimal0, is_visibile = false }); + + /// ee ask + column_configuration_list.Add(new NMSheetColumnConfiguration() { column_name = NMSheetColumnName.call_ee_ask_price, back_color_1 = BTSColors.Quoter.default_background, back_color_2 = BTSColors.Quoter.default_background, font_color_1 = BTSColors.Quoter.ask_text, font_color_2 = BTSColors.Quoter.ask_text, display_format = theo_tick_type, is_visibile = true }); + column_configuration_list.Add(new NMSheetColumnConfiguration() { column_name = NMSheetColumnName.call_ee_set_ask_edge, back_color_1 = BTSColors.Quoter.set_background, back_color_2 = BTSColors.Quoter.set_background, font_color_1 = BTSColors.Quoter.default_text, font_color_2 = BTSColors.Quoter.default_text, display_format = theo_tick_type, is_visibile = true }); + column_configuration_list.Add(new NMSheetColumnConfiguration() { column_name = NMSheetColumnName.call_ee_set_ask_size, back_color_1 = BTSColors.Quoter.set_background, back_color_2 = BTSColors.Quoter.set_background, font_color_1 = BTSColors.Quoter.default_text, font_color_2 = BTSColors.Quoter.default_text, display_format = Utilities.General.TickConverter2.TickType.tickDecimal0, is_visibile = true }); + + /// common + column_configuration_list.Add(new NMSheetColumnConfiguration() { column_name = NMSheetColumnName.strike, back_color_1 = BTSColors.Security.default_background, back_color_2 = BTSColors.Security.default_background, font_color_1 = BTSColors.Security.default_text, font_color_2 = BTSColors.Security.default_text, font = new Font("Tahoma", 8), display_format = strike_tick_type }); + column_configuration_list.Add(new NMSheetColumnConfiguration() { column_name = NMSheetColumnName.standard_strike, back_color_1 = BTSColors.Greeks.default_background, back_color_2 = BTSColors.Greeks.default_background, font_color_1 = BTSColors.Greeks.default_text, font_color_2 = BTSColors.Greeks.default_text, is_visibile = false }); + column_configuration_list.Add(new NMSheetColumnConfiguration() { column_name = NMSheetColumnName.vol, back_color_1 = BTSColors.Greeks.default_background, back_color_2 = BTSColors.Greeks.default_background, font_color_1 = BTSColors.Greeks.default_text, font_color_2 = BTSColors.Greeks.default_text }); + column_configuration_list.Add(new NMSheetColumnConfiguration() { column_name = NMSheetColumnName.vol_change, back_color_1 = BTSColors.Greeks.default_background, back_color_2 = BTSColors.Greeks.default_background, font_color_1 = BTSColors.Greeks.default_text, font_color_2 = BTSColors.Greeks.default_text, is_visibile = false }); + column_configuration_list.Add(new NMSheetColumnConfiguration() { column_name = NMSheetColumnName.straddle_change, back_color_1 = BTSColors.Greeks.default_background, back_color_2 = BTSColors.Greeks.default_background, font_color_1 = BTSColors.Greeks.default_text, font_color_2 = BTSColors.Greeks.default_text, is_visibile = false }); + column_configuration_list.Add(new NMSheetColumnConfiguration() { column_name = NMSheetColumnName.straddle, back_color_1 = BTSColors.Greeks.default_background, back_color_2 = BTSColors.Greeks.default_background, font_color_1 = BTSColors.Greeks.default_text, font_color_2 = BTSColors.Greeks.default_text, is_visibile = false, display_format = theo_tick_type }); + column_configuration_list.Add(new NMSheetColumnConfiguration() { column_name = NMSheetColumnName.quoteset_mid_price_straddle, back_color_1 = BTSColors.Quoteset.mid_straddle_background, back_color_2 = BTSColors.Quoteset.mid_straddle_background, font_color_1 = BTSColors.Quoteset.default_text, font_color_2 = BTSColors.Quoteset.default_text, is_visibile = false, display_format = theo_tick_type }); + /// put + + /// put ee bid + column_configuration_list.Add(new NMSheetColumnConfiguration() { column_name = NMSheetColumnName.put_ee_set_bid_edge, back_color_1 = BTSColors.Quoter.set_background, back_color_2 = BTSColors.Quoter.set_background, font_color_1 = BTSColors.Quoter.default_text, font_color_2 = BTSColors.Quoter.default_text, display_format = theo_tick_type, is_visibile = true }); + column_configuration_list.Add(new NMSheetColumnConfiguration() { column_name = NMSheetColumnName.put_ee_set_bid_size, back_color_1 = BTSColors.Quoter.set_background, back_color_2 = BTSColors.Quoter.set_background, font_color_1 = BTSColors.Quoter.default_text, font_color_2 = BTSColors.Quoter.default_text, display_format = Utilities.General.TickConverter2.TickType.tickDecimal0, is_visibile = true }); + column_configuration_list.Add(new NMSheetColumnConfiguration() { column_name = NMSheetColumnName.put_ee_bid_price, back_color_1 = BTSColors.Quoter.default_background, back_color_2 = BTSColors.Quoter.default_background, font_color_1 = BTSColors.Quoter.bid_text, font_color_2 = BTSColors.Quoter.bid_text, display_format = theo_tick_type, is_visibile = true }); + + /// put quoter bid + column_configuration_list.Add(new NMSheetColumnConfiguration() { column_name = NMSheetColumnName.put_quoteset_resolved_bid_edge, back_color_1 = BTSColors.Quoteset.default_background, back_color_2 = BTSColors.Quoteset.default_background, font_color_1 = BTSColors.Quoteset.default_text, font_color_2 = BTSColors.Quoteset.default_text, display_format = theo_tick_type, is_visibile = false }); + column_configuration_list.Add(new NMSheetColumnConfiguration() { column_name = NMSheetColumnName.put_quoteset_resolved_bid_size, back_color_1 = BTSColors.Quoteset.default_background, back_color_2 = BTSColors.Quoteset.default_background, font_color_1 = BTSColors.Quoteset.default_text, font_color_2 = BTSColors.Quoteset.default_text, display_format = Utilities.General.TickConverter2.TickType.tickDecimal0, is_visibile = false }); + column_configuration_list.Add(new NMSheetColumnConfiguration() { column_name = NMSheetColumnName.put_quoter_set_bid_edge, back_color_1 = BTSColors.Quoter.set_background, back_color_2 = BTSColors.Quoter.set_background, font_color_1 = BTSColors.Quoter.default_text, font_color_2 = BTSColors.Quoter.default_text, display_format = theo_tick_type, is_visibile = false }); + column_configuration_list.Add(new NMSheetColumnConfiguration() { column_name = NMSheetColumnName.put_quoter_set_bid_size, back_color_1 = BTSColors.Quoter.set_background, back_color_2 = BTSColors.Quoter.set_background, font_color_1 = BTSColors.Quoter.default_text, font_color_2 = BTSColors.Quoter.default_text, display_format = Utilities.General.TickConverter2.TickType.tickDecimal0, is_visibile = false }); + column_configuration_list.Add(new NMSheetColumnConfiguration() { column_name = NMSheetColumnName.put_quoter_bid_price, back_color_1 = BTSColors.Quoter.default_background, back_color_2 = BTSColors.Quoter.default_background, font_color_1 = BTSColors.Quoter.bid_text, font_color_2 = BTSColors.Quoter.bid_text, display_format = theo_tick_type, is_visibile = false }); + column_configuration_list.Add(new NMSheetColumnConfiguration() { column_name = NMSheetColumnName.put_quoter_bid_size, back_color_1 = BTSColors.Quoter.default_background, back_color_2 = BTSColors.Quoter.default_background, font_color_1 = BTSColors.Quoter.bid_text, font_color_2 = BTSColors.Quoter.bid_text, display_format = Utilities.General.TickConverter2.TickType.tickDecimal0, is_visibile = false }); + + /// put bid bbo + column_configuration_list.Add(new NMSheetColumnConfiguration() { column_name = NMSheetColumnName.put_bid_size, back_color_1 = BTSColors.MarketData.default_background, back_color_2 = BTSColors.MarketData.default_background, font_color_1 = BTSColors.MarketData.bid_text, font_color_2 = BTSColors.MarketData.bid_text, display_format = Utilities.General.TickConverter2.TickType.tickDecimal0 }); + column_configuration_list.Add(new NMSheetColumnConfiguration() { column_name = NMSheetColumnName.put_bid_price, back_color_1 = BTSColors.MarketData.default_background, back_color_2 = BTSColors.MarketData.default_background, font_color_1 = BTSColors.MarketData.bid_text, font_color_2 = BTSColors.MarketData.bid_text, display_format = price_tick_type }); + + column_configuration_list.Add(new NMSheetColumnConfiguration() { column_name = NMSheetColumnName.put_quoteset_mid_price, back_color_1 = BTSColors.Quoteset.mid_price_background, back_color_2 = BTSColors.Quoteset.mid_price_background, font_color_1 = BTSColors.Quoteset.default_text, font_color_2 = BTSColors.Quoteset.default_text, display_format = theo_tick_type, font = new Font("Tahoma", 8), is_visibile = false }); + column_configuration_list.Add(new NMSheetColumnConfiguration() { column_name = NMSheetColumnName.put_quoteset_mid_theo_diff, back_color_1 = BTSColors.Quoteset.default_background, back_color_2 = BTSColors.Quoteset.default_background, font_color_1 = BTSColors.Quoteset.default_text, font_color_2 = BTSColors.Quoteset.default_text, display_format = theo_tick_type, font = new Font("Tahoma", 7), is_visibile = false }); + + /// put theo + column_configuration_list.Add(new NMSheetColumnConfiguration() { column_name = NMSheetColumnName.put_theo, back_color_1 = BTSColors.Greeks.live_theo, back_color_2 = BTSColors.Greeks.live_theo, font_color_1 = BTSColors.Greeks.default_text, font_color_2 = BTSColors.Greeks.default_text, display_format = theo_tick_type, font = new Font("Tahoma", 8) }); + column_configuration_list.Add(new NMSheetColumnConfiguration() { column_name = NMSheetColumnName.presave_put_theo, back_color_1 = BTSColors.Presave.default_background, back_color_2 = BTSColors.Presave.default_background, font_color_1 = BTSColors.Presave.default_text, font_color_2 = BTSColors.Presave.default_text, display_format = theo_tick_type, is_visibile = false }); + column_configuration_list.Add(new NMSheetColumnConfiguration() { column_name = NMSheetColumnName.presave_put_theo_diff, back_color_1 = BTSColors.Presave.default_background, back_color_2 = BTSColors.Presave.default_background, font_color_1 = BTSColors.Presave.default_text, font_color_2 = BTSColors.Presave.default_text, display_format = theo_tick_type, is_visibile = false }); + column_configuration_list.Add(new NMSheetColumnConfiguration() { column_name = NMSheetColumnName.put_delta, back_color_1 = BTSColors.Greeks.delta, back_color_2 = BTSColors.Greeks.delta, font_color_1 = BTSColors.Greeks.default_text, font_color_2 = BTSColors.Greeks.default_text, display_format = Utilities.General.TickConverter2.TickType.tickDecimal0 }); + column_configuration_list.Add(new NMSheetColumnConfiguration() { column_name = NMSheetColumnName.put_gamma, back_color_1 = BTSColors.Greeks.default_background, back_color_2 = BTSColors.Greeks.default_background, font_color_1 = BTSColors.Greeks.default_text, font_color_2 = BTSColors.Greeks.default_text, is_visibile = false }); + column_configuration_list.Add(new NMSheetColumnConfiguration() { column_name = NMSheetColumnName.put_vega, back_color_1 = BTSColors.Greeks.default_background, back_color_2 = BTSColors.Greeks.default_background, font_color_1 = BTSColors.Greeks.default_text, font_color_2 = BTSColors.Greeks.default_text, is_visibile = false }); + + /// put ask bbo + column_configuration_list.Add(new NMSheetColumnConfiguration() { column_name = NMSheetColumnName.put_ask_price, back_color_1 = BTSColors.MarketData.default_background, back_color_2 = BTSColors.MarketData.default_background, font_color_1 = BTSColors.MarketData.ask_text, font_color_2 = BTSColors.MarketData.ask_text, display_format = price_tick_type }); + column_configuration_list.Add(new NMSheetColumnConfiguration() { column_name = NMSheetColumnName.put_ask_size, back_color_1 = BTSColors.MarketData.default_background, back_color_2 = BTSColors.MarketData.default_background, font_color_1 = BTSColors.MarketData.ask_text, font_color_2 = BTSColors.MarketData.ask_text, display_format = Utilities.General.TickConverter2.TickType.tickDecimal0 }); + + /// put quoter ask + column_configuration_list.Add(new NMSheetColumnConfiguration() { column_name = NMSheetColumnName.put_quoter_ask_price, back_color_1 = BTSColors.Quoter.default_background, back_color_2 = BTSColors.Quoter.default_background, font_color_1 = BTSColors.Quoter.ask_text, font_color_2 = BTSColors.Quoter.ask_text, display_format = theo_tick_type, is_visibile = false }); + column_configuration_list.Add(new NMSheetColumnConfiguration() { column_name = NMSheetColumnName.put_quoter_ask_size, back_color_1 = BTSColors.Quoter.default_background, back_color_2 = BTSColors.Quoter.default_background, font_color_1 = BTSColors.Quoter.ask_text, font_color_2 = BTSColors.Quoter.ask_text, display_format = Utilities.General.TickConverter2.TickType.tickDecimal0, is_visibile = false }); + column_configuration_list.Add(new NMSheetColumnConfiguration() { column_name = NMSheetColumnName.put_quoteset_resolved_ask_edge, back_color_1 = BTSColors.Quoteset.default_background, back_color_2 = BTSColors.Quoteset.default_background, font_color_1 = BTSColors.Quoteset.default_text, font_color_2 = BTSColors.Quoteset.default_text, display_format = theo_tick_type, is_visibile = false }); + column_configuration_list.Add(new NMSheetColumnConfiguration() { column_name = NMSheetColumnName.put_quoter_set_ask_edge, back_color_1 = BTSColors.Quoter.set_background, back_color_2 = BTSColors.Quoter.set_background, font_color_1 = BTSColors.Quoter.default_text, font_color_2 = BTSColors.Quoter.default_text, display_format = theo_tick_type, is_visibile = false }); + column_configuration_list.Add(new NMSheetColumnConfiguration() { column_name = NMSheetColumnName.put_quoteset_resolved_ask_size, back_color_1 = BTSColors.Quoteset.default_background, back_color_2 = BTSColors.Quoteset.default_background, font_color_1 = BTSColors.Quoteset.default_text, font_color_2 = BTSColors.Quoteset.default_text, display_format = Utilities.General.TickConverter2.TickType.tickDecimal0, is_visibile = false }); + column_configuration_list.Add(new NMSheetColumnConfiguration() { column_name = NMSheetColumnName.put_quoter_set_ask_size, back_color_1 = BTSColors.Quoter.set_background, back_color_2 = BTSColors.Quoter.set_background, font_color_1 = BTSColors.Quoter.default_text, font_color_2 = BTSColors.Quoter.default_text, display_format = Utilities.General.TickConverter2.TickType.tickDecimal0, is_visibile = false }); + + /// put ee ask + column_configuration_list.Add(new NMSheetColumnConfiguration() { column_name = NMSheetColumnName.put_ee_ask_price, back_color_1 = BTSColors.Quoter.default_background, back_color_2 = BTSColors.Quoter.default_background, font_color_1 = BTSColors.Quoter.ask_text, font_color_2 = BTSColors.Quoter.ask_text, display_format = theo_tick_type, is_visibile = true }); + column_configuration_list.Add(new NMSheetColumnConfiguration() { column_name = NMSheetColumnName.put_ee_set_ask_edge, back_color_1 = BTSColors.Quoter.set_background, back_color_2 = BTSColors.Quoter.set_background, font_color_1 = BTSColors.Quoter.default_text, font_color_2 = BTSColors.Quoter.default_text, display_format = theo_tick_type, is_visibile = true }); + column_configuration_list.Add(new NMSheetColumnConfiguration() { column_name = NMSheetColumnName.put_ee_set_ask_size, back_color_1 = BTSColors.Quoter.set_background, back_color_2 = BTSColors.Quoter.set_background, font_color_1 = BTSColors.Quoter.default_text, font_color_2 = BTSColors.Quoter.default_text, display_format = Utilities.General.TickConverter2.TickType.tickDecimal0, is_visibile = true }); + + column_configuration_list.Add(new NMSheetColumnConfiguration() { column_name = NMSheetColumnName.put_position, back_color_1 = BTSColors.Position.default_background, back_color_2 = BTSColors.Position.default_background, font_color_1 = BTSColors.Position.default_text, font_color_2 = BTSColors.Position.default_text, display_format = Utilities.General.TickConverter2.TickType.tickDecimal0, is_visibile = false }); + + /// shifts + column_configuration_list.Add(new NMSheetColumnConfiguration() { column_name = NMSheetColumnName.call_shift, back_color_1 = BTSColors.Greeks.default_background, back_color_2 = BTSColors.Greeks.default_background, font_color_1 = BTSColors.Greeks.default_text, font_color_2 = BTSColors.Greeks.default_text, display_format = Utilities.General.TickConverter2.TickType.tickDecimal0, is_visibile = false, minimum_width = 1 }); + column_configuration_list.Add(new NMSheetColumnConfiguration() { column_name = NMSheetColumnName.put_shift, back_color_1 = BTSColors.Greeks.default_background, back_color_2 = BTSColors.Greeks.default_background, font_color_1 = BTSColors.Greeks.default_text, font_color_2 = BTSColors.Greeks.default_text, display_format = Utilities.General.TickConverter2.TickType.tickDecimal0, is_visibile = false, minimum_width = 1 }); + column_configuration_list.Add(new NMSheetColumnConfiguration() { column_name = NMSheetColumnName.call_shifted_theo, back_color_1 = BTSColors.Greeks.default_background, back_color_2 = BTSColors.Greeks.default_background, font_color_1 = BTSColors.Greeks.default_text, font_color_2 = BTSColors.Greeks.default_text, display_format = Utilities.General.TickConverter2.TickType.tickDecimal0, is_visibile = false, minimum_width = 1 }); + column_configuration_list.Add(new NMSheetColumnConfiguration() { column_name = NMSheetColumnName.put_shifted_theo, back_color_1 = BTSColors.Greeks.default_background, back_color_2 = BTSColors.Greeks.default_background, font_color_1 = BTSColors.Greeks.default_text, font_color_2 = BTSColors.Greeks.default_text, display_format = Utilities.General.TickConverter2.TickType.tickDecimal0, is_visibile = false, minimum_width = 1 }); + } + + public NMSheetSettingColumnOrganization() + : this(null) { } + + public IDictionary get_mapped_col_data() { + Dictionary rv = new Dictionary(); + foreach (NMSheetColumnConfiguration conf in column_configuration_list) + rv.Add(conf.column_name, conf); + return rv; + } + + public uint get_column_min_width(NMSheetColumnName col_name) { + IDictionary map = get_mapped_col_data(); + NMSheetColumnConfiguration col_conf = null; + if (map.TryGetValue(col_name, out col_conf) && col_conf != null) + return col_conf.minimum_width.Value; + return new NMSheetColumnConfiguration().minimum_width.Value; + } + + public static void parse_column(NMSheetColumnName col_name, out bool is_call, out bool is_put, out bool is_bid, out bool is_ask) { + is_call = _col_basic_info[(int)col_name].is_call; + is_put = _col_basic_info[(int)col_name].is_put; + is_bid = _col_basic_info[(int)col_name].is_bid; + is_ask = _col_basic_info[(int)col_name].is_ask; + } + + public static NMSheetColumnType get_col_type(NMSheetColumnName col_name) { + foreach (KeyValuePair> p in _col_type_map) + if (p.Value.Contains(col_name)) + return p.Key; + bts.Log.assert(false, String.Format("NMSheetColumnName {0} does not belong to any type", col_name)); + return NMSheetColumnType.Security; + } + + public static IEnumerable get_cols_for_type(NMSheetColumnType col_type) { + HashSet rv; + return NMSheetSettingColumnOrganization._col_type_map.TryGetValue(col_type, out rv) ? rv : new HashSet(); + } + + public static NMSheetColumnInfo get_column_info(NMSheetColumnName col) { + return _col_basic_info[(int)col]; + } + + } +} diff --git a/src/client/spark/NMSheets/Settings/NMSheetSettingDriver.cs b/src/client/spark/NMSheets/Settings/NMSheetSettingDriver.cs new file mode 100644 index 000000000..5cee4f58a --- /dev/null +++ b/src/client/spark/NMSheets/Settings/NMSheetSettingDriver.cs @@ -0,0 +1,24 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace BCG +{ + [Serializable] + public class NMSheetSettingDriver + { + [System.ComponentModel.DisplayName("Driver Price Up/Down Move Interval")] + public double driver_move_interval {get; set;} + + [System.ComponentModel.DisplayName("Driver Price Formatting")] + public BCG.Utilities.General.TickConverter2.TickType tick_type {get; set;} + + public NMSheetSettingDriver() + { + driver_move_interval = 0.25; + tick_type = Utilities.General.TickConverter2.TickType.tickDecimal2; + } + } +} diff --git a/src/client/spark/NMSheets/Settings/NMSheetSettingExpirationHeader.cs b/src/client/spark/NMSheets/Settings/NMSheetSettingExpirationHeader.cs new file mode 100644 index 000000000..e6d106229 --- /dev/null +++ b/src/client/spark/NMSheets/Settings/NMSheetSettingExpirationHeader.cs @@ -0,0 +1,88 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.ComponentModel; + +using mbts.ui; + +namespace BCG +{ + [Serializable] + public class NMSheetSettingExpirationHeader + { + [Category("Straddle Display")] + [DisplayName("Straddle Display")] + public StraddleDisplayEnum straddle_display_type { get; set; } + + [Category("Straddle Display")] + [DisplayName("Straddle Theo vs Market Negative Back Color")] + public System.Drawing.Color straddle_theovsmarket_negative_back_color { get; set; } + + [Category("Straddle Display")] + [DisplayName("Straddle Theo vs Market Negative Font Color")] + public System.Drawing.Color straddle_theovsmarket_negative_font_color { get; set; } + + [Category("Straddle Display")] + [DisplayName("Straddle Theo vs Market Positive Back Color")] + public System.Drawing.Color straddle_theovsmarket_positive_back_color { get; set; } + + [Category("Straddle Display")] + [DisplayName("Straddle Theo vs Market Positive Font Color")] + public System.Drawing.Color straddle_theovsmarket_positive_font_color { get; set; } + + [Category("Vol Control")] + [DisplayName("Show Vol Shift Control")] + public bool show_vol_shift_control { get; set; } + + [Category("Vol Control")] + [DisplayName("Vol Shift Interval")] + public double vol_shift_interval { get; set; } + + [DisplayName("Show ATM Navigation Button")] + public bool show_atm_navigation_button { get; set; } + + [Category("Expiration Display")] + [DisplayName("Expiration Font")] + public System.Drawing.Font expiration_font { get; set; } + + [Category("Expiration Display")] + [DisplayName("Expiration Alternate Back Color 1")] + public System.Drawing.Color expiration_background_color_1 { get; set; } + + [Category("Expiration Display")] + [DisplayName("Expiration Alternate Back Color 2")] + public System.Drawing.Color expiration_background_color_2 { get; set; } + + [Category("Expiration Display")] + [DisplayName("Expiration Seperator Line")] + public System.Drawing.Color expiration_seperator_line_color { get; set; } + + [Category("Expiration Display")] + [DisplayName("Expiration Alternate Font Color 1")] + public System.Drawing.Color expiration_font_color_1 { get; set; } + + [Category("Expiration Display")] + [DisplayName("Expiration Alternate Font Color 2")] + public System.Drawing.Color expiration_font_color_2 { get; set; } + + public NMSheetSettingExpirationHeader() + { + straddle_display_type = StraddleDisplayEnum.StraddleTheo; + straddle_theovsmarket_negative_back_color = BTSColors.Orders.straddle_theovsmarket_negative; + straddle_theovsmarket_negative_font_color = BTSColors.Orders.default_text; + straddle_theovsmarket_positive_back_color = BTSColors.Orders.straddle_theovsmarket_positive; + straddle_theovsmarket_positive_font_color = BTSColors.Orders.default_text; + show_vol_shift_control = true; + show_atm_navigation_button = true; + vol_shift_interval = 0.1; + expiration_font = new System.Drawing.Font("Tahoma", 10); + expiration_background_color_1 = BTSColors.header; + expiration_background_color_2 = BTSColors.header; + expiration_seperator_line_color = BTSColors.Grid.expiration_seperator; + expiration_font_color_1 = BTSColors.header_text; + expiration_font_color_2 = BTSColors.header_text; + } + } +} diff --git a/src/client/spark/NMSheets/Settings/NMSheetSettingFilter.cs b/src/client/spark/NMSheets/Settings/NMSheetSettingFilter.cs new file mode 100644 index 000000000..7e4615347 --- /dev/null +++ b/src/client/spark/NMSheets/Settings/NMSheetSettingFilter.cs @@ -0,0 +1,32 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace BCG +{ + [Serializable] + public class NMSheetSettingFilter + { + private bool _filter_ee_task_strikes = false; + public bool filter_ee_task_strikes + { + get { return _filter_ee_task_strikes; } + set { _filter_ee_task_strikes = value; } + } + + private bool _filter_on_ee_task_strikes = false; + public bool filter_on_ee_task_strikes + { + get { return _filter_on_ee_task_strikes; } + set { _filter_on_ee_task_strikes = value; } + } + private Nullable _filter_positive_edge_strikes = false; + public Nullable filter_positive_edge_strikes + { + get { return _filter_positive_edge_strikes == null ? false : _filter_positive_edge_strikes.Value; } + set { _filter_positive_edge_strikes = value == null ? false : value.Value; } + } + } +} diff --git a/src/client/spark/NMSheets/Settings/NMSheetSettingGrid.cs b/src/client/spark/NMSheets/Settings/NMSheetSettingGrid.cs new file mode 100644 index 000000000..98d314a41 --- /dev/null +++ b/src/client/spark/NMSheets/Settings/NMSheetSettingGrid.cs @@ -0,0 +1,158 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.ComponentModel; +using System.Reflection; +using mbts.ui; + +namespace BCG +{ + [Serializable] + public class NMSheetSettingGridInternal + { + public enum NavigationMode + { + Auto = 0, + Jump, + Scroll + } + + public enum NMSheetGridHorizontalTextAlignment + { + Center = 0, + Left, + Right + } + + private readonly bool _is_remoted = mbts.config.Configuration.get().is_remote_app; + + [Category("Grid Lines")] + [DisplayName("Row Seperator Line Color")] + public System.Drawing.Color row_seperator_line_color { get; set; } + + [Category("Grid Lines")] + [DisplayName("Expiration Seperator Line Color")] + public System.Drawing.Color expiration_seperator_line_color { get; set; } + + [Category("Grid Lines")] + [DisplayName("Draw Row Seperator Line")] + public bool draw_row_separator_line { get; set; } + + [Category("Text Padding")] + [DisplayName("Header Vertical Padding")] + public int header_vertical_padding { get; set; } + + [Category("Text Padding")] + [DisplayName("Horizontal Padding")] + public int horizontal_padding { get; set; } + + [Category("Text Padding")] + [DisplayName("Verical Padding")] + public int vertical_padding { get; set; } + + [Category("Scrolling")] + [DisplayName("Horizontal Scroll Step")] + public int horizontal_scroll_step { get; set; } + + [Category("Scrolling")] + [DisplayName("Verical Scroll Step")] + public int vertical_scroll_step { get; set; } + + [Category("Scrolling")] + [DisplayName("Distance For Page")] + public int distance_for_page { get; set; } + + [Category("Scrolling")] + [DisplayName("Distance For Cell")] + public int distance_for_cell { get; set; } + + [Category("Scrolling")] + [DisplayName("Track Motion")] + public bool track_motion { get; set; } + + [Category("Scrolling")] + [DisplayName("Scrolls Per Second")] + public int scroll_per_second { get; set; } + + [Category("Scrolling")] + [DisplayName("Speed Threshold")] + public int speed_threshhold { get; set; } + + [Category("Scrolling")] + [DisplayName("Distance Threshold")] + public int distance_threshhold { get; set; } + + [Category("Scrolling")] + [DisplayName("Maximum Frames In Scroll")] + public int scroll_max_frames { get; set; } + + [Category("Quick Navigation")] + [Description("Quick Navigation to Expirations and ATM Strikes can be Jump, Scroll or Auto in which case the system decides the best mode based on available resources")] + [DisplayName("Navigation Mode")] + public NavigationMode navigation_mode { get; set; } + + [DisplayName("Grid Paint Throttle(ms)")] + public int grid_paint_throttle_ms { get; set; } + + private Nullable _min_column_width_dec_before_resizing = 64; + [DisplayName("Minimum Column Width Decrease Before Resizing Column Width")] + public Nullable min_column_size_dec_before_refitting + { + get { return _min_column_width_dec_before_resizing.HasValue ? _min_column_width_dec_before_resizing.Value : 64; } + set { _min_column_width_dec_before_resizing = value.HasValue ? value.Value : 64; } + } + + [Browsable(false)] + [DisplayName("Grid Cell Highlight Color")] + [Description("This is currently not used")] + public System.Drawing.Color cell_highlight_color { get; set; } + + [Browsable(false)] + [DisplayName("Grid Cell Highlight Rectangle Color")] + [Description("This is currently not used")] + public System.Drawing.Color cell_highlight_rectangle_color { get; set; } + + private Nullable _horizontal_text_alignment = NMSheetGridHorizontalTextAlignment.Center; + [Category("Text Alignment")] + [DisplayName("Horizontal Text Alignment")] + public Nullable horizontal_text_alignment + { + get { return (_horizontal_text_alignment != null && _horizontal_text_alignment.HasValue) ? _horizontal_text_alignment.Value : NMSheetGridHorizontalTextAlignment.Center; } + set { _horizontal_text_alignment = (value != null && value.HasValue) ? value.Value : NMSheetGridHorizontalTextAlignment.Center; } + } + + private Nullable _selection_back_color = BTSColors.Grid.grid_selection_background; + [Category("Selection")] + [DisplayName("Selection Background Color")] + public Nullable selection_back_color + { + get { return (_selection_back_color != null && _selection_back_color.HasValue) ? _selection_back_color.Value : (System.Drawing.Color) BTSColors.Grid.grid_selection_background; } + set { _selection_back_color = (value != null && value.HasValue) ? value.Value : (System.Drawing.Color)BTSColors.Grid.grid_selection_background; } + } + + public NMSheetSettingGridInternal() + { + row_seperator_line_color = BTSColors.Grid.grid_line; + expiration_seperator_line_color = BTSColors.Grid.expiration_seperator; + header_vertical_padding = 2; + draw_row_separator_line = true; + horizontal_padding = 4; + vertical_padding = 4; + horizontal_scroll_step = 50; + vertical_scroll_step = 100; + distance_for_page = 50; + distance_for_cell = 10; + track_motion = true; + scroll_per_second = 1000; + speed_threshhold = 10; + distance_threshhold = 10; + grid_paint_throttle_ms = 400; + scroll_max_frames = 10; + cell_highlight_color = System.Drawing.Color.Yellow; + cell_highlight_rectangle_color = System.Drawing.Color.Black; + navigation_mode = NavigationMode.Auto; + } + } +} diff --git a/src/client/spark/NMSheets/Settings/NMSheetSettingLayout.cs b/src/client/spark/NMSheets/Settings/NMSheetSettingLayout.cs new file mode 100644 index 000000000..98a78ce6e --- /dev/null +++ b/src/client/spark/NMSheets/Settings/NMSheetSettingLayout.cs @@ -0,0 +1,125 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace BCG +{ + [Serializable] + public class NMSheetSettingLayout + { + [System.ComponentModel.Category("Header")] + [System.ComponentModel.DisplayName("Show Settings Header (Restart required)")] + public bool show_settings_header { get; set; } + + [System.ComponentModel.Category("Header")] + [System.ComponentModel.DisplayName("Show Expiration Navigator (Restart required)")] + public bool show_exp_navigator { get; set; } + + private Nullable _condense_navigator_expirations = false; + [System.ComponentModel.Category("Header")] + [System.ComponentModel.DisplayName("Condense Navigator Expirations (Restart required)")] + public Nullable condense_navigator_expirations + { + get { return _condense_navigator_expirations.HasValue ? _condense_navigator_expirations.Value : false; } + set { _condense_navigator_expirations = value.HasValue ? value.Value : false; } + } + + [System.ComponentModel.Category("Header")] + [System.ComponentModel.DisplayName("Show Expiration ATM Header (Restart required)")] + public bool show_exp_atm_header { get; set; } + + #region One-Five in Title + private Nullable _show_onefive_in_title = false; + [System.ComponentModel.Category("One Five Title")] + [System.ComponentModel.DisplayName("Show One-Five in Title")] + public Nullable show_onefive_in_title + { + get { return _show_onefive_in_title.HasValue ? _show_onefive_in_title.Value : false; } + set { _show_onefive_in_title = value.HasValue ? value.Value : false; } + } + #endregion + + #region Risk in Title + private Nullable _show_day_pnl_in_title = false; + [System.ComponentModel.Category("Risk Title")] + [System.ComponentModel.DisplayName("Show Day PNL in Title")] + public Nullable show_day_pnl_in_title + { + get { return _show_day_pnl_in_title.HasValue ? _show_day_pnl_in_title.Value : false; } + set { _show_day_pnl_in_title = value.HasValue ? value.Value : false; } + } + + private Nullable _show_day_delta_in_title = false; + [System.ComponentModel.Category("Risk Title")] + [System.ComponentModel.DisplayName("Show Day Delta in Title")] + public Nullable show_day_delta_in_title + { + get { return _show_day_delta_in_title.HasValue ? _show_day_delta_in_title.Value : false; } + set { _show_day_delta_in_title = value.HasValue ? value.Value : false; } + } + + private Nullable _show_day_gamma_in_title = false; + [System.ComponentModel.Category("Risk Title")] + [System.ComponentModel.DisplayName("Show Day Gamma in Title")] + public Nullable show_day_gamma_in_title + { + get { return _show_day_gamma_in_title.HasValue ? _show_day_gamma_in_title.Value : false; } + set { _show_day_gamma_in_title = value.HasValue ? value.Value : false; } + } + + private Nullable _show_day_vega_in_title = false; + [System.ComponentModel.Category("Risk Title")] + [System.ComponentModel.DisplayName("Show Day Vega in Title")] + public Nullable show_day_vega_in_title + { + get { return _show_day_vega_in_title.HasValue ? _show_day_vega_in_title.Value : false; } + set { _show_day_vega_in_title = value.HasValue ? value.Value : false; } + } + + private Nullable _show_day_theta_in_title = false; + [System.ComponentModel.Category("Risk Title")] + [System.ComponentModel.DisplayName("Show Day Theta in Title")] + public Nullable show_day_theta_in_title + { + get { return _show_day_theta_in_title.HasValue ? _show_day_theta_in_title.Value : false; } + set { _show_day_theta_in_title = value.HasValue ? value.Value : false; } + } + + public bool trader_risk_input_complete() { return !String.IsNullOrEmpty(_risk_account) && !String.IsNullOrEmpty(risk_in_terms_of); } + + public bool show_trader_risk_in_title() + { + return show_day_pnl_in_title.Value || show_day_delta_in_title.Value || show_day_gamma_in_title.Value || + show_day_vega_in_title.Value || show_day_theta_in_title.Value; + } + + private string _risk_in_terms_of = String.Empty; + [System.ComponentModel.Category("Risk Title")] + [System.ComponentModel.DisplayName("Risk In Terms Of")] + public string risk_in_terms_of + { + get { return _risk_in_terms_of; } + set { _risk_in_terms_of = value; } + } + + private string _risk_account = String.Empty; + [System.ComponentModel.Category("Risk Title")] + [System.ComponentModel.DisplayName("Risk Account(s)")] + public string risk_account + { + get { return _risk_account; } + set { _risk_account = value; } + } + + #endregion + + public NMSheetSettingLayout() + { + show_settings_header = false; + show_exp_navigator = false; + show_exp_atm_header = true; + } + } +} diff --git a/src/client/spark/NMSheets/Settings/NMSheetSettingMouse.cs b/src/client/spark/NMSheets/Settings/NMSheetSettingMouse.cs new file mode 100644 index 000000000..768a8887d --- /dev/null +++ b/src/client/spark/NMSheets/Settings/NMSheetSettingMouse.cs @@ -0,0 +1,112 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace BCG +{ + public enum NMSheetMouseAction + { + Click, + DoubleClick, + Drag, + Swipe + } + + public enum NMSheetSpreadInitialization + { + Smart, + Buy, + Sell + } + + [Serializable] + public class NMSheetSettingMouse + { + #region Spreads + private NMSheetMouseAction _spread_mouse_action = NMSheetMouseAction.Click; + [System.ComponentModel.Category("Spread Box")] + [System.ComponentModel.DisplayName("Spread Mouse Action")] + [System.ComponentModel.Browsable(false)] + public NMSheetMouseAction spread_mouse_action + { + get {return _spread_mouse_action;} + set { _spread_mouse_action = value; } + } + + private MouseButtons _spread_mouse_button = MouseButtons.Left; + [System.ComponentModel.Category("Spread Box")] + [System.ComponentModel.DisplayName("Spread Mouse Button")] + [System.ComponentModel.Browsable(false)] + public MouseButtons spread_mouse_button + { + get { return _spread_mouse_button; } + set { _spread_mouse_button = value; } + } + + private NMSheetSpreadInitialization _spread_initialization = NMSheetSpreadInitialization.Smart; + [System.ComponentModel.Category("Spread Box")] + [System.ComponentModel.DisplayName("Spread Action")] + [System.ComponentModel.Browsable(false)] + public NMSheetSpreadInitialization spread_initialization + { + get { return _spread_initialization; } + set { _spread_initialization = value; } + } + #endregion + + #region Scrolling + private SheetsScrollMode _scroll_mode = SheetsScrollMode.Classic; + [System.ComponentModel.Category("Scrolling")] + [System.ComponentModel.DisplayName("Scrolling Mode")] + [System.ComponentModel.Browsable (false)] + public SheetsScrollMode scroll_mode + { + get { return _scroll_mode; } + set { _scroll_mode = value; } + } + + private MouseButtons _classical_mode_scrolling_mouse_button = MouseButtons.Left; + [System.ComponentModel.Category("Scrolling")] + [System.ComponentModel.DisplayName("Classic Mode Scrolling Mouse Button")] + public MouseButtons classical_mode_scrolling_mouse_button + { + get { return _classical_mode_scrolling_mouse_button; } + set { _classical_mode_scrolling_mouse_button = value; } + } + #endregion + + #region Selection + private bool _enable_selection = true; + [System.ComponentModel.Category("Selection")] + [System.ComponentModel.DisplayName("Enable Selection")] + public bool enable_selection + { + get { return _enable_selection; } + set { _enable_selection = value; } + } + + private bool _limit_selection_to_single_column = true; + [System.ComponentModel.Category("Selection")] + [System.ComponentModel.DisplayName("Limit Selection To Single Column")] + public bool limit_selection_to_single_column + { + get { return _limit_selection_to_single_column; } + set { _limit_selection_to_single_column = value; } + } + + private MouseButtons _selection_mouse_button = MouseButtons.Right; + [System.ComponentModel.Category("Selection")] + [System.ComponentModel.DisplayName("Selection Mouse Button")] + public MouseButtons selection_mouse_button + { + get { return _selection_mouse_button; } + set { _selection_mouse_button = value; } + } + + #endregion + + } +} diff --git a/src/client/spark/NMSheets/Settings/NMSheetSettingQuoteset.cs b/src/client/spark/NMSheets/Settings/NMSheetSettingQuoteset.cs new file mode 100644 index 000000000..c674cfee6 --- /dev/null +++ b/src/client/spark/NMSheets/Settings/NMSheetSettingQuoteset.cs @@ -0,0 +1,89 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Drawing; + +using mbts.ui; + +namespace BCG +{ + [Serializable] + public class NMSheetSettingQuoteset + { + #region Quoteset override + private Nullable _quoteset_override_id = null; + [System.ComponentModel.Browsable(false)] + public Nullable quoteset_override_id + { + get { return _quoteset_override_id; } + set { _quoteset_override_id = value; } + } + + public bool get_quoteset_id(out uint qs_id) + { + if (_quoteset_override_id.HasValue) + { + qs_id = _quoteset_override_id.Value; + return true; + } + else + { + qs_id = 0; + return false; + } + } + #endregion + + #region Edges/Sizes + private string _preconfigured_edges = "0.25, 0.30, 0.35, 0.40, 0.45, 0.50, 1.0"; + [System.ComponentModel.Category("Edges/Sizes")] + [System.ComponentModel.DisplayName("Preconfigured Edges")] + public string preconfigured_edges + { + get { return _preconfigured_edges; } + set { _preconfigured_edges = value; } + } + + + private string _preconfigured_edge_shifts = "-0.10, -0.05, 0.05, 0.10, 0.25"; + [System.ComponentModel.Category("Edges/Sizes")] + [System.ComponentModel.DisplayName("Preconfigured Edge Shifts")] + public string preconfigured_edge_shifts + { + get { return _preconfigured_edge_shifts; } + set { _preconfigured_edge_shifts = value; } + } + + private string _preconfigured_sizes = "1, 5, 10, 20, 25, 50, 100"; + [System.ComponentModel.Category("Edges/Sizes")] + [System.ComponentModel.DisplayName("Preconfigured Sizes")] + public string preconfigured_sizes + { + get { return _preconfigured_sizes; } + set { _preconfigured_sizes = value; } + } + #endregion + + #region Pump Fades + private string _preconfigured_pumpfades = "0.05, 0.10, 0.15, 0.2"; + [System.ComponentModel.Category("Pumps/Fades")] + [System.ComponentModel.DisplayName("Preconfigured Pump/Fade")] + public string preconfigured_pumpfades + { + get { return _preconfigured_pumpfades; } + set { _preconfigured_pumpfades = value; } + } + #endregion + + private Color _quoteset_override_color = BTSColors.Quoteset.quoteset_override; + [System.ComponentModel.Category("Display")] + [System.ComponentModel.DisplayName("Edge Surface Override color")] + public Color quoteset_override_color + { + get { return _quoteset_override_color.IsEmpty ? (Color) BTSColors.Quoteset.quoteset_override : _quoteset_override_color; } + set { _quoteset_override_color = value.IsEmpty ? (Color) BTSColors.Quoteset.quoteset_override : value; } + } + } +} \ No newline at end of file diff --git a/src/client/spark/NMSheets/Settings/NMSheetSettingStatusBar.cs b/src/client/spark/NMSheets/Settings/NMSheetSettingStatusBar.cs new file mode 100644 index 000000000..aa30d8658 --- /dev/null +++ b/src/client/spark/NMSheets/Settings/NMSheetSettingStatusBar.cs @@ -0,0 +1,51 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace BCG +{ + [Serializable] + public class NMSheetSettingStatusBar + { + #region Main + + private bool _show_statusbar = true; + [System.ComponentModel.Category("Main")] + [System.ComponentModel.DisplayName("Show Status Bar at the bottom (Restart required)")] + public bool show_statusbar + { + get { return _show_statusbar; } + set { _show_statusbar = value; } + } + + #endregion + + #region Market Data + + private bool _show_market_data = false; + [System.ComponentModel.Category("Market Data")] + [System.ComponentModel.DisplayName("Show Market Data")] + public bool show_market_data + { + get { return _show_market_data; } + set { _show_market_data = value; } + } + + #endregion + + #region Quoter Data + + private bool _show_quote_data = false; + [System.ComponentModel.Category("Quoter Data")] + [System.ComponentModel.DisplayName("Show Quoter Data")] + public bool show_quote_data + { + get { return _show_quote_data; } + set { _show_quote_data = value; } + } + + #endregion + } +} diff --git a/src/client/spark/NMSheets/Settings/NMSheetSettingUtilities.cs b/src/client/spark/NMSheets/Settings/NMSheetSettingUtilities.cs new file mode 100644 index 000000000..c2c374754 --- /dev/null +++ b/src/client/spark/NMSheets/Settings/NMSheetSettingUtilities.cs @@ -0,0 +1,76 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Drawing; + + +namespace BCG +{ + public class NMSheetSettingUtilities + { + public static NMSheetColumnConfiguration get_col_conf(NMSheetSettings settings, NMSheetColumnName col_name) + { + foreach (NMSheetColumnConfiguration col_conf in settings.setting_column_organization.column_configuration_list) + if (col_conf.column_name == col_name) + return col_conf; + return null; + } + + public static bool is_visible(NMSheetSettings settings, NMSheetColumnName col_name) + { + NMSheetColumnConfiguration col_conf = get_col_conf(settings, col_name); + return col_conf != null ? col_conf.is_visibile : false; + } + + public static int no_of_visible_cols(NMSheetSettings settings, params NMSheetColumnName[] col_names) + { + int rv = 0; + foreach (NMSheetColumnName c in col_names) + if (is_visible(settings, c)) + rv++; + return rv; + } + + public static void set_visibility_state(NMSheetSettings settings, bool is_visible, params NMSheetColumnName[] col_name_list) + { + foreach (NMSheetColumnName col_name in col_name_list) + { + NMSheetColumnConfiguration col_conf = get_col_conf(settings, col_name); + if (col_conf != null) + col_conf.is_visibile = is_visible; + } + } + + public static NMSheetSettings change_font_size(NMSheetSettings settings, float size_change, float floor, float ceil) + { + NMSheetSettings rv = settings.Clone() as NMSheetSettings; + foreach (NMSheetColumnConfiguration col in rv.setting_column_organization.column_configuration_list) + { + Font orig_font = col.font; + Font new_font = CommonGUIUtilities.change_font_size(orig_font, size_change, floor, ceil); + if (orig_font.Size == new_font.Size) + /// this will only happen if the ceil or floor prevented + /// a font from changing size. In that case we wont + /// change the font size for anything. + return settings; + col.font = new_font; + } + return rv; + } + + private static List _copy_col_order(List col_conf_list, TheoGridColumnOrder old_col_order) + { + List rv = new List(col_conf_list); + Dictionary column_position_map = TheoGridColumnOrder.get_column_position_map(old_col_order); + foreach (NMSheetColumnConfiguration col_conf in col_conf_list) + { + int col_position = 0; + if (column_position_map.TryGetValue(col_conf.column_name, out col_position)) + rv[col_position] = col_conf; + } + return rv; + } + } +} diff --git a/src/client/spark/NMSheets/Settings/NMSheetSettings.cs b/src/client/spark/NMSheets/Settings/NMSheetSettings.cs new file mode 100644 index 000000000..f0a36101d --- /dev/null +++ b/src/client/spark/NMSheets/Settings/NMSheetSettings.cs @@ -0,0 +1,76 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Drawing; + +namespace BCG +{ + [Serializable] + public class NMSheetSettings : ICloneable + { + public List setting_option_list = new List(); + public List setting_unselected_expirations = new List(); + public List setting_unselected_strikes = new List(); + public NMSheetSettingColumnOrganization setting_column_organization = new NMSheetSettingColumnOrganization(); + public NMSheetSettingExpirationHeader setting_expiration_header = new NMSheetSettingExpirationHeader(); + public NMSheetSettingGridInternal setting_grid_internal = new NMSheetSettingGridInternal(); + public NMSheetSettingDriver setting_driver = new NMSheetSettingDriver(); + public NMSheetSettingAlert setting_alerts = new NMSheetSettingAlert(); + public NMSheetSettingATM setting_atm = new NMSheetSettingATM(); + public NMSheetSettingLayout setting_layout = new NMSheetSettingLayout(); + public NMSheetSettingsQuoting setting_quoter = new NMSheetSettingsQuoting(); + public NMSheetSettingStrikeNavigator setting_strike_navigator = new NMSheetSettingStrikeNavigator(); + public NMSheetSettingStatusBar setting_status_bar = new NMSheetSettingStatusBar(); + public NMSheetSettingMouse setting_mouse = new NMSheetSettingMouse(); + public NMSheetSettingQuoteset setting_quoteset = new NMSheetSettingQuoteset(); + public NMSheetSettingFilter setting_filter = new NMSheetSettingFilter(); + public NMSheetSettingColumnOrganization setting_export_data_column_organization = new NMSheetSettingColumnOrganization(); + + public NMSheetSettings() { } + + public object Clone() { return CommonGUIUtilities.basic_deep_clone(this); } + + public static void handle_bad_data(NMSheetSettings settings) + { + IDictionary complete_col_map = (new NMSheetSettingColumnOrganization()).get_mapped_col_data(), + this_col_map = settings.setting_column_organization.get_mapped_col_data(); + foreach (NMSheetColumnConfiguration conf in complete_col_map.Values) + if (!this_col_map.ContainsKey(conf.column_name)) + { + conf.is_visibile = false; + settings.setting_column_organization.column_configuration_list.Add(conf); + } + settings.setting_quoter = settings.setting_quoter ?? new NMSheetSettingsQuoting(); + settings.setting_status_bar = settings.setting_status_bar ?? new NMSheetSettingStatusBar(); + settings.setting_mouse = settings.setting_mouse ?? new NMSheetSettingMouse(); + settings.setting_quoteset = settings.setting_quoteset ?? new NMSheetSettingQuoteset(); + settings.setting_filter = settings.setting_filter ?? new NMSheetSettingFilter(); + settings.setting_export_data_column_organization = settings.setting_export_data_column_organization ?? CommonGUIUtilities.basic_deep_clone(settings.setting_column_organization); + NMSheetSettingsQuoting.fill_missing_data(settings.setting_quoter); + } + + public void set_col_visibility(bool is_visible, IEnumerable cols) + { + foreach (NMSheetColumnName c in cols) + { + NMSheetColumnConfiguration col_conf = get_column_conf(c); + if (col_conf != null) + col_conf.is_visibile = is_visible; + } + } + + public NMSheetColumnConfiguration get_column_conf(NMSheetColumnName col_name) + { + IDictionary map = setting_column_organization.get_mapped_col_data(); + NMSheetColumnConfiguration col_conf = null; + return map.TryGetValue(col_name, out col_conf) ? col_conf : null; + } + + public IEnumerable get_visible_columns() + { + return setting_column_organization.column_configuration_list.Where(col => col.is_visibile); + } + } +} diff --git a/src/client/spark/NMSheets/Settings/NMSheetSettingsForm.Designer.cs b/src/client/spark/NMSheets/Settings/NMSheetSettingsForm.Designer.cs new file mode 100644 index 000000000..c917ab32a --- /dev/null +++ b/src/client/spark/NMSheets/Settings/NMSheetSettingsForm.Designer.cs @@ -0,0 +1,150 @@ +namespace BCG +{ + partial class NMSheetSettingsForm + { + /// + /// 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 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._treeview_setting_list = new System.Windows.Forms.TreeView(); + this._button_ok = new System.Windows.Forms.Button(); + this._button_cancel = new System.Windows.Forms.Button(); + this._panel_setting_data = new System.Windows.Forms.Panel(); + this._button_apply = new System.Windows.Forms.Button(); + this._button_load_settings = new System.Windows.Forms.Button(); + this._button_save_settings = new System.Windows.Forms.Button(); + this.SuspendLayout(); + // + // _treeview_setting_list + // + this._treeview_setting_list.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) + | System.Windows.Forms.AnchorStyles.Left))); + this._treeview_setting_list.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; + this._treeview_setting_list.ItemHeight = 18; + this._treeview_setting_list.Location = new System.Drawing.Point(12, 12); + this._treeview_setting_list.Name = "_treeview_setting_list"; + this._treeview_setting_list.ShowLines = false; + this._treeview_setting_list.ShowNodeToolTips = true; + this._treeview_setting_list.Size = new System.Drawing.Size(249, 494); + this._treeview_setting_list.TabIndex = 0; + // + // _button_ok + // + this._button_ok.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); + this._button_ok.FlatStyle = System.Windows.Forms.FlatStyle.Flat; + this._button_ok.Location = new System.Drawing.Point(570, 515); + this._button_ok.Name = "_button_ok"; + this._button_ok.Size = new System.Drawing.Size(65, 24); + this._button_ok.TabIndex = 1; + this._button_ok.Text = "OK"; + this._button_ok.UseVisualStyleBackColor = true; + // + // _button_cancel + // + this._button_cancel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); + this._button_cancel.FlatStyle = System.Windows.Forms.FlatStyle.Flat; + this._button_cancel.Location = new System.Drawing.Point(641, 515); + this._button_cancel.Name = "_button_cancel"; + this._button_cancel.Size = new System.Drawing.Size(65, 24); + this._button_cancel.TabIndex = 2; + this._button_cancel.Text = "Cancel"; + this._button_cancel.UseVisualStyleBackColor = true; + // + // _panel_setting_data + // + this._panel_setting_data.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) + | System.Windows.Forms.AnchorStyles.Left) + | System.Windows.Forms.AnchorStyles.Right))); + this._panel_setting_data.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; + this._panel_setting_data.Location = new System.Drawing.Point(278, 12); + this._panel_setting_data.Name = "_panel_setting_data"; + this._panel_setting_data.Size = new System.Drawing.Size(426, 494); + this._panel_setting_data.TabIndex = 3; + // + // _button_apply + // + this._button_apply.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); + this._button_apply.FlatStyle = System.Windows.Forms.FlatStyle.Flat; + this._button_apply.Location = new System.Drawing.Point(499, 515); + this._button_apply.Name = "_button_apply"; + this._button_apply.Size = new System.Drawing.Size(65, 24); + this._button_apply.TabIndex = 4; + this._button_apply.Text = "Apply"; + this._button_apply.UseVisualStyleBackColor = true; + // + // _button_load_settings + // + this._button_load_settings.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); + this._button_load_settings.FlatStyle = System.Windows.Forms.FlatStyle.Flat; + this._button_load_settings.Location = new System.Drawing.Point(12, 515); + this._button_load_settings.Name = "_button_load_settings"; + this._button_load_settings.Size = new System.Drawing.Size(120, 24); + this._button_load_settings.TabIndex = 6; + this._button_load_settings.Text = "Load Settings"; + this._button_load_settings.UseVisualStyleBackColor = true; + // + // _button_save_settings + // + this._button_save_settings.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); + this._button_save_settings.FlatStyle = System.Windows.Forms.FlatStyle.Flat; + this._button_save_settings.Location = new System.Drawing.Point(141, 515); + this._button_save_settings.Name = "_button_save_settings"; + this._button_save_settings.Size = new System.Drawing.Size(120, 24); + this._button_save_settings.TabIndex = 7; + this._button_save_settings.Text = "Save Settings"; + this._button_save_settings.UseVisualStyleBackColor = true; + // + // NMSheetSettingsForm + // + this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(716, 550); + this.Controls.Add(this._button_save_settings); + this.Controls.Add(this._button_load_settings); + this.Controls.Add(this._button_apply); + this.Controls.Add(this._panel_setting_data); + this.Controls.Add(this._button_cancel); + this.Controls.Add(this._button_ok); + this.Controls.Add(this._treeview_setting_list); + this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.SizableToolWindow; + this.Name = "NMSheetSettingsForm"; + this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Hide; + this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; + this.Text = "Sheet Settings"; + this.ResumeLayout(false); + + } + + #endregion + + private System.Windows.Forms.TreeView _treeview_setting_list; + private System.Windows.Forms.Button _button_ok; + private System.Windows.Forms.Button _button_cancel; + private System.Windows.Forms.Panel _panel_setting_data; + private System.Windows.Forms.Button _button_apply; + private System.Windows.Forms.Button _button_load_settings; + private System.Windows.Forms.Button _button_save_settings; + } +} \ No newline at end of file diff --git a/src/client/spark/NMSheets/Settings/NMSheetSettingsForm.cs b/src/client/spark/NMSheets/Settings/NMSheetSettingsForm.cs new file mode 100644 index 000000000..f1e043114 --- /dev/null +++ b/src/client/spark/NMSheets/Settings/NMSheetSettingsForm.cs @@ -0,0 +1,204 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; +using System.Text.Json; + +using mbts.ui.dpi; + +namespace BCG { + public partial class NMSheetSettingsForm : Form { + private NMSheetSettingsForm() { + InitializeComponent(); + _treeview_setting_list.ItemHeight = _treeview_setting_list.ItemHeight.MultipliedByDPIRatio(); + } + + private List _symbol_list; + private NMSheetSettings _settings; + private mbts.spark.SystemContractData _contract_data; + private Action _cb; + private NMSheetSettingCheckboxListControl _checkbox_list_exps, _checkbox_list_strikes; + private NMSheetSettingColumnOrderControl _column_order_control, _column_order_data_import_control; + private readonly ThreadedBlackboard _tbb; + + public NMSheetSettingsForm(NMSheetSettings settings, List symbol_list, mbts.spark.SystemContractData contract_data, Action cb, ThreadedBlackboard tbb) + : this() { + _symbol_list = symbol_list; + _contract_data = contract_data; + _cb = cb; + _tbb = tbb; + _assign_events(); + _set_settings(settings); + } + + public void go_to_column(NMSheetColumnName col_name) { + string display_name = NMSheetColumnDisplayHelper.get_column_display_string(col_name); + List nodes = new List(); + _find_treenode(_treeview_setting_list.Nodes, display_name, nodes); + if (nodes.Count == 1) { + _treeview_setting_list.SelectedNode = nodes[0]; + _on_treenode_click(this, new TreeNodeMouseClickEventArgs(nodes[0], System.Windows.Forms.MouseButtons.Left, 0, 0, 0)); + } + } + + private static void _find_treenode(TreeNodeCollection nodes, string text, List out_val) { + foreach (TreeNode node in nodes) { + if (String.Compare(node.Text, text) == 0) + out_val.Add(node); + _find_treenode(node.Nodes, text, out_val); + } + } + + private void _set_settings(NMSheetSettings new_settings) { + _settings = new_settings; + _set_expiration_list_control(); + _set_strike_selection_control(); + _construct_tree(); + _on_treenode_click(this, new TreeNodeMouseClickEventArgs(_treeview_setting_list.Nodes[0], System.Windows.Forms.MouseButtons.Left, 0, 0, 0)); + } + + private void _set_expiration_list_control() { + List all_exps = new List(), selected_exps = new List(); + foreach (NMSheetSymbol s in _symbol_list) + foreach (DateTime exp in _contract_data.get_option_expirations_with_strikes(s.option_name, false)) + all_exps.Add(new NMSheetExpiration(s, exp)); + all_exps.Sort(); + foreach (NMSheetExpiration selected_exp in _settings.setting_unselected_expirations) + selected_exps.Add(selected_exp); + _checkbox_list_exps = new NMSheetSettingCheckboxListControl(all_exps, selected_exps); + } + + private void _set_strike_selection_control() { + SortedDictionary all_strikes = new SortedDictionary(); + foreach (NMSheetSymbol s in _symbol_list) + foreach (double k in _contract_data.get_all_option_strikes(s.option_name)) + all_strikes[k] = true; + _checkbox_list_strikes = new NMSheetSettingCheckboxListControl(all_strikes.Keys, _settings.setting_unselected_strikes); + } + + private void _assign_events() { + _button_cancel.Click += (s, e) => { Close(); }; + _button_apply.Click += (s, e) => { _send_settings_out(); }; + _button_ok.Click += (s, e) => { + _send_settings_out(); + Close(); + }; + _button_save_settings.Click += (s, e) => { + try { + SaveFileDialog diag = new SaveFileDialog(); + if (diag.ShowDialog(this) == System.Windows.Forms.DialogResult.OK) { + // System.IO.FileStream str = new System.IO.FileStream(diag.FileName, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.ReadWrite); + // System.Runtime.Serialization.Formatters.Binary.BinaryFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); + // formatter.Serialize(str, _settings); + // str.Close(); + string json_txt = JsonSerializer.Serialize(_settings); + System.IO.File.WriteAllText(diag.FileName, json_txt); + } + } catch (Exception ex) { MessageBox.Show(String.Format("Could not save settings\n{0}", ex.Message), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } + }; + _button_load_settings.Click += (s, e) => { + try { + System.Windows.Forms.OpenFileDialog diag = new System.Windows.Forms.OpenFileDialog(); + diag.Multiselect = false; + if (diag.ShowDialog() == System.Windows.Forms.DialogResult.OK) { + // System.IO.FileStream str = new System.IO.FileStream(diag.FileName, System.IO.FileMode.Open); + // System.Runtime.Serialization.Formatters.Binary.BinaryFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); + // NMSheetSettings new_settings = formatter.Deserialize(str) as NMSheetSettings; + string json_txt = System.IO.File.ReadAllText(diag.FileName); + NMSheetSettings new_settings = JsonSerializer.Deserialize(json_txt); + NMSheetSettings.handle_bad_data(new_settings); + new_settings.setting_option_list = _settings.setting_option_list; + new_settings.setting_quoter = _settings.setting_quoter; + _set_settings(new_settings); + } + } catch (Exception ex) { MessageBox.Show(String.Format("Could not load settings\n{0}", ex.Message), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } + }; + _treeview_setting_list.NodeMouseClick += _on_treenode_click; + } + + private void _send_settings_out() { + _settings.setting_unselected_expirations.Clear(); + foreach (object o in _checkbox_list_exps.get_unselected_items()) + _settings.setting_unselected_expirations.Add((NMSheetExpiration)o); + _settings.setting_unselected_strikes.Clear(); + foreach (object o in _checkbox_list_strikes.get_unselected_items()) + _settings.setting_unselected_strikes.Add((double)o); + if (_cb != null) + _cb(_settings.Clone() as NMSheetSettings); + } + + void _on_treenode_click(object sender, TreeNodeMouseClickEventArgs e) { + if (e.Node.Tag != null) { + _panel_setting_data.Controls.Clear(); + PropertyGrid grid = new PropertyGrid() { Dock = DockStyle.Fill, SelectedObject = e.Node.Tag }; + _panel_setting_data.Controls.Add(grid); + } else if (e.Node.Text == "Expirations") { + _panel_setting_data.Controls.Clear(); + _checkbox_list_exps.Dock = DockStyle.Fill; + _panel_setting_data.Controls.Add(_checkbox_list_exps); + } else if (e.Node.Text == "Strikes") { + _panel_setting_data.Controls.Clear(); + _checkbox_list_strikes.Dock = DockStyle.Fill; + _panel_setting_data.Controls.Add(_checkbox_list_strikes); + } else if (e.Node.Text == "Column Ordering") { + _panel_setting_data.Controls.Clear(); + _column_order_control = new NMSheetSettingColumnOrderControl(_settings, true); + _column_order_control.Dock = DockStyle.Fill; + _panel_setting_data.Controls.Add(_column_order_control); + } else if (e.Node.Text == "Data Export") { + _panel_setting_data.Controls.Clear(); + _column_order_data_import_control = new NMSheetSettingColumnOrderControl(_settings, false); + _column_order_data_import_control.Dock = DockStyle.Fill; + _panel_setting_data.Controls.Add(_column_order_data_import_control); + } + } + + private void _construct_tree() { + _treeview_setting_list.Nodes.Clear(); + _treeview_setting_list.Nodes.Add(new TreeNode("Expirations", new TreeNode[] { })); + _treeview_setting_list.Nodes.Add(new TreeNode("Strikes", new TreeNode[] { })); + _add_column_nested_nodes(); + _treeview_setting_list.Nodes.Add(new TreeNode("Sheet Layout") { Tag = _settings.setting_layout }); + _treeview_setting_list.Nodes.Add(new TreeNode("Mouse Handling") { Tag = _settings.setting_mouse }); + _treeview_setting_list.Nodes.Add(new TreeNode("StatusBar Layout") { Tag = _settings.setting_status_bar }); + _treeview_setting_list.Nodes.Add(new TreeNode("Column Ordering")); + _treeview_setting_list.Nodes.Add(new TreeNode("Alerts") { Tag = _settings.setting_alerts }); + _treeview_setting_list.Nodes.Add(new TreeNode("ATM") { Tag = _settings.setting_atm }); + _treeview_setting_list.Nodes.Add(new TreeNode("Driver") { Tag = _settings.setting_driver }); + _treeview_setting_list.Nodes.Add(new TreeNode("Strike Navigator") { Tag = _settings.setting_strike_navigator }); + _treeview_setting_list.Nodes.Add(new TreeNode("Grid") { Tag = _settings.setting_grid_internal }); + _treeview_setting_list.Nodes.Add(new TreeNode("Expiration Header") { Tag = _settings.setting_expiration_header }); + if (_settings.setting_quoter.is_quoter_enabled()) + _treeview_setting_list.Nodes.Add(new TreeNode("Quoting") { Tag = _settings.setting_quoter }); + _treeview_setting_list.Nodes.Add(new TreeNode("Edge Surface") { Tag = _settings.setting_quoteset }); + _treeview_setting_list.Nodes.Add(new TreeNode("Data Export")); + } + + + private void _add_column_nested_nodes() { + List col_type_node_list = new List(); + foreach (NMSheetColumnType col_type in Enum.GetValues(typeof(NMSheetColumnType))) { + List col_node_list = new List(); + foreach (NMSheetColumnName col_enum in NMSheetSettingColumnOrganization.get_cols_for_type(col_type)) { + string display_name = NMSheetColumnDisplayHelper.get_column_display_string(col_enum); + col_node_list.Add(new TreeNode(display_name) { Tag = _get_column_configuration(col_enum) }); + } + col_node_list.Sort((t1, t2) => { return t1.Text.CompareTo(t2.Text); }); + col_type_node_list.Add(new TreeNode(NMSheetColumnDisplayHelper.get_columntype_display_string(col_type), col_node_list.ToArray())); + } + _treeview_setting_list.Nodes.Add(new TreeNode("Display Parameters", col_type_node_list.ToArray())); + } + + private NMSheetColumnConfiguration _get_column_configuration(NMSheetColumnName col_name) { + foreach (NMSheetColumnConfiguration c in _settings.setting_column_organization.column_configuration_list) + if (c.column_name == col_name) + return c; + return null; + } + } +} diff --git a/src/client/spark/NMSheets/Settings/NMSheetSettingsForm.resx b/src/client/spark/NMSheets/Settings/NMSheetSettingsForm.resx new file mode 100644 index 000000000..1af7de150 --- /dev/null +++ b/src/client/spark/NMSheets/Settings/NMSheetSettingsForm.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/NMSheets/Settings/NMSheetSettingsQuoting.cs b/src/client/spark/NMSheets/Settings/NMSheetSettingsQuoting.cs new file mode 100644 index 000000000..70d4622a8 --- /dev/null +++ b/src/client/spark/NMSheets/Settings/NMSheetSettingsQuoting.cs @@ -0,0 +1,140 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Drawing; +using System.ComponentModel; +using mbts.ui; + +namespace BCG +{ + [Serializable] + public class NMSheetSettingsQuoting + { + private readonly Nullable _quoter_id = null; + + #region Display + + private Color _quoter_security_on_color = BTSColors.Quoter.quoting_security_on; + [System.ComponentModel.Category("Display")] + [System.ComponentModel.DisplayName("Quoter Security ON color")] + [Description("This is the color for a that is switched on.")] + public Color quoter_security_on_color + { + get { return _quoter_security_on_color; } + set { _quoter_security_on_color = value; } + } + + private Color _quoter_security_streaming_color = BTSColors.Quoter.quoting_security_streaming; + [System.ComponentModel.Category("Display")] + [System.ComponentModel.DisplayName("Quoter Security Streaming color")] + [Description("This is the color for a security that is being streamed.")] + public Color quoter_security_streaming_color + { + get { return _quoter_security_streaming_color; } + set { _quoter_security_streaming_color = value; } + } + + private Color _quoter_security_streaming_on_bbo_color = BTSColors.Quoter.quoting_security_on_bbo; + [System.ComponentModel.Category("Display")] + [System.ComponentModel.DisplayName("Quoter Security Streaming on BBO color")] + [Description("This is the color for a security that is being streamed at the top of the book.")] + public Color quoter_security_streaming_on_bbo_color + { + get { return _quoter_security_streaming_on_bbo_color; } + set { _quoter_security_streaming_on_bbo_color = value; } + } + + private Color _quoteset_override_color = BTSColors.Quoteset.quoteset_override; + [System.ComponentModel.Category("Display")] + [System.ComponentModel.DisplayName("Edge Surface Override color")] + [Browsable(false)] + public Color quoteset_override_color + { + get { return _quoteset_override_color; } + set { _quoteset_override_color = value; } + } + #endregion + + #region Pump Fades + + private string _preconfigured_pumpfades = "0.05, 0.10, 0.15, 0.2"; + [System.ComponentModel.Category("Pumps/Fades")] + [System.ComponentModel.DisplayName("Preconfigured Pump/Fade")] + [Browsable (false)] + public string preconfigured_pumpfades + { + get { return _preconfigured_pumpfades; } + set { _preconfigured_pumpfades = value; } + } + + #endregion + + #region Edges/Sizes + + private string _preconfigured_edges = "0.25, 0.30, 0.35, 0.40, 0.45, 0.50, 1.0"; + [System.ComponentModel.Category("Edges/Sizes")] + [System.ComponentModel.DisplayName("Preconfigured Edges")] + [Browsable(false)] + public string preconfigured_edges + { + get { return _preconfigured_edges; } + set { _preconfigured_edges = value; } + } + + + private string _preconfigured_edge_shifts = "-0.10, -0.05, 0.05, 0.10, 0.25"; + [System.ComponentModel.Category("Edges/Sizes")] + [System.ComponentModel.DisplayName("Preconfigured Edge Shifts")] + [Browsable(false)] + public string preconfigured_edge_shifts + { + get { return _preconfigured_edge_shifts; } + set { _preconfigured_edge_shifts = value; } + } + + private string _preconfigured_sizes = "1, 5, 10, 20, 25, 50, 100"; + [System.ComponentModel.Category("Edges/Sizes")] + [System.ComponentModel.DisplayName("Preconfigured Sizes")] + [Browsable(false)] + public string preconfigured_sizes + { + get { return _preconfigured_sizes; } + set { _preconfigured_sizes = value; } + } + + #endregion + + public NMSheetSettingsQuoting() { } + + public NMSheetSettingsQuoting(uint quoter_id) { _quoter_id = quoter_id; } + + public static void fill_missing_data (NMSheetSettingsQuoting quoting_settings) + { + NMSheetSettingsQuoting def = new NMSheetSettingsQuoting (); + if (quoting_settings._quoter_security_on_color == Color.Empty) + quoting_settings._quoter_security_on_color = def._quoter_security_on_color; + if (quoting_settings._quoter_security_streaming_color == Color.Empty) + quoting_settings._quoter_security_streaming_color = def._quoter_security_streaming_color; + if (quoting_settings._quoter_security_streaming_on_bbo_color == Color.Empty) + quoting_settings._quoter_security_streaming_on_bbo_color = def._quoter_security_streaming_on_bbo_color; + } + + public bool get_quoter_id(out uint quoter_id) + { + if (_quoter_id.HasValue) + { + quoter_id = _quoter_id.Value; + return true; + } + else + { + quoter_id = 0; + return false; + } + } + + public bool is_quoter_enabled() { return _quoter_id.HasValue; } + } +} diff --git a/src/client/spark/NMSheets/UIComponents/ExpirationHeaderControl/NMSheetExpirationHeaderControlStrip.Designer.cs b/src/client/spark/NMSheets/UIComponents/ExpirationHeaderControl/NMSheetExpirationHeaderControlStrip.Designer.cs new file mode 100644 index 000000000..8a2bfcbc8 --- /dev/null +++ b/src/client/spark/NMSheets/UIComponents/ExpirationHeaderControl/NMSheetExpirationHeaderControlStrip.Designer.cs @@ -0,0 +1,47 @@ +namespace BCG +{ + partial class NMSheetExpirationHeaderControlStrip + { + /// + /// 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)) + { + _logical_dispose(disposing); + 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(); + // + // ExpirationHeader + // + this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(224)))), ((int)(((byte)(224)))), ((int)(((byte)(224))))); + this.Name = "ExpirationHeader"; + this.Size = new System.Drawing.Size(632, 23); + this.ResumeLayout(false); + + } + + #endregion + } +} diff --git a/src/client/spark/NMSheets/UIComponents/ExpirationHeaderControl/NMSheetExpirationHeaderControlStrip.cs b/src/client/spark/NMSheets/UIComponents/ExpirationHeaderControl/NMSheetExpirationHeaderControlStrip.cs new file mode 100644 index 000000000..44f6a9a64 --- /dev/null +++ b/src/client/spark/NMSheets/UIComponents/ExpirationHeaderControl/NMSheetExpirationHeaderControlStrip.cs @@ -0,0 +1,161 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Drawing; +using System.Data; +using System.Text; +using System.Windows.Forms; +using BCG.Utilities; +using BCG.Utilities.General; + +namespace BCG +{ + /// Sits on top of the option sheets (below menu panel) + /// Contains OptionSheetSingleVolControl for each + /// option expiration. + /// External inputs are + /// 1. NMSheet Settings + /// a. strictly to get the ui properties + /// 2. NMSheetViewableAreaTag + /// a. to allign the control with the grid + /// 3. set_header_data + /// a. To add remove controls, since the control list + /// should corresponds to the expiration list in the theos + public partial class NMSheetExpirationHeaderControlStrip : UserControl + { + private SortedList _vol_controls = new SortedList(); + private readonly object _in_bb_nmsheet_viewable_area_tag, _in_bb_nmsheet_settings_tag; + private readonly object _out_bb_vol_shift_tag; + private ThreadedBlackboard _threaded_bb; + private Action _scroll_to_atm_cb; + private IDictionary _header_data; + private BCG.Utilities.General.HighPerformanceTimer _timer = new HighPerformanceTimer(); + private NMSheetExpirationHeaderControlStrip() { InitializeComponent(); } + private PerfStatsLogger _logger = new PerfStatsLogger(); + private readonly string _log_id; + + public NMSheetExpirationHeaderControlStrip(object req_id, ThreadedBlackboard threaded_bb, Action scroll_to_atm_cb) + { + _log_id = String.Format("NMSheetExpirationHeaderControlStrip_{0}", req_id); + BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; + BackColor = Color.Transparent; + _in_bb_nmsheet_settings_tag = new NMSheetTags.NMSheetSettingsTag(req_id); + _in_bb_nmsheet_viewable_area_tag = new NMSheetTags.NMSheetViewableAreaTag(req_id); + _out_bb_vol_shift_tag = new NMSheetTags.NMSheetVolShiftTag(req_id); + _threaded_bb = threaded_bb; + _scroll_to_atm_cb = scroll_to_atm_cb; + _threaded_bb.data_callback += _react_to_bb; + _threaded_bb.add_to_subscription_list(_in_bb_nmsheet_viewable_area_tag, _in_bb_nmsheet_settings_tag); + } + + private void _react_to_bb(object tag, object value) + { + if (_in_bb_nmsheet_viewable_area_tag.Equals(tag)) + _reallign_controls(this, _vol_controls.Values, _threaded_bb.sec_thread_retrieve_from_cache(_in_bb_nmsheet_viewable_area_tag) as double[]); + else if (_in_bb_nmsheet_settings_tag.Equals(tag)) + _handle_setting_changes(); + } + + private void _handle_setting_changes() + { + NMSheetSettings settings = (NMSheetSettings)_threaded_bb.sec_thread_retrieve_from_cache(_in_bb_nmsheet_settings_tag) ?? new NMSheetSettings(); + _set_ui_properties(_vol_controls.Values, settings); + } + + public void set_header_data(IDictionary header_data) + { + _timer.start(); + _header_data = header_data; + NMSheetSettings settings = (NMSheetSettings)_threaded_bb.sec_thread_retrieve_from_cache(_in_bb_nmsheet_settings_tag) ?? new NMSheetSettings(); + bool control_list_modified = false; + foreach (KeyValuePair p in _header_data) + { + NMSheetExpiration nmsheet_exp = p.Key; + ATMData nmsheet_exp_atmdata = p.Value; + NMSheetSingleExpirationHeaderControl nmsheet_exp_header; + if (!_vol_controls.TryGetValue(nmsheet_exp, out nmsheet_exp_header)) + { + nmsheet_exp_header = new NMSheetSingleExpirationHeaderControl(nmsheet_exp, settings, () => { _publish_vol_shift_data(); }, + (clicked_nmsheet_exp) => { _scroll_to_atm_event(clicked_nmsheet_exp); }); + nmsheet_exp_header.Tag = nmsheet_exp; + nmsheet_exp_header.BackColor = Color.Transparent; + _vol_controls.Add(nmsheet_exp, nmsheet_exp_header); + Controls.Add(nmsheet_exp_header); + control_list_modified = true; + } + nmsheet_exp_header.set_atm_data(nmsheet_exp_atmdata); + } + foreach (NMSheetExpiration nmsheet_exp in new List(_vol_controls.Keys)) + { + if (!_header_data.ContainsKey(nmsheet_exp)) + { + NMSheetSingleExpirationHeaderControl c = _vol_controls[nmsheet_exp]; + c.Dispose(); + Controls.Remove(c); + _vol_controls.Remove(nmsheet_exp); + control_list_modified = true; + } + } + if (control_list_modified) + { + _reallign_controls(this, _vol_controls.Values, _threaded_bb.sec_thread_retrieve_from_cache(_in_bb_nmsheet_viewable_area_tag) as double[]); + _publish_vol_shift_data(); + } + _timer.stop(); + _logger.log(_log_id, "NMSheetExpirationHeaderControlStrip.set_header_data", _timer.lastIntervalTime); + } + + private void _scroll_to_atm_event(NMSheetExpiration nmsheet_exp) { _scroll_to_atm_cb(nmsheet_exp); } + + private void _publish_vol_shift_data() + { + Dictionary volshift_map = new Dictionary(); + foreach (KeyValuePair p in _vol_controls) + volshift_map[p.Key] = p.Value.get_vol_shift(); + _threaded_bb.sec_thread_write(_out_bb_vol_shift_tag, volshift_map); + } + + #region Stateless helpers + private static void _reallign_controls(Control container_control, IEnumerable header_control, double[] grid_coords) + { + int control_height = 0; + if (grid_coords != null && grid_coords.Length > 0) + { + int expiration_width = Convert.ToInt32(grid_coords[4]); + int total_width = Convert.ToInt32(grid_coords[5]); + int cell_start = -1 * Convert.ToInt32(Convert.ToDouble(total_width) * grid_coords[0]); + foreach (NMSheetSingleExpirationHeaderControl exp_header in header_control) + { + exp_header.Visible = true; + exp_header.Top = 1; + exp_header.Left = cell_start + (expiration_width - exp_header.Width) / 2; + exp_header.Visible = true; + cell_start += expiration_width; + control_height = Math.Max(control_height, exp_header.Height); + } + container_control.Height = Math.Max(container_control.Height, control_height + 2); + } + } + + private static void _set_ui_properties(IEnumerable header_control_ui_list, NMSheetSettings settings) + { + foreach (NMSheetSingleExpirationHeaderControl header_control_ui in header_control_ui_list) + header_control_ui.set_settings(settings); + } + #endregion + + #region Disposing + private bool _is_logically_disposed = false; + private void _logical_dispose(bool disposing) + { + if (!_is_logically_disposed) + { + _is_logically_disposed = true; + _threaded_bb.data_callback -= _react_to_bb; + foreach (NMSheetSingleExpirationHeaderControl c in _vol_controls.Values) + c.Dispose(); + } + } + #endregion + } +} diff --git a/src/client/spark/NMSheets/UIComponents/ExpirationHeaderControl/NMSheetSettingStrikeNavigator.cs b/src/client/spark/NMSheets/UIComponents/ExpirationHeaderControl/NMSheetSettingStrikeNavigator.cs new file mode 100644 index 000000000..3faa30761 --- /dev/null +++ b/src/client/spark/NMSheets/UIComponents/ExpirationHeaderControl/NMSheetSettingStrikeNavigator.cs @@ -0,0 +1,34 @@ +using System; +using System.Collections.Generic; +using System.Drawing; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using mbts.ui; + +namespace BCG +{ + [Serializable] + public class NMSheetSettingStrikeNavigator + { + public NMSheetSettingStrikeNavigator() + { + visible_strike_range_foreground = BTSColors.Security.default_text; + visible_strike_range_background = BTSColors.Security.visible_strike_range_background; + } + + [System.ComponentModel.DisplayName("Visible Strike Range Foreground")] + public Color visible_strike_range_foreground { get; set; } + + [System.ComponentModel.DisplayName("Visible Strike Range Background")] + public Color visible_strike_range_background { get; set; } + + private Nullable _show_strike_navigator = false; + [System.ComponentModel.DisplayName("Show Strike Navigator (Restart required)")] + public bool show_strike_navigator + { + get { return _show_strike_navigator.HasValue ? _show_strike_navigator.Value : false; } + set { _show_strike_navigator = value; } + } + } +} diff --git a/src/client/spark/NMSheets/UIComponents/ExpirationHeaderControl/NMSheetSingleExpirationHeaderControl.Designer.cs b/src/client/spark/NMSheets/UIComponents/ExpirationHeaderControl/NMSheetSingleExpirationHeaderControl.Designer.cs new file mode 100644 index 000000000..b8ee06d25 --- /dev/null +++ b/src/client/spark/NMSheets/UIComponents/ExpirationHeaderControl/NMSheetSingleExpirationHeaderControl.Designer.cs @@ -0,0 +1,87 @@ +namespace BCG +{ + partial class NMSheetSingleExpirationHeaderControl + { + /// + /// 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._panel_volshift = new System.Windows.Forms.Panel(); + this._label_main_text = new System.Windows.Forms.Label(); + this._button_ATM = new System.Windows.Forms.Button(); + this.SuspendLayout(); + // + // _panel_volshift + // + this._panel_volshift.AutoSize = true; + this._panel_volshift.Location = new System.Drawing.Point(48, 4); + this._panel_volshift.Name = "_panel_volshift"; + this._panel_volshift.Size = new System.Drawing.Size(59, 20); + this._panel_volshift.TabIndex = 4; + // + // _label_main_text + // + this._label_main_text.AutoSize = true; + this._label_main_text.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this._label_main_text.Location = new System.Drawing.Point(111, 7); + this._label_main_text.Name = "_label_main_text"; + this._label_main_text.Size = new System.Drawing.Size(41, 13); + this._label_main_text.TabIndex = 5; + this._label_main_text.Tag = ""; + this._label_main_text.Text = "F R V S"; + // + // _button_ATM + // + this._button_ATM.FlatStyle = System.Windows.Forms.FlatStyle.Flat; + this._button_ATM.Location = new System.Drawing.Point(3, 4); + this._button_ATM.Name = "_button_ATM"; + this._button_ATM.Size = new System.Drawing.Size(41, 20); + this._button_ATM.TabIndex = 6; + this._button_ATM.Text = "ATM"; + this._button_ATM.UseVisualStyleBackColor = true; + // + // NMSheetSingleExpirationHeaderControl + // + this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.AutoSize = true; + this.BackColor = System.Drawing.Color.Transparent; + this.Controls.Add(this._button_ATM); + this.Controls.Add(this._label_main_text); + this.Controls.Add(this._panel_volshift); + this.Name = "NMSheetSingleExpirationHeaderControl"; + this.Size = new System.Drawing.Size(159, 27); + this.ResumeLayout(false); + this.PerformLayout(); + + } + + #endregion + + private System.Windows.Forms.Panel _panel_volshift; + private System.Windows.Forms.Label _label_main_text; + private System.Windows.Forms.Button _button_ATM; + } +} diff --git a/src/client/spark/NMSheets/UIComponents/ExpirationHeaderControl/NMSheetSingleExpirationHeaderControl.cs b/src/client/spark/NMSheets/UIComponents/ExpirationHeaderControl/NMSheetSingleExpirationHeaderControl.cs new file mode 100644 index 000000000..f77308cb0 --- /dev/null +++ b/src/client/spark/NMSheets/UIComponents/ExpirationHeaderControl/NMSheetSingleExpirationHeaderControl.cs @@ -0,0 +1,226 @@ +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.General; + +namespace BCG +{ + /// + /// Vol control at the top of each exp. Shows (in order) + /// atm_vol, vol_control, offset, fwd (driver+offset), atm_straddle + /// + public partial class NMSheetSingleExpirationHeaderControl : UserControl + { + private const int _control_spacing = 2; + private readonly NMSheetExpiration _nmsheet_expiration; + private NMSheetSettings _nmsheet_settings = null; + private ATMData _atm_data = null; + private ValueEntryGUIConfig _cached_vol_control_config; + private ITheoFormatter _theo_formatter; + private ValueEntryGUI _volshift_control; + private Action _vol_shift_cb; + private Action _atm_button_cb; + private ToolTip _main_tooltip; + private int _button_atm_default_width, _vol_shift_control_default_width; + //private readonly bool _show_vol_shift_control = true;//, _show_fwd_roll = true, _show_atm_vol = true, _show_atm_straddle = true; + + private NMSheetSingleExpirationHeaderControl() { InitializeComponent(); } + + public NMSheetSingleExpirationHeaderControl(NMSheetExpiration nmsheet_expiration, NMSheetSettings nmsheet_settings, Action vol_shift_cb, Action atm_button_cb) + : this () + { + Tag = _nmsheet_expiration = nmsheet_expiration; + _nmsheet_settings = nmsheet_settings; + _theo_formatter = new TheoFormatter(TickConverter2.TickType.tickDecimal2); + _vol_shift_cb = vol_shift_cb; + _atm_button_cb = atm_button_cb; + _init_controls(); + _resize_control(); + } + + private void _init_controls() + { + _init_tooltip(); + _init_vol_shift_control(); + _button_ATM.Click += (s, e) => { if (_atm_button_cb != null) _atm_button_cb(_nmsheet_expiration); }; + _button_atm_default_width = _button_ATM.Width; + _vol_shift_control_default_width = _volshift_control.Width; + } + + private void _init_tooltip() + { + _main_tooltip = new ToolTip(); + _main_tooltip.AutoPopDelay = 6000; + _main_tooltip.InitialDelay = 0; + _main_tooltip.ReshowDelay = 0; + // Force the ToolTip text to be displayed whether or not the form is active. + _main_tooltip.ShowAlways = true; + + // Set up the ToolTip text for the Button and Checkbox. + _main_tooltip.SetToolTip(_label_main_text, "Roll, Fwd, ATMVol, ATMStraddle"); + } + + private void _init_vol_shift_control() + { + _volshift_control = new ValueEntryGUI(); + _volshift_control.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; + _cached_vol_control_config = new ValueEntryGUIConfig(); + _volshift_control.onValueUp += (object sender, object value) => { _set_vol_shift_value(Double.Parse(value.ToString()) + _nmsheet_settings.setting_expiration_header.vol_shift_interval); }; + _volshift_control.onValueDown += (object sender, object value) => { _set_vol_shift_value(Double.Parse(value.ToString()) - _nmsheet_settings.setting_expiration_header.vol_shift_interval); }; + _volshift_control.onValueEdit += (s, e) => + { + using (TCNumPad numpad = new TCNumPad("Vol Shift", ".")) + { + if (numpad.myShowDialog() == DialogResult.OK) + { + double new_shift = 0; + try {new_shift = Double.Parse(numpad.asText);} + catch (Exception) + { + MessageBox.Show("Invalid Vol Shift", "Sheets", MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + _set_vol_shift_value(new_shift); + } + } + }; + _panel_volshift.Controls.Add(_volshift_control); + _volshift_control.Dock = DockStyle.Fill; + _set_vol_shift_value(0.0); + } + + public void set_atm_data(ATMData atm_data) + { + _atm_data = atm_data; + _paint_atm_values(_atm_data, _nmsheet_settings); + } + + public void set_settings(NMSheetSettings nmsheet_settings) + { + _nmsheet_settings = nmsheet_settings; + _paint_atm_values(_atm_data, _nmsheet_settings); + _resize_control(); + } + + public double get_vol_shift() + { + double rv = 0.0; + Double.TryParse(_volshift_control.currentValue.ToString(), out rv); + return rv; + } + + #region Painting ATM values + + private void _paint_atm_values(ATMData atm_data, NMSheetSettings nmsheet_settings) + { + /// offset and roll are also included in the straddle label + string roll_fwd_text = String.Format ("{0} {1}", _format_future(atm_data.roll_offset, nmsheet_settings), _format_future(atm_data.fwd, nmsheet_settings)), + straddle_text = String.Empty, + vol_text = String.Empty; + double straddle = Double.NaN; + foreach (double strike in atm_data.get_sorted_strikes()) + { + if (nmsheet_settings.setting_expiration_header.straddle_display_type == StraddleDisplayEnum.StraddleTheo) + { + straddle = atm_data.get_theo_straddle(strike); + _label_main_text.BackColor = Color.FromKnownColor(KnownColor.Transparent); + _label_main_text.ForeColor = Color.Black; + } + else if (nmsheet_settings.setting_expiration_header.straddle_display_type == StraddleDisplayEnum.StraddleTheoVsMarket) + { + straddle = atm_data.get_md_midpoint_straddle_minus_theo_straddle(strike); + if (straddle < 0) + { + _label_main_text.BackColor = nmsheet_settings.setting_expiration_header.straddle_theovsmarket_negative_back_color; + _label_main_text.ForeColor = nmsheet_settings.setting_expiration_header.straddle_theovsmarket_negative_font_color; + } + else + { + _label_main_text.BackColor = nmsheet_settings.setting_expiration_header.straddle_theovsmarket_positive_back_color; + _label_main_text.ForeColor = nmsheet_settings.setting_expiration_header.straddle_theovsmarket_positive_font_color; + } + } + double vol = atm_data.get_vol(strike); + straddle_text += (straddle_text == String.Empty ? String.Empty : " ") + _theo_formatter.formatTheo("call", straddle); + vol_text += (vol_text == String.Empty ? String.Empty : " ") + _theo_formatter.formatTheo("vol", vol); + } + _label_main_text.Text = String.Format("{0} {1} {2}", roll_fwd_text, vol_text, straddle_text); + } + + private static string _format_future(double value, NMSheetSettings nmsheet_settings) + { + return TickConverter2.toTick(value, nmsheet_settings.setting_driver.tick_type); + } + + #endregion + + #region Vol Shift handling + + private void _set_vol_shift_value(double shift) + { + shift = Math.Round(shift, 6); + _volshift_control.currentValue = (shift - Math.Floor(shift) == 0) ? shift.ToString("0.00") : shift.ToString(); + _paint_vol_shift_control(); + _publish_vol_shift(shift); + } + + private void _paint_vol_shift_control() + { + Double shift = Double.Parse(_volshift_control.currentValue.ToString()); + if (shift > 0) + _cached_vol_control_config.valueBColor = Color.LightGreen; + else if (shift < 0) + _cached_vol_control_config.valueBColor = Color.LightPink; + else + _cached_vol_control_config.valueBColor = Color.FromKnownColor(KnownColor.Transparent); + _cached_vol_control_config.FlipSize = new Size(5, _cached_vol_control_config.FlipSize.Height); + _cached_vol_control_config.FlipSeparation = 2; + _cached_vol_control_config.valueLPadding = 2; + _volshift_control.config = _cached_vol_control_config; + } + + private void _publish_vol_shift(double shift) + { + if (_vol_shift_cb != null) + _vol_shift_cb(); + } + + #endregion + + private void _resize_control() + { + /// button atm navigation + int next_control_pos = _control_spacing; + _button_ATM.Left = next_control_pos; + if (_nmsheet_settings.setting_expiration_header.show_atm_navigation_button) + { + _button_ATM.Enabled = _button_ATM.Visible = true; + next_control_pos = _button_ATM.Right + _control_spacing; + } + else + { + _button_ATM.Enabled = _button_ATM.Visible = false; + } + /// vol shift + _panel_volshift.Left = next_control_pos; + + if (_nmsheet_settings.setting_expiration_header.show_vol_shift_control) + { + _volshift_control.Enabled = _volshift_control.Visible = true; + _panel_volshift.Visible = true; + next_control_pos = _panel_volshift.Right + _control_spacing; + } + else + { + _volshift_control.Enabled = _volshift_control.Visible = false; + _panel_volshift.Visible = false; + } + _label_main_text.Left = next_control_pos; + } + } +} diff --git a/src/client/spark/NMSheets/UIComponents/ExpirationHeaderControl/NMSheetSingleExpirationHeaderControl.resx b/src/client/spark/NMSheets/UIComponents/ExpirationHeaderControl/NMSheetSingleExpirationHeaderControl.resx new file mode 100644 index 000000000..1af7de150 --- /dev/null +++ b/src/client/spark/NMSheets/UIComponents/ExpirationHeaderControl/NMSheetSingleExpirationHeaderControl.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/NMSheets/UIComponents/ExpirationHeaderDriverControl/NMSheetDriverControlStrip.Designer.cs b/src/client/spark/NMSheets/UIComponents/ExpirationHeaderDriverControl/NMSheetDriverControlStrip.Designer.cs new file mode 100644 index 000000000..893051b8d --- /dev/null +++ b/src/client/spark/NMSheets/UIComponents/ExpirationHeaderDriverControl/NMSheetDriverControlStrip.Designer.cs @@ -0,0 +1,47 @@ +namespace BCG +{ + partial class NMSheetDriverControlStrip + { + /// + /// 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)) + { + _threaded_bb.data_callback -= _react_to_bb; + 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(); + // + // OptionSheetDriverControlStrip + // + this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.BackColor = System.Drawing.Color.White; + this.Name = "OptionSheetDriverControlStrip"; + this.Size = new System.Drawing.Size(565, 24); + this.ResumeLayout(false); + + } + + #endregion + } +} diff --git a/src/client/spark/NMSheets/UIComponents/ExpirationHeaderDriverControl/NMSheetDriverControlStrip.cs b/src/client/spark/NMSheets/UIComponents/ExpirationHeaderDriverControl/NMSheetDriverControlStrip.cs new file mode 100644 index 000000000..aed55b77b --- /dev/null +++ b/src/client/spark/NMSheets/UIComponents/ExpirationHeaderDriverControl/NMSheetDriverControlStrip.cs @@ -0,0 +1,244 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Drawing; +using System.Data; +using System.Text; +using System.Windows.Forms; +using BCG.Utilities; +using mbts.ui.dpi; + +namespace BCG { + /// Control that sits on top (under the vol control strip). + /// For every selected option expiration, theres a driver + /// control + /// External inputs are + /// 1. NMSheet Settings (NMSheetTags.NMSheetSettingsTag) + /// This is used for + /// a. UI settings (driver tick type, interval etc) + /// b. to figure out the visible expirations to send out the theo request + /// 2. All Sec Data (AllBasicSecuritiesSource.AllBasicSecuritiesTag) + /// a. So that the expiration add/removes get reflected in the theo request + /// 3. Grid coordinates (NMSheetTags.NMSheetViewableAreaTag) + /// a. To paint the control based on where the grid is + /// 4. set_sheet_data is called directly to set the theos. + /// a. To add remove controls, since the control list + /// should corresponds to the expiration list in the theos + + public partial class NMSheetDriverControlStrip : UserControl { + private SortedList _price_controls = new SortedList(); + private double[] _grid_coords; + private NMSheetData _nmsheet_data; + + // HighDPI - multiplying Taha's magic number by the _dpi_ratio + // fixes the up/down arrows overlaping the driver price + private static readonly int _single_driver_control_width = (105).MultipliedByDPIRatio(); + private BCG.Utilities.General.HighPerformanceTimer _timer = new Utilities.General.HighPerformanceTimer(); + + private ThreadedBlackboard _threaded_bb; + private readonly object _in_bb_nmsheet_settings_tag, _in_bb_nmsheet_viewable_area_tag, _in_contract_data_tag, + _out_bb_theo_request_tag; + private readonly List _nmsheet_symbol_list; + private readonly string _log_id; + private PerfStatsLogger _logger = new PerfStatsLogger(); + + private NMSheetDriverControlStrip() { InitializeComponent(); } + + public NMSheetDriverControlStrip(object req_id, List nmsheet_symbol_list, ThreadedBlackboard threaded_bb) + : this() { + _log_id = String.Format("NMSheetDriverControlStrip_{0}", req_id); + BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; + BackColor = Color.Transparent; + _threaded_bb = threaded_bb; + _nmsheet_symbol_list = nmsheet_symbol_list; + _in_bb_nmsheet_settings_tag = new NMSheetTags.NMSheetSettingsTag(req_id); + _in_bb_nmsheet_viewable_area_tag = new NMSheetTags.NMSheetViewableAreaTag(req_id); + _in_contract_data_tag = new ContractTags.SystemContractsTag(); + _out_bb_theo_request_tag = new NMSheetTags.NMSheetDataRequestTag(req_id); + + _threaded_bb.data_callback += _react_to_bb; + _threaded_bb.add_to_subscription_list(_in_bb_nmsheet_settings_tag, _in_bb_nmsheet_viewable_area_tag, _in_contract_data_tag); + } + + private void _react_to_bb(object tag, object value) { + if (_in_bb_nmsheet_settings_tag.Equals(tag)) + _handle_setting_changes(); + else if (_in_contract_data_tag.Equals(tag)) + _handle_contract_data_change(); + else if (_in_bb_nmsheet_viewable_area_tag.Equals(tag)) + _handle_grid_changes(); + } + + private void _handle_setting_changes() { + NMSheetSettings settings = (NMSheetSettings)_threaded_bb.sec_thread_retrieve_from_cache(_in_bb_nmsheet_settings_tag) ?? new NMSheetSettings(); + _set_ui_properties(_price_controls.Values, settings); + _send_new_theo_request(); + } + + private void _handle_contract_data_change() { + _send_new_theo_request(); + } + + private void _handle_grid_changes() { + double[] coords = _threaded_bb.sec_thread_retrieve_from_cache(_in_bb_nmsheet_viewable_area_tag) as double[]; + if (coords != null && coords.Length > 0) { + if (_grid_coords == null || _grid_coords[0] != coords[0] || _grid_coords[4] != coords[4]) { + _grid_coords = coords; + _reallign_controls(_price_controls, _grid_coords); + } + } + } + + /// Called on + /// 1. Setting change (as exps are enabled disabled) + /// 2. Security list change (as new exps are added) + /// 3. When a price is frozen/unfrozen + private void _send_new_theo_request() { + /// requests are always based on settings + NMSheetSettings settings = (NMSheetSettings)_threaded_bb.sec_thread_retrieve_from_cache(_in_bb_nmsheet_settings_tag) ?? new NMSheetSettings(); + mbts.spark.SystemContractData contract_data = _threaded_bb.sec_thread_retrieve_from_cache(_in_contract_data_tag) as mbts.spark.SystemContractData ?? mbts.spark.SystemContractData.empty; + List selected_nmsheet_exp_list = NMSheetExpirationMapper.filter_expirations(contract_data, _nmsheet_symbol_list, settings.setting_unselected_expirations); + List> req_list = new List>(); + foreach (NMSheetExpiration nm_exp in selected_nmsheet_exp_list) { + bool is_frozen; + double frozen_price; + _get_driver_frozen_state(_price_controls, nm_exp, out is_frozen, out frozen_price); + req_list.Add(new Triplet(nm_exp, is_frozen, frozen_price)); + } + _threaded_bb.sec_thread_write(_out_bb_theo_request_tag, new NMSheetDataRequest(req_list)); + } + + + public void set_sheet_data(NMSheetData nmsheet_data) { + _nmsheet_data = nmsheet_data; + _handle_sheet_theo_data(nmsheet_data); + } + + /// Uses the theos to update the list of controls. Since theos is what + /// dictated whats being painted on the grid, this keeps this control + /// in sync with the grid in terms of expiration. + private void _handle_sheet_theo_data(NMSheetData nmsheet_data) { + _timer.start(); + bool control_list_modified = false; + NMSheetSettings settings = (NMSheetSettings)_threaded_bb.sec_thread_retrieve_from_cache(_in_bb_nmsheet_settings_tag) ?? new NMSheetSettings(); + if (nmsheet_data != null) { + IDictionary driver_data_map = nmsheet_data.get_driver_data(); + foreach (KeyValuePair driver_data_map_elem in driver_data_map) { + NMSheetExpiration nm_exp = driver_data_map_elem.Key; + PriceControlGUI this_exp_price_control = null; + if (!_price_controls.TryGetValue(nm_exp, out this_exp_price_control)) { + this_exp_price_control = new PriceControlGUI(); + _price_controls.Add(nm_exp, this_exp_price_control); + this_exp_price_control.Tag = nm_exp; + this_exp_price_control.onFreezePrice += _handle_frozen_price_switch; + this_exp_price_control.onLivePrice += _handle_live_price_switch; + Controls.Add(this_exp_price_control); + _set_control_ui_properties(this_exp_price_control, settings); + control_list_modified = true; + } + if (!this_exp_price_control.getCheckState()) + this_exp_price_control.setAnchor(0, driver_data_map_elem.Value.driver_price_at_computed_theo); + } + foreach (NMSheetExpiration nm_exp in new List(_price_controls.Keys)) { + if (!driver_data_map.ContainsKey(nm_exp)) { + PriceControlGUI u = _price_controls[nm_exp]; + u.onFreezePrice -= _handle_frozen_price_switch; + u.onLivePrice -= _handle_live_price_switch; + Controls.Remove(u); + _price_controls.Remove(nm_exp); + control_list_modified = true; + } + } + } + if (control_list_modified) { + _reallign_controls(_price_controls, _threaded_bb.sec_thread_retrieve_from_cache(_in_bb_nmsheet_viewable_area_tag) as double[]); + } + _timer.stop(); + _logger.log(_log_id, "NMSheetDriverControlStrip._handle_sheet_data", _timer.lastIntervalTime); + } + + #region Price control events + + private void _handle_frozen_price_switch(object sender, object data) { + PriceControlGUI pc_ui = sender as PriceControlGUI; + _paint_control_color(pc_ui); + _set_same_as(pc_ui); + _send_new_theo_request(); + } + + private void _handle_live_price_switch(object sender, object data) { + PriceControlGUI pc_ui = sender as PriceControlGUI; + _paint_control_color(pc_ui); + _set_same_as(pc_ui); + _send_new_theo_request(); + } + + private void _set_same_as(PriceControlGUI pc_ui) { + bool frozen_state = pc_ui.getCheckState(); + double price = pc_ui.getAnchor(0); + NMSheetExpiration nmsheet_exp = pc_ui.Tag as NMSheetExpiration; + HashSet same_driver_exps = _nmsheet_data.get_expirations_with_same_driver(nmsheet_exp); + foreach (NMSheetExpiration exp in same_driver_exps) { + PriceControlGUI ui = null; + if (_price_controls.TryGetValue(exp, out ui)) { + ui.setCheckState(frozen_state); + ui.setAnchor(0, price); + _paint_control_color(ui); + } + } + } + + #endregion + + #region Stateless Helpers + + private static void _get_driver_frozen_state(IDictionary price_controls, NMSheetExpiration nm_exp, out bool is_frozen, out double frozen_price) { + PriceControlGUI this_exp_control = null; + is_frozen = false; + frozen_price = -1; + if (price_controls.TryGetValue(nm_exp, out this_exp_control)) { + is_frozen = this_exp_control.getCheckState(); + frozen_price = this_exp_control.getAnchor((int)Anchors.primary); + } + } + + private static void _paint_control_color(PriceControlGUI ui) { + if (!ui.getCheckState()) { + ui.primaryAnchor.config.valueFColor = Color.Black; + ui.primaryAnchor.config.valueBColor = Color.FromKnownColor(KnownColor.Transparent); + } else { + ui.primaryAnchor.config.valueFColor = Color.Yellow; + ui.primaryAnchor.config.valueBColor = Color.IndianRed; + } + } + + private static void _set_ui_properties(IEnumerable driver_control_ui_list, NMSheetSettings settings) { + foreach (PriceControlGUI driver_control_ui in driver_control_ui_list) + _set_control_ui_properties(driver_control_ui, settings); + } + + private static void _set_control_ui_properties(PriceControlGUI driver_control_ui, NMSheetSettings settings) { + driver_control_ui.setInterval(0, settings.setting_driver.driver_move_interval); + driver_control_ui.setTickType(0, settings.setting_driver.tick_type); + } + + /// Paints the controls alligning it with the grid is + private static void _reallign_controls(SortedList price_controls, double[] grid_coords) { + if (grid_coords != null && grid_coords.Length > 0) { + int expiration_width = Convert.ToInt32(grid_coords[4]); + int total_width = Convert.ToInt32(grid_coords[5]); + int offset_within_exp = (expiration_width - _single_driver_control_width) / 2; + int start = offset_within_exp + (-1 * Convert.ToInt32(Convert.ToDouble(total_width) * grid_coords[0])); + foreach (PriceControlGUI price_control in price_controls.Values) { + price_control.Visible = true; + price_control.Top = (5).MultipliedByDPIRatio(); + price_control.Left = start; + price_control.Width = _single_driver_control_width; + price_control.Visible = true; + start += expiration_width; + } + } + } + #endregion + } +} \ No newline at end of file diff --git a/src/client/spark/NMSheets/UIComponents/MainSheet/NMSheetControl.Designer.cs b/src/client/spark/NMSheets/UIComponents/MainSheet/NMSheetControl.Designer.cs new file mode 100644 index 000000000..6f5a2446a --- /dev/null +++ b/src/client/spark/NMSheets/UIComponents/MainSheet/NMSheetControl.Designer.cs @@ -0,0 +1,864 @@ +namespace BCG { + partial class NMSheetControl { + /// + /// 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) { + _logical_dispose(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.components = new System.ComponentModel.Container(); + this._menu_panel = new System.Windows.Forms.Panel(); + this._button_minimize_spreads = new System.Windows.Forms.Button(); + this._button_spreads = new System.Windows.Forms.Button(); + this._button_settings = new System.Windows.Forms.Button(); + this._checkbox_show_straddle = new System.Windows.Forms.CheckBox(); + this._checkbox_show_vol_change = new System.Windows.Forms.CheckBox(); + this._checkbox_show_vol = new System.Windows.Forms.CheckBox(); + this._checkbox_show_position = new System.Windows.Forms.CheckBox(); + this._checkbox_show_bbo = new System.Windows.Forms.CheckBox(); + this._checkbox_show_vega = new System.Windows.Forms.CheckBox(); + this._checkbox_show_gamma = new System.Windows.Forms.CheckBox(); + this._checkbox_show_delta = new System.Windows.Forms.CheckBox(); + this._button_zoom_minus = new System.Windows.Forms.Button(); + this._button_zoom_plus = new System.Windows.Forms.Button(); + this._label_zoom = new System.Windows.Forms.Label(); + this._contextmenustrip_main = new System.Windows.Forms.ContextMenuStrip(this.components); + this._toolstripmenuitem_atm = new System.Windows.Forms.ToolStripMenuItem(); + this._toolseperator_atm = new System.Windows.Forms.ToolStripSeparator(); + this._toolstripmenuitem_task_eye = new System.Windows.Forms.ToolStripMenuItem(); + this._toolstripseperator_task_eye_create = new System.Windows.Forms.ToolStripSeparator(); + this._toolstripmenuitem_task_eye_add_buys_to_task = new System.Windows.Forms.ToolStripMenuItem(); + this._toolstripmenuitem_task_eye_add_sells_to_task = new System.Windows.Forms.ToolStripMenuItem(); + this._toolstripmenuitem_task_eye_add_buys_and_sells_to_task = new System.Windows.Forms.ToolStripMenuItem(); + this._toolstripmenuitem_task_quoter = new System.Windows.Forms.ToolStripMenuItem(); + this._toolstripseperator_task_quoter_create = new System.Windows.Forms.ToolStripSeparator(); + this._toolstripmenuitem_task_quoter_add_buys_to_task = new System.Windows.Forms.ToolStripMenuItem(); + this._toolstripmenuitem_task_quoter_add_sells_to_task = new System.Windows.Forms.ToolStripMenuItem(); + this._toolstripmenuitem_task_quoter_add_buys_and_sells_to_task = new System.Windows.Forms.ToolStripMenuItem(); + this._toolstripmenuitem_task_override_edge = new System.Windows.Forms.ToolStripMenuItem(); + this._toolstripmenuitem_task_enter_edge = new System.Windows.Forms.ToolStripMenuItem(); + this._toolstripseparator_task_edge = new System.Windows.Forms.ToolStripSeparator(); + this._toolstripmenuitem_task_undo_edge_override = new System.Windows.Forms.ToolStripMenuItem(); + this._toolstripmenuitem_task_override_size = new System.Windows.Forms.ToolStripMenuItem(); + this._toolstripmenuitem_task_enter_size = new System.Windows.Forms.ToolStripMenuItem(); + this._toolstripseparator_task_size = new System.Windows.Forms.ToolStripSeparator(); + this._toolstripmenuitem_task_undo_size_override = new System.Windows.Forms.ToolStripMenuItem(); + this._toolstripmenuitem_task_eye_switch_all_off = new System.Windows.Forms.ToolStripMenuItem(); + this._toolstripmenuitem_task_manage_templates = new System.Windows.Forms.ToolStripMenuItem(); + this._toolstripseperator_task_eye = new System.Windows.Forms.ToolStripSeparator(); + this._toolstrip_menuitem_save_data_to_file = new System.Windows.Forms.ToolStripMenuItem(); + this._toolstripseperator_export_data = new System.Windows.Forms.ToolStripSeparator(); + this._toolstripmenuitem_card = new System.Windows.Forms.ToolStripMenuItem(); + this._toolstripseperator_expirations = new System.Windows.Forms.ToolStripSeparator(); + this._toolstripmenuitem_spread_summary = new System.Windows.Forms.ToolStripMenuItem(); + this._toolstripmenuitem_minimize_spreads = new System.Windows.Forms.ToolStripMenuItem(); + this._toolstripseperator_filter = new System.Windows.Forms.ToolStripSeparator(); + this._toolstripmenuitem_filter = new System.Windows.Forms.ToolStripMenuItem(); + this._toolstripmenuitem_filter_strikes_in_tasks = new System.Windows.Forms.ToolStripMenuItem(); + this._toolstripmenuitem_filter_on_strikes_in_tasks = new System.Windows.Forms.ToolStripMenuItem(); + this._toolseperator_quotesets = new System.Windows.Forms.ToolStripSeparator(); + this._toolstripmenuitem_sheet_column_settings = new System.Windows.Forms.ToolStripMenuItem(); + this._toolstripmenuitem_sheet_settings = new System.Windows.Forms.ToolStripMenuItem(); + this._toolstripmenuitem_settings_delta = new System.Windows.Forms.ToolStripMenuItem(); + this._toolstripmenuitem_settings_gamma = new System.Windows.Forms.ToolStripMenuItem(); + this._toolstripmenuitem_settings_vega = new System.Windows.Forms.ToolStripMenuItem(); + this._toolstripmenuitem_settings_bbo = new System.Windows.Forms.ToolStripMenuItem(); + this._toolstripmenuitem_settings_position = new System.Windows.Forms.ToolStripMenuItem(); + this._toolstripmenuitem_settings_vol = new System.Windows.Forms.ToolStripMenuItem(); + this._toolstripmenuitem_settings_volchange = new System.Windows.Forms.ToolStripMenuItem(); + this._toolstripmenuitem_settings_straddle = new System.Windows.Forms.ToolStripMenuItem(); + this._toolseperator_task_ee = new System.Windows.Forms.ToolStripSeparator(); + this._toolstripmenuitem_settings_show_task_ee_data = new System.Windows.Forms.ToolStripMenuItem(); + this._toolstripmenuitem_settings_show_task_quoter_data = new System.Windows.Forms.ToolStripMenuItem(); + this._toolseperator_quoteset_parameters = new System.Windows.Forms.ToolStripSeparator(); + this._toolstripmenuitem_settings_show_quoteset_edgesize = new System.Windows.Forms.ToolStripMenuItem(); + this._toolstripmenuitem_settings_show_quoteset_midprice = new System.Windows.Forms.ToolStripMenuItem(); + this._toolseperator_parameters = new System.Windows.Forms.ToolStripSeparator(); + this._toolstripmenuitem_settings_zoomout = new System.Windows.Forms.ToolStripMenuItem(); + this._toolstripmenuitem_settings_zoomin = new System.Windows.Forms.ToolStripMenuItem(); + this._toolstripseperator_zoom = new System.Windows.Forms.ToolStripSeparator(); + this._toolstripmenuitem_sheet_settings_window = new System.Windows.Forms.ToolStripMenuItem(); + this._statusbar_toolstripstatus_security = new System.Windows.Forms.ToolStripStatusLabel(); + this._statusbar_toolstripstatus_column = new System.Windows.Forms.ToolStripStatusLabel(); + this._statustrip_main = new System.Windows.Forms.StatusStrip(); + this._statusbar_toolstripstatus_task = new System.Windows.Forms.ToolStripStatusLabel(); + this._statusbar_toolstripstatus_quoterdata = new System.Windows.Forms.ToolStripStatusLabel(); + this._button_theo_acceptance_confirmation = new System.Windows.Forms.Button(); + this._toolstripmenuitem_filter_strikes_with_pos_edge = new System.Windows.Forms.ToolStripMenuItem(); + this._menu_panel.SuspendLayout(); + this._contextmenustrip_main.SuspendLayout(); + this._statustrip_main.SuspendLayout(); + this.SuspendLayout(); + // + // _menu_panel + // + this._menu_panel.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) + | System.Windows.Forms.AnchorStyles.Right))); + this._menu_panel.Controls.Add(this._button_minimize_spreads); + this._menu_panel.Controls.Add(this._button_spreads); + this._menu_panel.Controls.Add(this._button_settings); + this._menu_panel.Controls.Add(this._checkbox_show_straddle); + this._menu_panel.Controls.Add(this._checkbox_show_vol_change); + this._menu_panel.Controls.Add(this._checkbox_show_vol); + this._menu_panel.Controls.Add(this._checkbox_show_position); + this._menu_panel.Controls.Add(this._checkbox_show_bbo); + this._menu_panel.Controls.Add(this._checkbox_show_vega); + this._menu_panel.Controls.Add(this._checkbox_show_gamma); + this._menu_panel.Controls.Add(this._checkbox_show_delta); + this._menu_panel.Controls.Add(this._button_zoom_minus); + this._menu_panel.Controls.Add(this._button_zoom_plus); + this._menu_panel.Controls.Add(this._label_zoom); + this._menu_panel.Location = new System.Drawing.Point(0, 0); + this._menu_panel.Name = "_menu_panel"; + this._menu_panel.Size = new System.Drawing.Size(1133, 28); + this._menu_panel.TabIndex = 0; + // + // _button_minimize_spreads + // + this._button_minimize_spreads.FlatStyle = System.Windows.Forms.FlatStyle.Flat; + this._button_minimize_spreads.Location = new System.Drawing.Point(126, 2); + this._button_minimize_spreads.Name = "_button_minimize_spreads"; + this._button_minimize_spreads.Size = new System.Drawing.Size(77, 22); + this._button_minimize_spreads.TabIndex = 22; + this._button_minimize_spreads.Text = "Min Spreads"; + this._button_minimize_spreads.UseVisualStyleBackColor = true; + // + // _button_spreads + // + this._button_spreads.FlatStyle = System.Windows.Forms.FlatStyle.Flat; + this._button_spreads.Location = new System.Drawing.Point(65, 2); + this._button_spreads.Name = "_button_spreads"; + this._button_spreads.Size = new System.Drawing.Size(58, 22); + this._button_spreads.TabIndex = 21; + this._button_spreads.Text = "Spreads"; + this._button_spreads.UseVisualStyleBackColor = true; + // + // _button_settings + // + this._button_settings.FlatStyle = System.Windows.Forms.FlatStyle.Flat; + this._button_settings.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this._button_settings.Location = new System.Drawing.Point(4, 2); + this._button_settings.Name = "_button_settings"; + this._button_settings.Size = new System.Drawing.Size(58, 22); + this._button_settings.TabIndex = 20; + this._button_settings.Text = "Settings"; + this._button_settings.TextAlign = System.Drawing.ContentAlignment.TopCenter; + this._button_settings.UseVisualStyleBackColor = true; + // + // _checkbox_show_straddle + // + this._checkbox_show_straddle.AutoSize = true; + this._checkbox_show_straddle.FlatStyle = System.Windows.Forms.FlatStyle.Flat; + this._checkbox_show_straddle.Location = new System.Drawing.Point(681, 6); + this._checkbox_show_straddle.Name = "_checkbox_show_straddle"; + this._checkbox_show_straddle.Size = new System.Drawing.Size(42, 17); + this._checkbox_show_straddle.TabIndex = 19; + this._checkbox_show_straddle.Text = "Strd"; + this._checkbox_show_straddle.UseVisualStyleBackColor = true; + // + // _checkbox_show_vol_change + // + this._checkbox_show_vol_change.AutoSize = true; + this._checkbox_show_vol_change.FlatStyle = System.Windows.Forms.FlatStyle.Flat; + this._checkbox_show_vol_change.Location = new System.Drawing.Point(620, 6); + this._checkbox_show_vol_change.Name = "_checkbox_show_vol_change"; + this._checkbox_show_vol_change.Size = new System.Drawing.Size(54, 17); + this._checkbox_show_vol_change.TabIndex = 18; + this._checkbox_show_vol_change.Text = "Vol Ch"; + this._checkbox_show_vol_change.UseVisualStyleBackColor = true; + // + // _checkbox_show_vol + // + this._checkbox_show_vol.AutoSize = true; + this._checkbox_show_vol.FlatStyle = System.Windows.Forms.FlatStyle.Flat; + this._checkbox_show_vol.Location = new System.Drawing.Point(576, 6); + this._checkbox_show_vol.Name = "_checkbox_show_vol"; + this._checkbox_show_vol.Size = new System.Drawing.Size(38, 17); + this._checkbox_show_vol.TabIndex = 17; + this._checkbox_show_vol.Text = "Vol"; + this._checkbox_show_vol.UseVisualStyleBackColor = true; + // + // _checkbox_show_position + // + this._checkbox_show_position.AutoSize = true; + this._checkbox_show_position.FlatStyle = System.Windows.Forms.FlatStyle.Flat; + this._checkbox_show_position.Location = new System.Drawing.Point(529, 6); + this._checkbox_show_position.Name = "_checkbox_show_position"; + this._checkbox_show_position.Size = new System.Drawing.Size(41, 17); + this._checkbox_show_position.TabIndex = 16; + this._checkbox_show_position.Text = "Pos"; + this._checkbox_show_position.UseVisualStyleBackColor = true; + // + // _checkbox_show_bbo + // + this._checkbox_show_bbo.AutoSize = true; + this._checkbox_show_bbo.FlatStyle = System.Windows.Forms.FlatStyle.Flat; + this._checkbox_show_bbo.Location = new System.Drawing.Point(477, 6); + this._checkbox_show_bbo.Name = "_checkbox_show_bbo"; + this._checkbox_show_bbo.Size = new System.Drawing.Size(45, 17); + this._checkbox_show_bbo.TabIndex = 15; + this._checkbox_show_bbo.Text = "BBO"; + this._checkbox_show_bbo.UseVisualStyleBackColor = true; + // + // _checkbox_show_vega + // + this._checkbox_show_vega.AutoSize = true; + this._checkbox_show_vega.FlatStyle = System.Windows.Forms.FlatStyle.Flat; + this._checkbox_show_vega.Location = new System.Drawing.Point(422, 6); + this._checkbox_show_vega.Name = "_checkbox_show_vega"; + this._checkbox_show_vega.Size = new System.Drawing.Size(48, 17); + this._checkbox_show_vega.TabIndex = 14; + this._checkbox_show_vega.Text = "Vega"; + this._checkbox_show_vega.UseVisualStyleBackColor = true; + // + // _checkbox_show_gamma + // + this._checkbox_show_gamma.AutoSize = true; + this._checkbox_show_gamma.FlatStyle = System.Windows.Forms.FlatStyle.Flat; + this._checkbox_show_gamma.Location = new System.Drawing.Point(357, 6); + this._checkbox_show_gamma.Name = "_checkbox_show_gamma"; + this._checkbox_show_gamma.Size = new System.Drawing.Size(59, 17); + this._checkbox_show_gamma.TabIndex = 13; + this._checkbox_show_gamma.Text = "Gamma"; + this._checkbox_show_gamma.UseVisualStyleBackColor = true; + // + // _checkbox_show_delta + // + this._checkbox_show_delta.AutoSize = true; + this._checkbox_show_delta.FlatStyle = System.Windows.Forms.FlatStyle.Flat; + this._checkbox_show_delta.Location = new System.Drawing.Point(305, 6); + this._checkbox_show_delta.Name = "_checkbox_show_delta"; + this._checkbox_show_delta.Size = new System.Drawing.Size(48, 17); + this._checkbox_show_delta.TabIndex = 12; + this._checkbox_show_delta.Text = "Delta"; + this._checkbox_show_delta.UseVisualStyleBackColor = true; + // + // _button_zoom_minus + // + this._button_zoom_minus.FlatStyle = System.Windows.Forms.FlatStyle.Flat; + // TODO + //this._button_zoom_minus.Image = global::BCG.Properties.Resources.minus_16; + this._button_zoom_minus.Location = new System.Drawing.Point(206, 2); + this._button_zoom_minus.Name = "_button_zoom_minus"; + this._button_zoom_minus.Size = new System.Drawing.Size(22, 22); + this._button_zoom_minus.TabIndex = 11; + this._button_zoom_minus.UseVisualStyleBackColor = true; + // + // _button_zoom_plus + // + this._button_zoom_plus.FlatStyle = System.Windows.Forms.FlatStyle.Flat; + //this._button_zoom_plus.Image = global::BCG.Properties.Resources.plus_16; + this._button_zoom_plus.Location = new System.Drawing.Point(268, 2); + this._button_zoom_plus.Name = "_button_zoom_plus"; + this._button_zoom_plus.Size = new System.Drawing.Size(22, 22); + this._button_zoom_plus.TabIndex = 10; + this._button_zoom_plus.UseVisualStyleBackColor = true; + // + // _label_zoom + // + this._label_zoom.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; + this._label_zoom.Location = new System.Drawing.Point(227, 2); + this._label_zoom.Name = "_label_zoom"; + this._label_zoom.Size = new System.Drawing.Size(42, 22); + this._label_zoom.TabIndex = 9; + this._label_zoom.Text = "Zoom"; + this._label_zoom.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; + // + // _contextmenustrip_main + // + System.Collections.Generic.List right_click_menu = new System.Collections.Generic.List() { + this._toolstripmenuitem_atm, + this._toolseperator_atm, + }; + if (!_api_tasking_enabled) { + right_click_menu.AddRange(new System.Collections.Generic.List() { + this._toolstripmenuitem_task_eye, + this._toolstripmenuitem_task_quoter, + }); + } + right_click_menu.AddRange(new System.Collections.Generic.List() { + this._toolstripmenuitem_task_override_edge, + this._toolstripmenuitem_task_override_size, + }); + if (!_api_tasking_enabled) { + right_click_menu.AddRange(new System.Collections.Generic.List() { + this._toolstripmenuitem_task_eye_switch_all_off, + this._toolstripmenuitem_task_manage_templates, + }); + } + right_click_menu.AddRange(new System.Collections.Generic.List() { + this._toolstripseperator_task_eye, + this._toolstrip_menuitem_save_data_to_file, + this._toolstripseperator_export_data, + this._toolstripmenuitem_card, + this._toolstripseperator_expirations, + this._toolstripmenuitem_spread_summary, + this._toolstripmenuitem_minimize_spreads, + this._toolstripseperator_filter, + }); + if (!_api_tasking_enabled) { + right_click_menu.AddRange(new System.Collections.Generic.List() { + this._toolstripmenuitem_filter, + this._toolseperator_quotesets + }); + } + right_click_menu.AddRange(new System.Collections.Generic.List() { + this._toolstripmenuitem_sheet_column_settings, + this._toolstripmenuitem_sheet_settings + }); + + this._contextmenustrip_main.Items.AddRange(right_click_menu.ToArray()); + this._contextmenustrip_main.Name = "_contextmenustrip_main"; + this._contextmenustrip_main.RenderMode = System.Windows.Forms.ToolStripRenderMode.Professional; + this._contextmenustrip_main.Size = new System.Drawing.Size(217, 370); + // + // _toolstripmenuitem_atm + // + this._toolstripmenuitem_atm.Name = "_toolstripmenuitem_atm"; + this._toolstripmenuitem_atm.Size = new System.Drawing.Size(216, 22); + this._toolstripmenuitem_atm.Text = "ATM"; + // + // _toolseperator_atm + // + this._toolseperator_atm.Name = "_toolseperator_atm"; + this._toolseperator_atm.Size = new System.Drawing.Size(213, 6); + // + // _toolstripmenuitem_task_eye + // + this._toolstripmenuitem_task_eye.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { + this._toolstripseperator_task_eye_create, + this._toolstripmenuitem_task_eye_add_buys_to_task, + this._toolstripmenuitem_task_eye_add_sells_to_task, + this._toolstripmenuitem_task_eye_add_buys_and_sells_to_task}); + this._toolstripmenuitem_task_eye.Name = "_toolstripmenuitem_task_eye"; + this._toolstripmenuitem_task_eye.Size = new System.Drawing.Size(216, 22); + this._toolstripmenuitem_task_eye.Text = "Eye Tasks"; + // + // _toolstripseperator_task_eye_create + // + this._toolstripseperator_task_eye_create.Name = "_toolstripseperator_task_eye_create"; + this._toolstripseperator_task_eye_create.Size = new System.Drawing.Size(191, 6); + // + // _toolstripmenuitem_task_eye_add_buys_to_task + // + this._toolstripmenuitem_task_eye_add_buys_to_task.Name = "_toolstripmenuitem_task_eye_add_buys_to_task"; + this._toolstripmenuitem_task_eye_add_buys_to_task.Size = new System.Drawing.Size(194, 22); + this._toolstripmenuitem_task_eye_add_buys_to_task.Text = "Add Buys To Task"; + // + // _toolstripmenuitem_task_eye_add_sells_to_task + // + this._toolstripmenuitem_task_eye_add_sells_to_task.Name = "_toolstripmenuitem_task_eye_add_sells_to_task"; + this._toolstripmenuitem_task_eye_add_sells_to_task.Size = new System.Drawing.Size(194, 22); + this._toolstripmenuitem_task_eye_add_sells_to_task.Text = "Add Sells To Task"; + // + // _toolstripmenuitem_task_eye_add_buys_and_sells_to_task + // + this._toolstripmenuitem_task_eye_add_buys_and_sells_to_task.Name = "_toolstripmenuitem_task_eye_add_buys_and_sells_to_task"; + this._toolstripmenuitem_task_eye_add_buys_and_sells_to_task.Size = new System.Drawing.Size(194, 22); + this._toolstripmenuitem_task_eye_add_buys_and_sells_to_task.Text = "Add Buys/Sells To Task"; + // + // _toolstripmenuitem_task_quoter + // + this._toolstripmenuitem_task_quoter.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { + this._toolstripseperator_task_quoter_create, + this._toolstripmenuitem_task_quoter_add_buys_to_task, + this._toolstripmenuitem_task_quoter_add_sells_to_task, + this._toolstripmenuitem_task_quoter_add_buys_and_sells_to_task}); + this._toolstripmenuitem_task_quoter.Name = "_toolstripmenuitem_task_quoter"; + this._toolstripmenuitem_task_quoter.Size = new System.Drawing.Size(216, 22); + this._toolstripmenuitem_task_quoter.Text = "Quote Tasks"; + // + // _toolstripseperator_task_quoter_create + // + this._toolstripseperator_task_quoter_create.Name = "_toolstripseperator_task_quoter_create"; + this._toolstripseperator_task_quoter_create.Size = new System.Drawing.Size(191, 6); + // + // _toolstripmenuitem_task_quoter_add_buys_to_task + // + this._toolstripmenuitem_task_quoter_add_buys_to_task.Name = "_toolstripmenuitem_task_quoter_add_buys_to_task"; + this._toolstripmenuitem_task_quoter_add_buys_to_task.Size = new System.Drawing.Size(194, 22); + this._toolstripmenuitem_task_quoter_add_buys_to_task.Text = "Add Buys To Task"; + // + // _toolstripmenuitem_task_quoter_add_sells_to_task + // + this._toolstripmenuitem_task_quoter_add_sells_to_task.Name = "_toolstripmenuitem_task_quoter_add_sells_to_task"; + this._toolstripmenuitem_task_quoter_add_sells_to_task.Size = new System.Drawing.Size(194, 22); + this._toolstripmenuitem_task_quoter_add_sells_to_task.Text = "Add Sells To Task"; + // + // _toolstripmenuitem_task_quoter_add_buys_and_sells_to_task + // + this._toolstripmenuitem_task_quoter_add_buys_and_sells_to_task.Name = "_toolstripmenuitem_task_quoter_add_buys_and_sells_to_task"; + this._toolstripmenuitem_task_quoter_add_buys_and_sells_to_task.Size = new System.Drawing.Size(194, 22); + this._toolstripmenuitem_task_quoter_add_buys_and_sells_to_task.Text = "Add Buys/Sells To Task"; + // + // _toolstripmenuitem_task_override_edge + // + this._toolstripmenuitem_task_override_edge.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { + this._toolstripmenuitem_task_enter_edge, + this._toolstripseparator_task_edge, + this._toolstripmenuitem_task_undo_edge_override}); + this._toolstripmenuitem_task_override_edge.Name = "_toolstripmenuitem_task_override_edge"; + this._toolstripmenuitem_task_override_edge.Size = new System.Drawing.Size(216, 22); + this._toolstripmenuitem_task_override_edge.Text = "Override Edge"; + // + // _toolstripmenuitem_task_enter_edge + // + this._toolstripmenuitem_task_enter_edge.Name = "_toolstripmenuitem_task_enter_edge"; + this._toolstripmenuitem_task_enter_edge.Size = new System.Drawing.Size(180, 22); + this._toolstripmenuitem_task_enter_edge.Text = "Edge..."; + // + // _toolstripseparator_task_edge + // + this._toolstripseparator_task_edge.Name = "_toolstripseparator_task_edge"; + this._toolstripseparator_task_edge.Size = new System.Drawing.Size(177, 6); + // + // _toolstripmenuitem_task_undo_edge_override + // + this._toolstripmenuitem_task_undo_edge_override.Name = "_toolstripmenuitem_task_undo_edge_override"; + this._toolstripmenuitem_task_undo_edge_override.Size = new System.Drawing.Size(180, 22); + this._toolstripmenuitem_task_undo_edge_override.Text = "Undo Edge Override"; + // + // _toolstripmenuitem_task_override_size + // + this._toolstripmenuitem_task_override_size.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { + this._toolstripmenuitem_task_enter_size, + this._toolstripseparator_task_size, + this._toolstripmenuitem_task_undo_size_override}); + this._toolstripmenuitem_task_override_size.Name = "_toolstripmenuitem_task_override_size"; + this._toolstripmenuitem_task_override_size.Size = new System.Drawing.Size(216, 22); + this._toolstripmenuitem_task_override_size.Text = "Override Size"; + // + // _toolstripmenuitem_task_enter_size + // + this._toolstripmenuitem_task_enter_size.Name = "_toolstripmenuitem_task_enter_size"; + this._toolstripmenuitem_task_enter_size.Size = new System.Drawing.Size(174, 22); + this._toolstripmenuitem_task_enter_size.Text = "Size..."; + // + // _toolstripseparator_task_size + // + this._toolstripseparator_task_size.Name = "_toolstripseparator_task_size"; + this._toolstripseparator_task_size.Size = new System.Drawing.Size(171, 6); + // + // _toolstripmenuitem_task_undo_size_override + // + this._toolstripmenuitem_task_undo_size_override.Name = "_toolstripmenuitem_task_undo_size_override"; + this._toolstripmenuitem_task_undo_size_override.Size = new System.Drawing.Size(174, 22); + this._toolstripmenuitem_task_undo_size_override.Text = "Undo Size Override"; + // + // _toolstripmenuitem_task_eye_switch_all_off + // + this._toolstripmenuitem_task_eye_switch_all_off.BackColor = System.Drawing.SystemColors.Control; + this._toolstripmenuitem_task_eye_switch_all_off.ForeColor = System.Drawing.SystemColors.ControlText; + this._toolstripmenuitem_task_eye_switch_all_off.Name = "_toolstripmenuitem_task_eye_switch_all_off"; + this._toolstripmenuitem_task_eye_switch_all_off.Size = new System.Drawing.Size(216, 22); + this._toolstripmenuitem_task_eye_switch_all_off.Text = "Switch All Tasks OFF"; + // + // _toolstripmenuitem_task_manage_templates + // + this._toolstripmenuitem_task_manage_templates.Name = "_toolstripmenuitem_task_manage_templates"; + this._toolstripmenuitem_task_manage_templates.Size = new System.Drawing.Size(216, 22); + this._toolstripmenuitem_task_manage_templates.Text = "Manage Task Templates"; + // + // _toolstripseperator_task_eye + // + this._toolstripseperator_task_eye.Name = "_toolstripseperator_task_eye"; + this._toolstripseperator_task_eye.Size = new System.Drawing.Size(213, 6); + // + // _toolstrip_menuitem_save_data_to_file + // + this._toolstrip_menuitem_save_data_to_file.Name = "_toolstrip_menuitem_save_data_to_file"; + this._toolstrip_menuitem_save_data_to_file.Size = new System.Drawing.Size(216, 22); + this._toolstrip_menuitem_save_data_to_file.Text = "Save Data To File"; + // + // _toolstripseperator_export_data + // + this._toolstripseperator_export_data.Name = "_toolstripseperator_export_data"; + this._toolstripseperator_export_data.Size = new System.Drawing.Size(213, 6); + // + // _toolstripmenuitem_card + // + this._toolstripmenuitem_card.Name = "_toolstripmenuitem_card"; + this._toolstripmenuitem_card.Size = new System.Drawing.Size(216, 22); + this._toolstripmenuitem_card.Text = "Card"; + // + // _toolstripseperator_expirations + // + this._toolstripseperator_expirations.Name = "_toolstripseperator_expirations"; + this._toolstripseperator_expirations.Size = new System.Drawing.Size(213, 6); + // + // _toolstripmenuitem_spread_summary + // + this._toolstripmenuitem_spread_summary.Name = "_toolstripmenuitem_spread_summary"; + this._toolstripmenuitem_spread_summary.Size = new System.Drawing.Size(216, 22); + this._toolstripmenuitem_spread_summary.Text = "Spread Summary"; + // + // _toolstripmenuitem_minimize_spreads + // + this._toolstripmenuitem_minimize_spreads.Name = "_toolstripmenuitem_minimize_spreads"; + this._toolstripmenuitem_minimize_spreads.Size = new System.Drawing.Size(216, 22); + this._toolstripmenuitem_minimize_spreads.Text = "Minimize All Open Spreads"; + // + // _toolstripseperator_filter + // + this._toolstripseperator_filter.Name = "_toolstripseperator_filter"; + this._toolstripseperator_filter.Size = new System.Drawing.Size(213, 6); + // + // _toolstripmenuitem_filter + // + this._toolstripmenuitem_filter.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { + this._toolstripmenuitem_filter_strikes_with_pos_edge, + this._toolstripmenuitem_filter_strikes_in_tasks, + this._toolstripmenuitem_filter_on_strikes_in_tasks}); + this._toolstripmenuitem_filter.Name = "_toolstripmenuitem_filter"; + this._toolstripmenuitem_filter.Size = new System.Drawing.Size(216, 22); + this._toolstripmenuitem_filter.Text = "Show Only"; + // + // _toolstripmenuitem_filter_strikes_in_tasks + // + this._toolstripmenuitem_filter_strikes_in_tasks.Name = "_toolstripmenuitem_filter_strikes_in_tasks"; + this._toolstripmenuitem_filter_strikes_in_tasks.Size = new System.Drawing.Size(269, 22); + this._toolstripmenuitem_filter_strikes_in_tasks.Text = "Strikes in Electronic Trading Tasks"; + // + // _toolstripmenuitem_filter_on_strikes_in_tasks + // + this._toolstripmenuitem_filter_on_strikes_in_tasks.Name = "_toolstripmenuitem_filter_on_strikes_in_tasks"; + this._toolstripmenuitem_filter_on_strikes_in_tasks.Size = new System.Drawing.Size(269, 22); + this._toolstripmenuitem_filter_on_strikes_in_tasks.Text = "On Strikes in Electronic Trading Tasks"; + // + // _toolseperator_quotesets + // + this._toolseperator_quotesets.Name = "_toolseperator_quotesets"; + this._toolseperator_quotesets.Size = new System.Drawing.Size(213, 6); + // + // _toolstripmenuitem_sheet_column_settings + // + this._toolstripmenuitem_sheet_column_settings.Name = "_toolstripmenuitem_sheet_column_settings"; + this._toolstripmenuitem_sheet_column_settings.Size = new System.Drawing.Size(216, 22); + this._toolstripmenuitem_sheet_column_settings.Text = "Set Display For Call Theo"; + // + // _toolstripmenuitem_sheet_settings + // + System.Collections.Generic.List sheet_settings_items = new System.Collections.Generic.List() { + this._toolstripmenuitem_settings_delta, + this._toolstripmenuitem_settings_gamma, + this._toolstripmenuitem_settings_vega, + this._toolstripmenuitem_settings_bbo, + this._toolstripmenuitem_settings_position, + this._toolstripmenuitem_settings_vol, + this._toolstripmenuitem_settings_volchange, + this._toolstripmenuitem_settings_straddle + }; + if (!_api_tasking_enabled) { + sheet_settings_items.AddRange(new System.Collections.Generic.List() { + this._toolseperator_task_ee, + this._toolstripmenuitem_settings_show_task_ee_data, + this._toolstripmenuitem_settings_show_task_quoter_data, + this._toolseperator_quoteset_parameters, + this._toolstripmenuitem_settings_show_quoteset_edgesize, + this._toolstripmenuitem_settings_show_quoteset_midprice, + }); + } + sheet_settings_items.AddRange(new System.Collections.Generic.List() { this._toolseperator_parameters, + this._toolstripmenuitem_settings_zoomout, + this._toolstripmenuitem_settings_zoomin, + this._toolstripseperator_zoom, + this._toolstripmenuitem_sheet_settings_window + }); + + this._toolstripmenuitem_sheet_settings.DropDownItems.AddRange(sheet_settings_items.ToArray()); + this._toolstripmenuitem_sheet_settings.Name = "_toolstripmenuitem_sheet_settings"; + this._toolstripmenuitem_sheet_settings.Size = new System.Drawing.Size(216, 22); + this._toolstripmenuitem_sheet_settings.Text = "Sheet Settings"; + // + // _toolstripmenuitem_settings_delta + // + this._toolstripmenuitem_settings_delta.Name = "_toolstripmenuitem_settings_delta"; + this._toolstripmenuitem_settings_delta.Size = new System.Drawing.Size(196, 22); + this._toolstripmenuitem_settings_delta.Text = "Delta"; + // + // _toolstripmenuitem_settings_gamma + // + this._toolstripmenuitem_settings_gamma.Name = "_toolstripmenuitem_settings_gamma"; + this._toolstripmenuitem_settings_gamma.Size = new System.Drawing.Size(196, 22); + this._toolstripmenuitem_settings_gamma.Text = "Gamma"; + // + // _toolstripmenuitem_settings_vega + // + this._toolstripmenuitem_settings_vega.Name = "_toolstripmenuitem_settings_vega"; + this._toolstripmenuitem_settings_vega.Size = new System.Drawing.Size(196, 22); + this._toolstripmenuitem_settings_vega.Text = "Vega"; + // + // _toolstripmenuitem_settings_bbo + // + this._toolstripmenuitem_settings_bbo.Name = "_toolstripmenuitem_settings_bbo"; + this._toolstripmenuitem_settings_bbo.Size = new System.Drawing.Size(196, 22); + this._toolstripmenuitem_settings_bbo.Text = "BBO"; + // + // _toolstripmenuitem_settings_position + // + this._toolstripmenuitem_settings_position.Name = "_toolstripmenuitem_settings_position"; + this._toolstripmenuitem_settings_position.Size = new System.Drawing.Size(196, 22); + this._toolstripmenuitem_settings_position.Text = "Position"; + // + // _toolstripmenuitem_settings_vol + // + this._toolstripmenuitem_settings_vol.Name = "_toolstripmenuitem_settings_vol"; + this._toolstripmenuitem_settings_vol.Size = new System.Drawing.Size(196, 22); + this._toolstripmenuitem_settings_vol.Text = "Vol"; + // + // _toolstripmenuitem_settings_volchange + // + this._toolstripmenuitem_settings_volchange.Name = "_toolstripmenuitem_settings_volchange"; + this._toolstripmenuitem_settings_volchange.Size = new System.Drawing.Size(196, 22); + this._toolstripmenuitem_settings_volchange.Text = "Vol Change On Day"; + // + // _toolstripmenuitem_settings_straddle + // + this._toolstripmenuitem_settings_straddle.Name = "_toolstripmenuitem_settings_straddle"; + this._toolstripmenuitem_settings_straddle.Size = new System.Drawing.Size(196, 22); + this._toolstripmenuitem_settings_straddle.Text = "Straddle"; + // + // _toolseperator_task_ee + // + this._toolseperator_task_ee.Name = "_toolseperator_task_ee"; + this._toolseperator_task_ee.Size = new System.Drawing.Size(193, 6); + // + // _toolstripmenuitem_settings_show_task_ee_data + // + this._toolstripmenuitem_settings_show_task_ee_data.Name = "_toolstripmenuitem_settings_show_task_ee_data"; + this._toolstripmenuitem_settings_show_task_ee_data.Size = new System.Drawing.Size(196, 22); + this._toolstripmenuitem_settings_show_task_ee_data.Text = "Electronic Eye"; + // + // _toolstripmenuitem_settings_show_task_quoter_data + // + this._toolstripmenuitem_settings_show_task_quoter_data.Name = "_toolstripmenuitem_settings_show_task_quoter_data"; + this._toolstripmenuitem_settings_show_task_quoter_data.Size = new System.Drawing.Size(196, 22); + this._toolstripmenuitem_settings_show_task_quoter_data.Text = "Quoter"; + // + // _toolseperator_quoteset_parameters + // + this._toolseperator_quoteset_parameters.Name = "_toolseperator_quoteset_parameters"; + this._toolseperator_quoteset_parameters.Size = new System.Drawing.Size(193, 6); + // + // _toolstripmenuitem_settings_show_quoteset_edgesize + // + this._toolstripmenuitem_settings_show_quoteset_edgesize.Name = "_toolstripmenuitem_settings_show_quoteset_edgesize"; + this._toolstripmenuitem_settings_show_quoteset_edgesize.Size = new System.Drawing.Size(196, 22); + this._toolstripmenuitem_settings_show_quoteset_edgesize.Text = "Edge Surface Edge/Size"; + // + // _toolstripmenuitem_settings_show_quoteset_midprice + // + this._toolstripmenuitem_settings_show_quoteset_midprice.Name = "_toolstripmenuitem_settings_show_quoteset_midprice"; + this._toolstripmenuitem_settings_show_quoteset_midprice.Size = new System.Drawing.Size(196, 22); + this._toolstripmenuitem_settings_show_quoteset_midprice.Text = "Edge Surface Mid Price"; + // + // _toolseperator_parameters + // + this._toolseperator_parameters.Name = "_toolseperator_parameters"; + this._toolseperator_parameters.Size = new System.Drawing.Size(193, 6); + // + // _toolstripmenuitem_settings_zoomout + // + //this._toolstripmenuitem_settings_zoomout.Image = global::BCG.Properties.Resources.minus_16; + this._toolstripmenuitem_settings_zoomout.Name = "_toolstripmenuitem_settings_zoomout"; + this._toolstripmenuitem_settings_zoomout.Size = new System.Drawing.Size(196, 22); + this._toolstripmenuitem_settings_zoomout.Text = "Zoom Out"; + // + // _toolstripmenuitem_settings_zoomin + // + //this._toolstripmenuitem_settings_zoomin.Image = global::BCG.Properties.Resources.plus_16; + this._toolstripmenuitem_settings_zoomin.Name = "_toolstripmenuitem_settings_zoomin"; + this._toolstripmenuitem_settings_zoomin.Size = new System.Drawing.Size(196, 22); + this._toolstripmenuitem_settings_zoomin.Text = "Zoom In"; + // + // _toolstripseperator_zoom + // + this._toolstripseperator_zoom.Name = "_toolstripseperator_zoom"; + this._toolstripseperator_zoom.Size = new System.Drawing.Size(193, 6); + // + // _toolstripmenuitem_sheet_settings_window + // + this._toolstripmenuitem_sheet_settings_window.Name = "_toolstripmenuitem_sheet_settings_window"; + this._toolstripmenuitem_sheet_settings_window.Size = new System.Drawing.Size(196, 22); + this._toolstripmenuitem_sheet_settings_window.Text = "Settings Window..."; + // + // _statusbar_toolstripstatus_security + // + this._statusbar_toolstripstatus_security.Font = new System.Drawing.Font("Tahoma", 8F); + this._statusbar_toolstripstatus_security.Name = "_statusbar_toolstripstatus_security"; + this._statusbar_toolstripstatus_security.Size = new System.Drawing.Size(49, 17); + this._statusbar_toolstripstatus_security.Text = "Contract"; + this._statusbar_toolstripstatus_security.TextAlign = System.Drawing.ContentAlignment.MiddleRight; + // + // _statusbar_toolstripstatus_column + // + this._statusbar_toolstripstatus_column.Font = new System.Drawing.Font("Tahoma", 8F); + this._statusbar_toolstripstatus_column.Name = "_statusbar_toolstripstatus_column"; + this._statusbar_toolstripstatus_column.Size = new System.Drawing.Size(1065, 17); + this._statusbar_toolstripstatus_column.Spring = true; + this._statusbar_toolstripstatus_column.Text = "Data Column"; + this._statusbar_toolstripstatus_column.TextAlign = System.Drawing.ContentAlignment.MiddleRight; + // + // _statustrip_main + // + this._statustrip_main.GripMargin = new System.Windows.Forms.Padding(0); + this._statustrip_main.GripStyle = System.Windows.Forms.ToolStripGripStyle.Visible; + this._statustrip_main.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { + this._statusbar_toolstripstatus_security, + this._statusbar_toolstripstatus_task, + this._statusbar_toolstripstatus_quoterdata, + this._statusbar_toolstripstatus_column}); + this._statustrip_main.Location = new System.Drawing.Point(0, 678); + this._statustrip_main.Name = "_statustrip_main"; + this._statustrip_main.Size = new System.Drawing.Size(1133, 22); + this._statustrip_main.TabIndex = 1; + // + // _statusbar_toolstripstatus_task + // + this._statusbar_toolstripstatus_task.Font = new System.Drawing.Font("Tahoma", 8F); + this._statusbar_toolstripstatus_task.Name = "_statusbar_toolstripstatus_task"; + this._statusbar_toolstripstatus_task.Size = new System.Drawing.Size(0, 17); + // + // _statusbar_toolstripstatus_quoterdata + // + this._statusbar_toolstripstatus_quoterdata.BorderSides = System.Windows.Forms.ToolStripStatusLabelBorderSides.Left; + this._statusbar_toolstripstatus_quoterdata.Font = new System.Drawing.Font("Tahoma", 8F); + this._statusbar_toolstripstatus_quoterdata.Name = "_statusbar_toolstripstatus_quoterdata"; + this._statusbar_toolstripstatus_quoterdata.Size = new System.Drawing.Size(4, 17); + // + // _button_theo_acceptance_confirmation + // + this._button_theo_acceptance_confirmation.FlatStyle = System.Windows.Forms.FlatStyle.Flat; + this._button_theo_acceptance_confirmation.Location = new System.Drawing.Point(423, 386); + this._button_theo_acceptance_confirmation.Name = "_button_theo_acceptance_confirmation"; + this._button_theo_acceptance_confirmation.Size = new System.Drawing.Size(75, 23); + this._button_theo_acceptance_confirmation.TabIndex = 2; + this._button_theo_acceptance_confirmation.Text = "New Theos"; + this._button_theo_acceptance_confirmation.UseVisualStyleBackColor = true; + // + // _toolstripmenuitem_filter_strikes_with_pos_edge + // + this._toolstripmenuitem_filter_strikes_with_pos_edge.Name = "_toolstripmenuitem_filter_strikes_with_pos_edge"; + this._toolstripmenuitem_filter_strikes_with_pos_edge.Size = new System.Drawing.Size(269, 22); + this._toolstripmenuitem_filter_strikes_with_pos_edge.Text = "Strikes with Positive Edge"; + // + // NMSheetControl + // + this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.Controls.Add(this._button_theo_acceptance_confirmation); + this.Controls.Add(this._statustrip_main); + this.Controls.Add(this._menu_panel); + this.Name = "NMSheetControl"; + this.Size = new System.Drawing.Size(1133, 700); + this._menu_panel.ResumeLayout(false); + this._menu_panel.PerformLayout(); + this._contextmenustrip_main.ResumeLayout(false); + this._statustrip_main.ResumeLayout(false); + this._statustrip_main.PerformLayout(); + this.ResumeLayout(false); + this.PerformLayout(); + + } + + #endregion + + private System.Windows.Forms.Panel _menu_panel; + private System.Windows.Forms.Button _button_zoom_minus; + private System.Windows.Forms.Button _button_zoom_plus; + private System.Windows.Forms.Label _label_zoom; + private System.Windows.Forms.CheckBox _checkbox_show_gamma; + private System.Windows.Forms.CheckBox _checkbox_show_delta; + private System.Windows.Forms.CheckBox _checkbox_show_straddle; + private System.Windows.Forms.CheckBox _checkbox_show_vol_change; + private System.Windows.Forms.CheckBox _checkbox_show_vol; + private System.Windows.Forms.CheckBox _checkbox_show_position; + private System.Windows.Forms.CheckBox _checkbox_show_bbo; + private System.Windows.Forms.CheckBox _checkbox_show_vega; + private System.Windows.Forms.Button _button_settings; + private System.Windows.Forms.Button _button_spreads; + private System.Windows.Forms.Button _button_minimize_spreads; + private System.Windows.Forms.ContextMenuStrip _contextmenustrip_main; + private System.Windows.Forms.ToolStripMenuItem _toolstripmenuitem_atm; + private System.Windows.Forms.ToolStripSeparator _toolseperator_atm; + private System.Windows.Forms.ToolStripMenuItem _toolstripmenuitem_spread_summary; + private System.Windows.Forms.ToolStripMenuItem _toolstripmenuitem_minimize_spreads; + private System.Windows.Forms.ToolStripMenuItem _toolstripmenuitem_sheet_settings; + private System.Windows.Forms.ToolStripMenuItem _toolstripmenuitem_sheet_settings_window; + private System.Windows.Forms.ToolStripMenuItem _toolstripmenuitem_settings_delta; + private System.Windows.Forms.ToolStripMenuItem _toolstripmenuitem_settings_gamma; + private System.Windows.Forms.ToolStripMenuItem _toolstripmenuitem_settings_vega; + private System.Windows.Forms.ToolStripMenuItem _toolstripmenuitem_settings_bbo; + private System.Windows.Forms.ToolStripMenuItem _toolstripmenuitem_settings_vol; + private System.Windows.Forms.ToolStripMenuItem _toolstripmenuitem_settings_volchange; + private System.Windows.Forms.ToolStripMenuItem _toolstripmenuitem_settings_straddle; + private System.Windows.Forms.ToolStripSeparator _toolseperator_parameters; + private System.Windows.Forms.ToolStripMenuItem _toolstripmenuitem_settings_position; + private System.Windows.Forms.ToolStripSeparator _toolstripseperator_expirations; + private System.Windows.Forms.ToolStripMenuItem _toolstripmenuitem_settings_zoomout; + private System.Windows.Forms.ToolStripMenuItem _toolstripmenuitem_settings_zoomin; + private System.Windows.Forms.ToolStripSeparator _toolstripseperator_zoom; + private System.Windows.Forms.ToolStripMenuItem _toolstripmenuitem_card; + private System.Windows.Forms.ToolStripMenuItem _toolstripmenuitem_settings_show_quoteset_edgesize; + private System.Windows.Forms.ToolStripMenuItem _toolstripmenuitem_settings_show_quoteset_midprice; + private System.Windows.Forms.ToolStripStatusLabel _statusbar_toolstripstatus_security; + private System.Windows.Forms.ToolStripStatusLabel _statusbar_toolstripstatus_column; + private System.Windows.Forms.StatusStrip _statustrip_main; + private System.Windows.Forms.ToolStripMenuItem _toolstripmenuitem_sheet_column_settings; + private System.Windows.Forms.ToolStripStatusLabel _statusbar_toolstripstatus_quoterdata; + private System.Windows.Forms.ToolStripSeparator _toolseperator_quoteset_parameters; + private System.Windows.Forms.ToolStripSeparator _toolseperator_quotesets; + private System.Windows.Forms.ToolStripMenuItem _toolstripmenuitem_task_eye; + private System.Windows.Forms.ToolStripMenuItem _toolstripmenuitem_task_eye_add_buys_to_task; + private System.Windows.Forms.ToolStripSeparator _toolstripseperator_task_eye; + private System.Windows.Forms.ToolStripStatusLabel _statusbar_toolstripstatus_task; + private System.Windows.Forms.ToolStripSeparator _toolstripseperator_task_eye_create; + private System.Windows.Forms.ToolStripMenuItem _toolstripmenuitem_task_eye_switch_all_off; + private System.Windows.Forms.ToolStripSeparator _toolseperator_task_ee; + private System.Windows.Forms.ToolStripMenuItem _toolstripmenuitem_settings_show_task_ee_data; + private System.Windows.Forms.ToolStripMenuItem _toolstripmenuitem_task_eye_add_sells_to_task; + private System.Windows.Forms.ToolStripMenuItem _toolstripmenuitem_task_eye_add_buys_and_sells_to_task; + private System.Windows.Forms.ToolStripSeparator _toolstripseperator_filter; + private System.Windows.Forms.ToolStripMenuItem _toolstripmenuitem_filter; + private System.Windows.Forms.ToolStripMenuItem _toolstripmenuitem_filter_strikes_in_tasks; + private System.Windows.Forms.ToolStripMenuItem _toolstripmenuitem_filter_on_strikes_in_tasks; + private System.Windows.Forms.ToolStripMenuItem _toolstripmenuitem_task_manage_templates; + private System.Windows.Forms.ToolStripMenuItem _toolstripmenuitem_task_quoter; + private System.Windows.Forms.ToolStripMenuItem _toolstripmenuitem_task_quoter_add_buys_to_task; + private System.Windows.Forms.ToolStripMenuItem _toolstripmenuitem_task_quoter_add_sells_to_task; + private System.Windows.Forms.ToolStripMenuItem _toolstripmenuitem_task_quoter_add_buys_and_sells_to_task; + private System.Windows.Forms.ToolStripSeparator _toolstripseperator_task_quoter_create; + private System.Windows.Forms.ToolStripMenuItem _toolstripmenuitem_settings_show_task_quoter_data; + private System.Windows.Forms.ToolStripMenuItem _toolstripmenuitem_task_override_edge; + private System.Windows.Forms.ToolStripMenuItem _toolstripmenuitem_task_override_size; + private System.Windows.Forms.ToolStripMenuItem _toolstripmenuitem_task_enter_edge; + private System.Windows.Forms.ToolStripSeparator _toolstripseparator_task_edge; + private System.Windows.Forms.ToolStripMenuItem _toolstripmenuitem_task_undo_edge_override; + private System.Windows.Forms.ToolStripMenuItem _toolstripmenuitem_task_enter_size; + private System.Windows.Forms.ToolStripSeparator _toolstripseparator_task_size; + private System.Windows.Forms.ToolStripMenuItem _toolstripmenuitem_task_undo_size_override; + private System.Windows.Forms.ToolStripMenuItem _toolstrip_menuitem_save_data_to_file; + private System.Windows.Forms.ToolStripSeparator _toolstripseperator_export_data; + private System.Windows.Forms.Button _button_theo_acceptance_confirmation; + private System.Windows.Forms.ToolStripMenuItem _toolstripmenuitem_filter_strikes_with_pos_edge; + } +} \ 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 new file mode 100644 index 000000000..5bfeb047e --- /dev/null +++ b/src/client/spark/NMSheets/UIComponents/MainSheet/NMSheetControl.cs @@ -0,0 +1,832 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Drawing; +using System.Data; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; +using mbts.ui; +using mbts.ui.dpi; +using mbts.ui.shell; +using BCG.Utilities.General; + +namespace BCG { + public partial class NMSheetControl : UserControl { + /// bb + private ThreadedBlackboard _threaded_bb; + /// in tags + private object _out_bb_sheet_setting_tag, + _in_bb_contract_data_tag, + _in_bb_spreadui_config_tag; + //_in_bb_trader_risk_summary_tag; + /// out tags + private object _out_bb_viewable_area_tag; + /// ui controls + public NMSheetTheoGridWithScrollbars _theo_grid; + private NMSheetExpirationHeaderControlStrip _expiration_header_strip; + private NMSheetDriverControlStrip _driver_control_strip; + // private System.Windows.Forms.Integration.ElementHost _element_host_expiration_navigator; + // private System.Windows.Forms.Integration.ElementHost _element_host_strike_navigator; + // private StrikeNavigatorControl _strike_navigator; + private NMSheetShellWindow _parent_window; + //private ButtonListControl _button_list_control_exp_navigator; + + private readonly string _req_id = Guid.NewGuid().ToString(); + private readonly List _nmsheet_symbol_list; + + private NMSheetDataCoalescer _coalescer; + private System.Windows.Forms.Timer _windows_timer; + private string _title_prefix = String.Empty; + + private NMSheetSettings _settings; + public NMSheetDisplayFormatter _formatter; + internal NMSheetData _sheet_data; + private NMSheetExpiration[] _sorted_expirations = new NMSheetExpiration[] { }; + private NMSheetTheoGrid.GridCell _last_rightclick_cell = null; + + private readonly int _thread_id = System.Threading.Thread.CurrentThread.ManagedThreadId; + private readonly bool _show_settings_header; + private readonly bool _show_expiration_navigator; + private readonly bool _show_expiration_atm_header; + private readonly bool _show_strike_navigator; + private readonly bool _show_statusbar; + private PerfStatsLogger _recorder = new PerfStatsLogger(); + private readonly Graphics _graphics = Graphics.FromImage(new Bitmap(1, 1)); + + private readonly bool _api_tasking_enabled = false;// mbts.config.Configuration.get().enabled; + + private NMSheetControl() { InitializeComponent(); } + + public NMSheetControl(Blackboard bb, NMSheetShellWindow parent_window, NMSheetSettings settings) + : this() { + _parent_window = parent_window; + _settings = settings; + _show_strike_navigator = settings.setting_strike_navigator.show_strike_navigator; + _show_settings_header = _settings.setting_layout.show_settings_header; + _show_expiration_navigator = _settings.setting_layout.show_exp_navigator; + _show_expiration_atm_header = _settings.setting_layout.show_exp_atm_header; + _show_statusbar = settings.setting_status_bar.show_statusbar; + _nmsheet_symbol_list = settings.setting_option_list; + _init_bb_setup(bb); + _init_controls(); + _coalescer = new NMSheetDataCoalescer(_threaded_bb, _req_id, _nmsheet_symbol_list, settings); + _set_new_settings(settings); + _init_task_ui(); + _init_export_data(); + _init_theo_acceptance_button(); + _start(); + } + + #region Initialization + + private void _init_bb_setup(Blackboard bb) { + _in_bb_contract_data_tag = new ContractTags.SystemContractsTag(); + _out_bb_sheet_setting_tag = new NMSheetTags.NMSheetSettingsTag(_req_id); + _in_bb_spreadui_config_tag = new SpreadWindowSettingsTag(); + _out_bb_viewable_area_tag = new NMSheetTags.NMSheetViewableAreaTag(_req_id); + //_in_bb_trader_risk_summary_tag = new TraderRiskSummaryDispenser.TraderRiskSummaryDataTag(_req_id); + _threaded_bb = new ThreadedBlackboard(String.Format("{0}_{1}", "NMOptionSheet", _req_id), bb, MasterWorker.getInstance(false), _react_to_bb, + _in_bb_spreadui_config_tag, + //_in_bb_trader_risk_summary_tag, + new PriceSettingsTag(), + new ClickTradeSettingsTag(), + _in_bb_contract_data_tag + // new VolSurfaceBlackboardTags.VolSurfaceTheoAcceptanceConfirmationTag(), + // new VolSurfaceBlackboardTags.VolSurfaceTheoAlertTag() + ); + } + + private void _init_controls() { + this.BackColor = BTSColors.UI.default_background; + _statustrip_main.BackColor = BTSColors.UI.default_background; + + /// title + _title_prefix = String.Empty; + foreach (NMSheetSymbol s in _nmsheet_symbol_list) + _title_prefix += String.Format("{0}{1}", (String.IsNullOrEmpty(_title_prefix) ? String.Empty : " "), s.option_name); + _title_prefix = String.Format("Sheets ( {0} )", _title_prefix); + + /// menu panel + int running_y = 0; + int running_x = 0; + Size top_menu_default_size = _menu_panel.Size; + if (_show_settings_header) { + running_y += _menu_panel.Bottom; + _menu_panel.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; + _button_spreads.Click += (s, e) => { _threaded_bb.sec_thread_write(new SpreadSummaryDisplayTag(), null); }; + /// preferances in menu panel + _button_settings.Click += (snd, e) => { _launch_setting_form(); }; + /// minimize spreads + _button_minimize_spreads.Click += (s, e) => { _threaded_bb.sec_thread_write(new SpreadWindowMinimizeTag(), true); }; + /// zoom in menu panel + _button_zoom_plus.Click += (s, e) => { _handle_zoom(true); }; + _button_zoom_minus.Click += (s, e) => { _handle_zoom(false); }; + /// menu panel check boxes + _sync_display_checkbox_states_with_settings(); + _sync_toolmenuitems_states_with_settings(); + _assign_display_checkboxes_events(); + } else { + _menu_panel.Height = 0; + _menu_panel.Visible = false; + } + /// expiration navigator + // if (_show_expiration_navigator) { + // _element_host_expiration_navigator = new System.Windows.Forms.Integration.ElementHost(); + // _element_host_expiration_navigator.Size = top_menu_default_size; + // _element_host_expiration_navigator.Location = new Point(_menu_panel.Left, running_y); + // _element_host_expiration_navigator.Anchor = AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Top; + // Controls.Add(_element_host_expiration_navigator); + // _button_list_control_exp_navigator = new ButtonListControl(new List(), + // System.Windows.Controls.Orientation.Horizontal, + // (nmsheet_exp) => { _navigate_to_expiration((NMSheetExpiration)nmsheet_exp); }, + // new System.Windows.Thickness(8, 4, 0, 0), + // o => { + // if (o is NMSheetExpiration) { + // bool condense_exps = _settings != null && _settings.setting_layout.condense_navigator_expirations.Value; + // NMSheetExpiration exp = o as NMSheetExpiration; + // return condense_exps ? mbts.ui.utility.ExpirationFormatter.format_option_expiration_condensed(exp.option_name, exp.option_expiration, true, false, false) : o.ToString(); + // } else + // return o.ToString(); + // }); + // _element_host_expiration_navigator.Child = _button_list_control_exp_navigator; + // running_y += _element_host_expiration_navigator.Height; + // } + + // if (_show_strike_navigator) { + // _strike_navigator = new StrikeNavigatorControl(_settings); + // _strike_navigator.strike_click = new StrikeNavigatorControl.StrikeClick(async (strike, height) => { + // double ratio = (double)height / (double)_theo_grid.Height; + // _theo_grid.theo_grid.navigate_to_strike(strike, ratio); + // await Task.Yield(); + // update_visible_strike_range(); + // }); + // _element_host_strike_navigator = new System.Windows.Forms.Integration.ElementHost() { Child = _strike_navigator }; + // _element_host_strike_navigator.Location = new Point(running_x, running_y); + // _element_host_strike_navigator.AutoSize = true; + // //_element_host_strike_navigator.Anchor = AnchorStyles.Left | AnchorStyles.Top | AnchorStyles.Bottom; + // Controls.Add(_element_host_strike_navigator); + // running_x += _element_host_strike_navigator.Width; + // } + + /// expiration header + if (_show_expiration_atm_header) { + _expiration_header_strip = new NMSheetExpirationHeaderControlStrip(_req_id, _threaded_bb, (nmsheet_exp) => { _navigate_to_atm(nmsheet_exp); }); + // HighDPI - Need to multiply the magic number 24 by the dpi_ratio + // so that the driver control is not chopped off if the vol control + // is visible + _expiration_header_strip.Size = new Size(Width, (24).MultipliedByDPIRatio()); + _expiration_header_strip.Location = new Point(_menu_panel.Left, running_y); + _expiration_header_strip.Anchor = AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Top; + Controls.Add(_expiration_header_strip); + running_y += _expiration_header_strip.Height; + } + + /// driver strip + _driver_control_strip = new NMSheetDriverControlStrip(_req_id, _nmsheet_symbol_list, _threaded_bb); + _driver_control_strip.Size = new Size(Width, (24).MultipliedByDPIRatio()); + _driver_control_strip.Location = new Point(running_x, running_y); + _driver_control_strip.Anchor = AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Top; + Controls.Add(_driver_control_strip); + + SizeChanged += new EventHandler((o, e) => { + if (_sheet_data != null) + _set_strike_navigator(); + }); + + /// status bar + if (!_show_statusbar) { + Controls.Remove(_statustrip_main); + _statustrip_main.Dispose(); + } + + /// main grid + _theo_grid = new NMSheetTheoGridWithScrollbars(this); + _theo_grid.Size = new Size(Width - (0 /*_show_strike_navigator ? _element_host_strike_navigator.Width : 0*/), + Height - _driver_control_strip.Bottom - (_show_statusbar ? _statustrip_main.Height : 0)); + _theo_grid.Location = new Point(running_x, _driver_control_strip.Bottom); + _theo_grid.Anchor = AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Top | AnchorStyles.Bottom; + _theo_grid.theo_grid.init(); + + _theo_grid.theo_grid.onDoubleClick += _handle_theo_grid_double_click; + _theo_grid.theo_grid.onMouseUp += _handle_theo_grid_mouse_up; + _theo_grid.theo_grid.onMouseUpOutsideBitmap += _handle_theo_grid_mouse_up_outside_bitmap; + _theo_grid.theo_grid.onGesture += _handle_gesture; + _theo_grid.theo_grid.onDisplayChange += _handle_theo_grid_display_change; + _theo_grid.theo_grid.onMouseMove += _handle_theo_grid_mouse_move; + Controls.Add(_theo_grid); + + /// context menu + _assign_toolstripmenuitem_events(); + + /// windows timer + _windows_timer = new Timer(components); + _windows_timer.Enabled = true; + _windows_timer.Interval = 20; + _windows_timer.Tick += _windows_timer_tick; + _toolstripmenuitem_card.Visible = false; + /// status bar + } + + private void _assign_display_checkboxes_events() { + /// This sounds lame : MouseUp is used instead of CheckStateChanged because setting the checked state programmatically + /// in _set_check_box_state was raising events + _checkbox_show_delta.MouseUp += (s, e) => { _get_checkbox_display_state_and_publish(s as CheckBox, NMSheetColumnName.call_delta, NMSheetColumnName.put_delta); }; + _checkbox_show_gamma.MouseUp += (s, e) => { _get_checkbox_display_state_and_publish(s as CheckBox, NMSheetColumnName.call_gamma, NMSheetColumnName.put_gamma); }; + _checkbox_show_vega.MouseUp += (s, e) => { _get_checkbox_display_state_and_publish(s as CheckBox, NMSheetColumnName.call_vega, NMSheetColumnName.put_vega); }; + _checkbox_show_bbo.MouseUp += (s, e) => { + _get_checkbox_display_state_and_publish(s as CheckBox, NMSheetColumnName.call_bid_price, NMSheetColumnName.call_bid_size, + NMSheetColumnName.call_ask_price, NMSheetColumnName.call_ask_size, + NMSheetColumnName.put_bid_price, NMSheetColumnName.put_bid_size, + NMSheetColumnName.put_ask_price, NMSheetColumnName.put_ask_size); + }; + _checkbox_show_position.MouseUp += (s, e) => { _get_checkbox_display_state_and_publish(s as CheckBox, NMSheetColumnName.call_position, NMSheetColumnName.put_position); }; + _checkbox_show_vol.MouseUp += (s, e) => { _get_checkbox_display_state_and_publish(s as CheckBox, NMSheetColumnName.vol); }; + _checkbox_show_vol_change.MouseUp += (s, e) => { _get_checkbox_display_state_and_publish(s as CheckBox, NMSheetColumnName.vol_change); }; + _checkbox_show_straddle.MouseUp += (s, e) => { _get_checkbox_display_state_and_publish(s as CheckBox, NMSheetColumnName.straddle); }; + } + + private void _assign_toolstripmenuitem_events() { + _toolstripmenuitem_spread_summary.Click += (s, e) => { _threaded_bb.sec_thread_write(new SpreadSummaryDisplayTag(), null); }; + _toolstripmenuitem_card.Click += (s, e) => { + object[] sec_array = (object[])_toolstripmenuitem_card.Tag; + NMSheetExpiration nmsheet_exp = sec_array[0] as NMSheetExpiration; + double strike = (double)sec_array[1]; + bool is_call = (bool)sec_array[2]; + // SpreadSpec spec = new SpreadSpec(new OptionContractPosition[] { new OptionContractPosition(new OptionContract(nmsheet_exp.option_exchange, nmsheet_exp.nmsheet_symbol.option_name, nmsheet_exp.option_expiration, strike, is_call), 1.0, null) }); + // System.Windows.Window qc_view = new TradeEntryCard(); + // QuickCardViewModel qc_vm = new QuickCardViewModel(spec, nmsheet_exp.nmsheet_symbol.option_exchange); + // qc_view.DataContext = qc_vm; + // QuickCardDataSource qc_model = new QuickCardDataSource(_threaded_bb, nmsheet_exp.nmsheet_symbol.option_exchange, spec, qc_vm); + // qc_view.Closing += (qc_v_s, qc_v_e) => { qc_model.Dispose(); }; + // qc_view.Show(); + }; + _toolstripmenuitem_minimize_spreads.Click += (s, e) => { _threaded_bb.sec_thread_write(new SpreadWindowMinimizeTag(), true); }; + _toolstripmenuitem_sheet_settings_window.Click += (s, e) => { _launch_setting_form(); }; + _toolstripmenuitem_atm.Click += (s, e) => { _navigate_to_atm(_last_rightclick_cell.expiration); }; + + _toolstripmenuitem_settings_delta.Click += (s, e) => { _get_toolstripmenuitem_display_state_and_publish(_toolstripmenuitem_settings_delta, NMSheetColumnName.call_delta, NMSheetColumnName.put_delta); }; + _toolstripmenuitem_settings_gamma.Click += (s, e) => { _get_toolstripmenuitem_display_state_and_publish(_toolstripmenuitem_settings_gamma, NMSheetColumnName.call_gamma, NMSheetColumnName.put_gamma); }; + _toolstripmenuitem_settings_vega.Click += (s, e) => { _get_toolstripmenuitem_display_state_and_publish(_toolstripmenuitem_settings_vega, NMSheetColumnName.call_vega, NMSheetColumnName.put_vega); }; + _toolstripmenuitem_settings_bbo.Click += (s, e) => { + _get_toolstripmenuitem_display_state_and_publish(_toolstripmenuitem_settings_bbo, NMSheetColumnName.call_bid_price, NMSheetColumnName.call_bid_size, + NMSheetColumnName.call_ask_price, NMSheetColumnName.call_ask_size, + NMSheetColumnName.put_bid_price, NMSheetColumnName.put_bid_size, + NMSheetColumnName.put_ask_price, NMSheetColumnName.put_ask_size); + }; + _toolstripmenuitem_settings_position.Click += (s, e) => { _get_toolstripmenuitem_display_state_and_publish(_toolstripmenuitem_settings_position, NMSheetColumnName.call_position, NMSheetColumnName.put_position); }; + _toolstripmenuitem_settings_vol.Click += (s, e) => { _get_toolstripmenuitem_display_state_and_publish(_toolstripmenuitem_settings_vol, NMSheetColumnName.vol); }; + _toolstripmenuitem_settings_volchange.Click += (s, e) => { _get_toolstripmenuitem_display_state_and_publish(_toolstripmenuitem_settings_volchange, NMSheetColumnName.vol_change); }; + _toolstripmenuitem_settings_straddle.Click += (s, e) => { _get_toolstripmenuitem_display_state_and_publish(_toolstripmenuitem_settings_straddle, NMSheetColumnName.straddle); }; + _toolstripmenuitem_settings_zoomout.Click += (s, e) => { _handle_zoom(false); }; + _toolstripmenuitem_settings_zoomin.Click += (s, e) => { _handle_zoom(true); }; + _toolstripmenuitem_sheet_column_settings.Click += (s, e) => { _launch_setting_form(_toolstripmenuitem_sheet_column_settings.Tag); }; + _toolstripmenuitem_filter_strikes_with_pos_edge.Click += (s, e) => { + _settings.setting_filter.filter_positive_edge_strikes = !_settings.setting_filter.filter_positive_edge_strikes; + _set_new_settings(_settings); + _theo_grid.theo_grid.scroll_to_point(Point.Empty); + }; + _toolstripmenuitem_filter_strikes_in_tasks.Click += (s, e) => { + _settings.setting_filter.filter_ee_task_strikes = !_settings.setting_filter.filter_ee_task_strikes; + _set_new_settings(_settings); + _theo_grid.theo_grid.scroll_to_point(Point.Empty); + }; + _toolstripmenuitem_filter_on_strikes_in_tasks.Click += (s, e) => { + _settings.setting_filter.filter_on_ee_task_strikes = !_settings.setting_filter.filter_on_ee_task_strikes; + _set_new_settings(_settings); + _theo_grid.theo_grid.scroll_to_point(Point.Empty); + }; + } + + private void _sync_display_checkbox_states_with_settings() { + _set_check_box_state(_checkbox_show_delta, 2, NMSheetSettingUtilities.no_of_visible_cols(_settings, NMSheetColumnName.call_delta, NMSheetColumnName.put_delta)); + _set_check_box_state(_checkbox_show_gamma, 2, NMSheetSettingUtilities.no_of_visible_cols(_settings, NMSheetColumnName.call_gamma, NMSheetColumnName.put_gamma)); + _set_check_box_state(_checkbox_show_vega, 2, NMSheetSettingUtilities.no_of_visible_cols(_settings, NMSheetColumnName.call_vega, NMSheetColumnName.put_vega)); + _set_check_box_state(_checkbox_show_bbo, 8, NMSheetSettingUtilities.no_of_visible_cols(_settings, NMSheetColumnName.call_bid_price, NMSheetColumnName.call_bid_size, NMSheetColumnName.call_ask_price, NMSheetColumnName.call_ask_size, + NMSheetColumnName.put_bid_price, NMSheetColumnName.put_bid_size, NMSheetColumnName.put_ask_price, NMSheetColumnName.put_ask_size)); + _set_check_box_state(_checkbox_show_position, 2, NMSheetSettingUtilities.no_of_visible_cols(_settings, NMSheetColumnName.call_position, NMSheetColumnName.put_position)); + _set_check_box_state(_checkbox_show_vol, 1, NMSheetSettingUtilities.no_of_visible_cols(_settings, NMSheetColumnName.vol)); + _set_check_box_state(_checkbox_show_vol_change, 1, NMSheetSettingUtilities.no_of_visible_cols(_settings, NMSheetColumnName.vol_change)); + _set_check_box_state(_checkbox_show_straddle, 1, NMSheetSettingUtilities.no_of_visible_cols(_settings, NMSheetColumnName.straddle)); + } + + private void _sync_toolmenuitems_states_with_settings() { + _set_toolstripmenuitem_state(_toolstripmenuitem_settings_delta, 2, NMSheetSettingUtilities.no_of_visible_cols(_settings, NMSheetColumnName.call_delta, NMSheetColumnName.put_delta)); + _set_toolstripmenuitem_state(_toolstripmenuitem_settings_gamma, 2, NMSheetSettingUtilities.no_of_visible_cols(_settings, NMSheetColumnName.call_gamma, NMSheetColumnName.put_gamma)); + _set_toolstripmenuitem_state(_toolstripmenuitem_settings_vega, 2, NMSheetSettingUtilities.no_of_visible_cols(_settings, NMSheetColumnName.call_vega, NMSheetColumnName.put_vega)); + _set_toolstripmenuitem_state(_toolstripmenuitem_settings_bbo, 8, NMSheetSettingUtilities.no_of_visible_cols(_settings, NMSheetColumnName.call_bid_price, NMSheetColumnName.call_bid_size, NMSheetColumnName.call_ask_price, NMSheetColumnName.call_ask_size, + NMSheetColumnName.put_bid_price, NMSheetColumnName.put_bid_size, NMSheetColumnName.put_ask_price, NMSheetColumnName.put_ask_size)); + _set_toolstripmenuitem_state(_toolstripmenuitem_settings_position, 2, NMSheetSettingUtilities.no_of_visible_cols(_settings, NMSheetColumnName.call_position, NMSheetColumnName.put_position)); + _set_toolstripmenuitem_state(_toolstripmenuitem_settings_vol, 1, NMSheetSettingUtilities.no_of_visible_cols(_settings, NMSheetColumnName.vol)); + _set_toolstripmenuitem_state(_toolstripmenuitem_settings_volchange, 1, NMSheetSettingUtilities.no_of_visible_cols(_settings, NMSheetColumnName.vol_change)); + _set_toolstripmenuitem_state(_toolstripmenuitem_settings_straddle, 1, NMSheetSettingUtilities.no_of_visible_cols(_settings, NMSheetColumnName.straddle)); + + IEnumerable quoteset_cols = NMSheetQuoterHelper.get_quoteset_edge_size_cols(); + _set_toolstripmenuitem_state(_toolstripmenuitem_settings_show_quoteset_edgesize, quoteset_cols.Count(), NMSheetSettingUtilities.no_of_visible_cols(_settings, quoteset_cols.ToArray())); + IEnumerable quoteset_final_cols = NMSheetQuoterHelper.get_quoter_set_edge_size_cols(); + _set_toolstripmenuitem_state(_toolstripmenuitem_settings_show_quoteset_midprice, 2, NMSheetSettingUtilities.no_of_visible_cols(_settings, NMSheetColumnName.call_quoteset_mid_price, NMSheetColumnName.put_quoteset_mid_price)); + IEnumerable ee_cols = NMSheetSettingColumnOrganization.get_cols_for_type(NMSheetColumnType.EE); + _set_toolstripmenuitem_state(_toolstripmenuitem_settings_show_task_ee_data, ee_cols.Count(), NMSheetSettingUtilities.no_of_visible_cols(_settings, ee_cols.ToArray())); + IEnumerable quoter_cols = NMSheetSettingColumnOrganization.get_cols_for_type(NMSheetColumnType.Quoter); + _set_toolstripmenuitem_state(_toolstripmenuitem_settings_show_task_quoter_data, quoter_cols.Count(), NMSheetSettingUtilities.no_of_visible_cols(_settings, quoter_cols.ToArray())); + } + + private void _get_checkbox_display_state_and_publish(CheckBox checkbox, params NMSheetColumnName[] col_name_list) { + NMSheetSettingUtilities.set_visibility_state(_settings, checkbox.Checked, col_name_list); + _set_new_settings(_settings); + } + + private void _get_toolstripmenuitem_display_state_and_publish(ToolStripMenuItem toolstripmenuitem, params NMSheetColumnName[] col_name_list) { + NMSheetSettingUtilities.set_visibility_state(_settings, !toolstripmenuitem.Checked, col_name_list); + _set_new_settings(_settings); + } + + private static void _set_check_box_state(CheckBox cb, int rep_col_count, int vis_col_count) { + cb.CheckState = vis_col_count == 0 ? CheckState.Unchecked : (vis_col_count == rep_col_count ? CheckState.Checked : CheckState.Indeterminate); + } + + private static void _set_toolstripmenuitem_state(ToolStripMenuItem item, int rep_col_count, int vis_col_count) { + item.CheckState = vis_col_count == 0 ? CheckState.Unchecked : (vis_col_count == rep_col_count ? CheckState.Checked : CheckState.Indeterminate); + } + + private void _start() { + _write_title(); + _windows_timer.Start(); + } + #endregion + + private void _launch_setting_form(object args = null) { + mbts.spark.SystemContractData contract_data = _threaded_bb.sec_thread_retrieve_from_cache(_in_bb_contract_data_tag) as mbts.spark.SystemContractData ?? mbts.spark.SystemContractData.empty; + System.Windows.Threading.Dispatcher ui_thread_dispatcher = System.Windows.Threading.Dispatcher.CurrentDispatcher; + Action settings_form_cb = (new_settings) => { ui_thread_dispatcher.InvokeAsync(() => { _set_new_settings(new_settings); }); }; + System.Windows.Application.Current.Dispatcher.InvokeAsync(() => { + NMSheetSettingsForm setting_form = new NMSheetSettingsForm(_settings.Clone() as NMSheetSettings, _nmsheet_symbol_list, contract_data, + settings_form_cb, _threaded_bb); + if (args != null && args is NMSheetColumnName) + setting_form.go_to_column((NMSheetColumnName)args); + setting_form.ShowDialog(); + }); + } + + private static string _get_summary_expiration_text(NMSheetExpiration nmsheet_exp) { + return mbts.ui.utility.ExpirationFormatter.format_symbol_expiration_standard(bts.api.SecurityType.Option, nmsheet_exp.option_name, nmsheet_exp.option_expiration, true); + } + + private void _react_to_bb(object tag, object value) { + // if (_in_bb_trader_risk_summary_tag.Equals(tag)) + // _write_title(); + } + + /// Every time when the settings change, this is called + private void _send_risk_request() { + /// this could do things better by caching the last request + /// and not sending redundant requests (i know the req dispenser + /// is doing the right think + // TODO + // NMSheetSettingLayout layout = _settings.setting_layout; + // if (layout.trader_risk_input_complete() && layout.show_trader_risk_in_title()) + // _threaded_bb.sec_thread_write(new TraderRiskSummaryDispenser.TraderRiskSummaryRequestTag(), + // new TraderRiskSummaryDispenser.TraderRiskSummaryRequest(_req_id, layout.risk_account, layout.risk_in_terms_of)); + // else + // _threaded_bb.sec_thread_write(new TraderRiskSummaryDispenser.TradeRiskSummaryKillTag(), + // new TraderRiskSummaryDispenser.TraderRiskSummaryKill(_req_id)); + } + + #region Title + private void _write_title() { _parent_window.Title = _form_title(); } + + private string _form_title() { + string one_five_text = _get_onefive_text(), risk_text = _get_trader_risk_text(); + one_five_text = String.IsNullOrEmpty(one_five_text) ? String.Empty : String.Format(" [1-5 {0}]", one_five_text); + risk_text = String.IsNullOrEmpty(risk_text) ? String.Empty : String.Format(" [{0}]", risk_text); + return String.Format("{0}{1}{2}", _title_prefix, one_five_text, risk_text); + } + + private string _get_onefive_text() { + string onefive_text = String.Empty; + // if (_settings != null && _settings.setting_layout != null && _settings.setting_layout.show_onefive_in_title.Value) { + // foreach (NMSheetSymbol s in _nmsheet_symbol_list) { + // object dp_obj = _threaded_bb.sec_thread_retrieve_from_cache(new OneFiveValueTag(s.option_name)); + // if (dp_obj != null && dp_obj is DataPacket) { + // DataPacket dp = dp_obj as DataPacket; + // if (dp.newRows.Count > 0) { + // double one_five = BlueDataUtility.get_row_value(BlueDataUtility.extractRow(dp.newRows, 0), "scalarData", 0.0); + // onefive_text += String.Format(" {0} {1}", s.option_name, one_five.ToString("F2")); + // } + // } + // } + // } + return onefive_text.Trim(); + } + + private string _get_trader_risk_text() { + string risk_text = String.Empty; + // NMSheetSettingLayout layout = _settings.setting_layout; + // if (layout.trader_risk_input_complete() && layout.show_trader_risk_in_title()) { + // TraderRiskSummaryDispenser.TraderRiskSummaryData risk_data = _threaded_bb.sec_thread_retrieve_from_cache(_in_bb_trader_risk_summary_tag) as TraderRiskSummaryDispenser.TraderRiskSummaryData; + // if (risk_data != null) + // risk_text = String.Format("{0}{1}{2}{3}{4}", _format_title_greek("PNL", layout.show_day_pnl_in_title.Value, risk_data.theo_pnl), + // _format_title_greek(CommonGUIUtilities.delta_str, layout.show_day_delta_in_title.Value, risk_data.delta), + // _format_title_greek(CommonGUIUtilities.gamma_str, layout.show_day_gamma_in_title.Value, risk_data.gamma), + // _format_title_greek(CommonGUIUtilities.vega_str, layout.show_day_vega_in_title.Value, risk_data.vega), + // _format_title_greek(CommonGUIUtilities.theta_str, layout.show_day_theta_in_title.Value, risk_data.theta)); + // } + return risk_text.Trim(); + } + + private static string _format_title_greek(string greek_name, bool visible, double val) { + return visible ? String.Format(" {0} {1}", greek_name, val.ToString("F2")) : String.Empty; + } + + private void _set_new_settings(NMSheetSettings new_settings) { + _last_geo_lo_info = null; + _settings = new_settings; + _formatter = new NMSheetDisplayFormatter(_settings); + _sync_display_checkbox_states_with_settings(); + _sync_toolmenuitems_states_with_settings(); + _respond_to_data(); + _write_title(); // this is done so that the settings that are reflected on the title dont have to wait for the next input (ex hide theta, which would not generate an update) + _send_risk_request(); + _threaded_bb.sec_thread_write(_out_bb_sheet_setting_tag, _settings); + } + #endregion + + #region Public Accessors + + public NMSheetSettings get_setting() { return _settings; } + + public void get_settings(out NMSheetSettings settings, out NMSheetDisplayFormatter formatter) { + settings = _settings; + formatter = _formatter; + } + + public bool is_visible { get { return _parent_window.is_visibile; } } + + public NMSheetTheoGrid grid { get { return _theo_grid.theo_grid; } } + + #endregion + + #region Events + + private void _handle_theo_grid_mouse_move(NMSheetTheoGrid.GridCell cell) { + _on_statusbar_mousemove(cell); + } + + private double[] _grid_locations; + private void _handle_theo_grid_display_change(object sender, object[] args) { + double[] grid_locations = new double[] + { + Math.Min((double)args[0],1), + Math.Min((double)args[1],1), + Math.Min((double)args[2],1), + Math.Min((double)args[3],1), + Convert.ToDouble (args[4]), + Convert.ToDouble (args[5]) + }; + _grid_locations = _grid_locations ?? new double[grid_locations.Length]; + bool grid_coords_unchanged = true; + for (int i = 0; i < grid_locations.Length; i++) grid_coords_unchanged &= _grid_locations[i] == grid_locations[i]; + if (!grid_coords_unchanged) { + _grid_locations = grid_locations; + _threaded_bb.sec_thread_write(_out_bb_viewable_area_tag, grid_locations); + } + } + + private void _add_spread_leg(NMSheetExpiration nmsheet_expiration, + double option_strike, + bool is_call, + 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)); + // } + // } + } + + private void _handle_spread_initialization(NMSheetTheoGrid.GridCell cell, int leg_size) { + 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); + } + } + + private bool _single_click_spread = true; + private void _handle_theo_grid_double_click(Pair p) { + // SpreadWindowSettings spread_window_settings = ShellUserSettingsHelper.get_spread_window_settings(_threaded_bb); + if (p.first == System.Windows.Forms.MouseButtons.Left && !_single_click_spread /*spread_window_settings.layout_settings.spread_initialization_action == SpreadInitialization.DoubleClickSystem*/) { + //SharedTimer.log("SpreadDraw", "Spread initialized", "SpreadDisplayPerformance"); + _handle_spread_initialization(p.second, 1); + } + } + + private void _handle_theo_grid_mouse_up(Pair p) { + MouseButtons button = p.first; + NMSheetTheoGrid.GridCell cell = p.second; + /// single click + // SpreadWindowSettings spread_window_settings = ShellUserSettingsHelper.get_spread_window_settings(_threaded_bb); + if (button == System.Windows.Forms.MouseButtons.Right) { + _handle_right_click(cell); + } else if (button == System.Windows.Forms.MouseButtons.Middle) { + _navigate_to_atm(cell.expiration); + } else if (button == System.Windows.Forms.MouseButtons.Left) { + if (_single_click_spread /* spread_window_settings.layout_settings.spread_initialization_action == SpreadInitialization.SingleClickSystem*/) { + //SharedTimer.log("SpreadDraw", "Spread initialized", "SpreadDisplayPerformance"); + _handle_spread_initialization(cell, 1); + } + } + } + + private void _handle_gesture(Tuple args) { + // disabling gestures! + // SpreadWindowSettings spread_window_settings = ShellUserSettingsHelper.get_spread_window_settings(_threaded_bb); + // if (spread_window_settings.layout_settings.spread_initialization_action == SpreadInitialization.RightUpSwipeBuyRightDownSwipeSell) { + // if (args.Item1 == NMSheetTheoGrid.Gesture.Up) { + // //SharedTimer.log("SpreadDraw", "Spread initialized", "SpreadDisplayPerformance"); + // _handle_spread_initialization(args.Item4, 1); + // } else if (args.Item1 == NMSheetTheoGrid.Gesture.Down) { + // //SharedTimer.log("SpreadDraw", "Spread initialized", "SpreadDisplayPerformance"); + // _handle_spread_initialization(args.Item4, 1); + // } + // } + } + + #region Rightclick/Context menu + private void _handle_right_click(NMSheetTheoGrid.GridCell cell) { + _last_rightclick_cell = cell; + foreach (ToolStripItem i in _contextmenustrip_main.Items) { + if (i.Tag != null && i.Tag is NMSheetExpiration) { + NMSheetExpiration this_menu_exp = i.Tag as NMSheetExpiration; + if (i.Font.Bold) + i.Font = new Font(i.Font.FontFamily, i.Font.Size, FontStyle.Regular); + if (this_menu_exp.Equals(_last_rightclick_cell.expiration)) + i.Font = new Font(i.Font.FontFamily, i.Font.Size, FontStyle.Bold); + } + } + _adapt_contextmenu_for_tasks(); + _adapt_contextmenu_for_filter(); + _toolstripmenuitem_sheet_column_settings.Text = String.Format("Set Display For '{0}'", NMSheetColumnDisplayHelper.get_column_display_string(cell.col)); + _toolstripmenuitem_sheet_column_settings.Tag = cell.col; + _contextmenustrip_main.Show(System.Windows.Forms.Cursor.Position); + } + + private void _handle_theo_grid_mouse_up_outside_bitmap(MouseButtons button) { + if (button == System.Windows.Forms.MouseButtons.Right) { + _last_rightclick_cell = NMSheetTheoGrid.GridCell.empty; + _adapt_contextmenu_for_filter(); + _contextmenustrip_main.Show(System.Windows.Forms.Cursor.Position); + } + } + + #endregion + + private void _handle_zoom(bool inc_size) { + _set_new_settings(NMSheetSettingUtilities.change_font_size(_settings, (float)(inc_size ? 1.0 : -1.0), 6, 18)); + } + + private void _windows_timer_tick(object sender, EventArgs e) { + _publish_activation_state(); + _threaded_bb.sec_thread_dowork(); + _check_and_propagate_data(); + _poll_theo_acceptance_button(); + _refresh_statusbar_data(false); + } + + private bool _last_published_visible_state = false; + private void _publish_activation_state() { + if (_last_published_visible_state != is_visible) { + _last_published_visible_state = is_visible; + bts.Log.Ui.info(String.Format("NMSheets req_id {0} publishing new state {1}", _req_id, _last_published_visible_state.ToString().ToUpper())); + _threaded_bb.sec_thread_write(new NMSheetTags.NMSheetVisibilityTag(_req_id), _last_published_visible_state, false); + } + } + + private void _navigate_to_expiration(NMSheetExpiration nmsheet_exp) { + if (nmsheet_exp != null) { + bts.Log.Ui.info(String.Format("NMSheetControl callback from expiration navigator {0}", nmsheet_exp)); + _theo_grid.theo_grid.navigate_to_expiration(nmsheet_exp); + } + } + + private void _navigate_target_expiration_to_current_expiration(NMSheetExpiration nmsheet_exp) { + if (nmsheet_exp != null && _last_rightclick_cell != null) { + bts.Log.Ui.info(String.Format("NMSheetControl callback from expiration navigator {0}", nmsheet_exp)); + _theo_grid.theo_grid.navigate_to_expiration_target(_last_rightclick_cell.expiration, nmsheet_exp); + } + } + + private void _navigate_to_atm(NMSheetExpiration nmsheet_exp) { + if (nmsheet_exp != null) { + ATMData exp_atm_data = null; + if (_sheet_data != null) { + IDictionary map = _sheet_data.get_atm_data(); + if (map != null && map.TryGetValue(nmsheet_exp, out exp_atm_data)) { + double atm_strike = exp_atm_data.get_strike_closest_to_fwd(); + _theo_grid.theo_grid.navigate_to_strike(atm_strike, 0.5); + } + } + } + } + + #endregion + + #region Dispose + private bool _is_logical_disposed = false; + private void _logical_dispose(bool disposing) { + if (!_is_logical_disposed) { + if (System.Threading.Thread.CurrentThread.ManagedThreadId == _thread_id) { + _is_logical_disposed = true; + _threaded_bb.sec_thread_dispose(); + _coalescer.Dispose(); + } else { + bts.Log.Ui.info("NMSheetControl's Dispose called from a different thread"); + } + } + } + #endregion + + #region Coalescer NMSheetData interaction + + private DateTime _last_data_draw_time = DateTime.MinValue; + private const double _min_draw_period_ms = 333.3; + private NMSheetGeometricLayout _last_geo_lo_info = null; + private void _check_and_propagate_data() { + if (is_visible) { + if ((DateTime.Now - _last_data_draw_time).Milliseconds >= Math.Max(_settings.setting_grid_internal.grid_paint_throttle_ms, _min_draw_period_ms)) { + NMSheetData new_sheet_data = _coalescer.get_data(); + if (new_sheet_data != null) { + _last_data_draw_time = DateTime.Now; + _sheet_data = new_sheet_data; + _respond_to_data(); + } + } + } + } + + private void _respond_to_data() { + if (_sheet_data != null) { + _set_driver_control_display(); + _set_exp_header_control_display(); + _paint_grid(); + _refresh_statusbar_data(true); + if (this.Height > _driver_control_strip.Bottom && _sheet_data.get_sorted_strikes().Length != _last_strikes_count) + _set_strike_navigator(); + if (!Enumerable.SequenceEqual(_sorted_expirations, _sheet_data.get_sorted_expirations())) { + _sorted_expirations = _sheet_data.get_sorted_expirations(); + _set_exp_navigation_display(); + _set_expirations_to_menu(); + } + NMSheetExpiration[] sorted_exps = _sheet_data.get_sorted_expirations(); + // if (sorted_exps != null && _current_expiration_index < sorted_exps.Length) { + // if (_show_strike_navigator) { + // IDictionary map = _sheet_data.get_atm_data(); + // ATMData atm_data; + // if (map.TryGetValue(sorted_exps[_current_expiration_index], out atm_data)) + // _strike_navigator.set_atm_strike(atm_data.get_strike(true), _settings); + // } + // } + } + } + + private double _last_strikes_count = 0; + private void _set_strike_navigator() { + // if (_show_strike_navigator) { + // _last_strikes_count = _sheet_data.get_sorted_strikes().Length; + // double lowest_visible_strike, highest_visible_strike; + // _theo_grid.get_lowest_and_highest_visible_strikes(out lowest_visible_strike, out highest_visible_strike); + // _strike_navigator.set_height_and_strikes(_sheet_data.get_sorted_strikes(), this.Height - _driver_control_strip.Bottom, lowest_visible_strike, highest_visible_strike, _settings); + // _element_host_strike_navigator.Size = new Size(_element_host_strike_navigator.Size.Width, this.Height - _driver_control_strip.Bottom); + // } + } + + private void _set_driver_control_display() { + _driver_control_strip.set_sheet_data(_sheet_data); + } + + private void _set_exp_header_control_display() { + if (_show_expiration_atm_header) + _expiration_header_strip.set_header_data(_sheet_data.get_atm_data()); + } + + private void _set_exp_navigation_display() { + // if (_show_expiration_navigator) + // _button_list_control_exp_navigator.set_items(_sheet_data.get_sorted_expirations()); + } + + private void _set_expirations_to_menu() { + List removed_items = new List(); + foreach (ToolStripItem mi_item in _contextmenustrip_main.Items) + if (mi_item.Tag != null && mi_item.Tag is NMSheetExpiration) + removed_items.Add(mi_item); + foreach (ToolStripItem mi_item in removed_items) + _contextmenustrip_main.Items.Remove(mi_item); + int insert_index = _contextmenustrip_main.Items.IndexOf(_toolstripseperator_expirations); + foreach (NMSheetExpiration nmsheet_exp in _sorted_expirations) { + ToolStripMenuItem exp_mi = new ToolStripMenuItem(_get_summary_expiration_text(nmsheet_exp), null, (s, e) => { _navigate_target_expiration_to_current_expiration(nmsheet_exp); }) { Tag = nmsheet_exp }; + _contextmenustrip_main.Items.Insert(insert_index++, exp_mi); + } + } + + private void _paint_grid() { + NMSheetVisualLayout visual_lo_info; + NMSheetFormattedTheos formatted_theos; + NMSheetGeometricLayout geo_lo_info; + _get_grid_input(_sheet_data, _settings, _formatter, _last_geo_lo_info, _graphics, out visual_lo_info, out formatted_theos, out geo_lo_info, _recorder); + _last_geo_lo_info = geo_lo_info; + _theo_grid.theo_grid.reset_data(_settings, visual_lo_info, formatted_theos, geo_lo_info); + } + + private static void _get_grid_input(NMSheetData sheet_data, + NMSheetSettings nmsheet_settings, + NMSheetDisplayFormatter formatter, + NMSheetGeometricLayout prev_geo_lo_info, + Graphics graphics, + out NMSheetVisualLayout visual_lo_info, + out NMSheetFormattedTheos formatted_theos, + out NMSheetGeometricLayout geo_lo_info, + PerfStatsLogger recorder) { + BCG.Utilities.General.HighPerformanceTimer timer = new Utilities.General.HighPerformanceTimer(); + + timer.start(); + visual_lo_info = new NMSheetVisualLayout(nmsheet_settings); + timer.stop(); + double visual_layout_time = timer.lastIntervalTime; + + timer.start(); + formatted_theos = new NMSheetFormattedTheos(sheet_data, visual_lo_info.visible_cols, formatter); + timer.stop(); + double format_theo_time = timer.lastIntervalTime; + + timer.start(); + geo_lo_info = new NMSheetGeometricLayout(graphics, nmsheet_settings, visual_lo_info, formatted_theos, prev_geo_lo_info, false); + timer.stop(); + double geometric_layout_time = timer.lastIntervalTime; + + recorder.log("NMSheetTheoControl.VisualLayout", "NMSheetTheoControl.VisualLayout", visual_layout_time); + recorder.log("NMSheetTheoControl.Formatting", "NMSheetTheoControl.Formatting", format_theo_time); + recorder.log("NMSheetTheoControl.FormattingHitRatio", "NMSheetTheoControl.FormattingHitRatio", formatted_theos.formatter_hit_ratio); + recorder.log("NMSheetTheoControl.GeometricLayout", "NMSheetTheoControl.GeometricLayout", geometric_layout_time); + } + + #endregion + + #region Filter + + private void _adapt_contextmenu_for_filter() { + _toolstripmenuitem_filter_strikes_with_pos_edge.Checked = _settings.setting_filter.filter_positive_edge_strikes.Value; + _toolstripmenuitem_filter_strikes_in_tasks.Checked = _settings.setting_filter.filter_ee_task_strikes; + _toolstripmenuitem_filter_on_strikes_in_tasks.Checked = _settings.setting_filter.filter_on_ee_task_strikes; + } + + #endregion + + //private int _current_expiration_index; + + public void update_strike_navigator_after_scroll(int exp_index) { + // if (_show_strike_navigator) { + // if (exp_index != _current_expiration_index && exp_index >= 0 && exp_index < _sorted_expirations.Length) { + // _current_expiration_index = exp_index; + // IDictionary d = _sheet_data.get_atm_data(); + // foreach (KeyValuePair kvp in d) + // if (kvp.Key.Equals(_sorted_expirations[exp_index])) + // _strike_navigator.set_atm_strike(kvp.Value.get_strike(true), _settings); + // } + // update_visible_strike_range(); + // } + } + + public void update_visible_strike_range() { + // if (_show_strike_navigator) { + // double lowest_visible_strike, highest_visible_strike; + // _theo_grid.get_lowest_and_highest_visible_strikes(out lowest_visible_strike, out highest_visible_strike); + // _strike_navigator.set_color_scheme(lowest_visible_strike, highest_visible_strike, _settings); + // } + } + } +} diff --git a/src/client/spark/NMSheets/UIComponents/MainSheet/NMSheetControl.resx b/src/client/spark/NMSheets/UIComponents/MainSheet/NMSheetControl.resx new file mode 100644 index 000000000..130dbebf7 --- /dev/null +++ b/src/client/spark/NMSheets/UIComponents/MainSheet/NMSheetControl.resx @@ -0,0 +1,126 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + 17, 17 + + + 201, 17 + + \ No newline at end of file diff --git a/src/client/spark/NMSheets/UIComponents/MainSheet/NMSheetControlExportData.cs b/src/client/spark/NMSheets/UIComponents/MainSheet/NMSheetControlExportData.cs new file mode 100644 index 000000000..423e9defe --- /dev/null +++ b/src/client/spark/NMSheets/UIComponents/MainSheet/NMSheetControlExportData.cs @@ -0,0 +1,65 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.IO; +using System.Windows.Forms; +using mbts; +using mbts.spark; + +namespace BCG { + partial class NMSheetControl { + private void _init_export_data() { + _toolstrip_menuitem_save_data_to_file.Click += (s, e) => { + try { + if (_sheet_data != null && _settings != null && _settings.setting_export_data_column_organization != null && _settings.setting_export_data_column_organization.column_configuration_list != null) { + string file_name = _get_saving_file_name(); + if (!String.IsNullOrEmpty(file_name)) { + double[] recv_array = new double[Enum.GetNames(typeof(NMSheetColumnName)).Length]; NMSheetRowAuxiliaryData aux_data; + StreamWriter writer = new StreamWriter(new FileStream(file_name, FileMode.Create, FileAccess.Write)); + IDictionary driver_map = _sheet_data.get_driver_data(); + IDictionary atm_map = _sheet_data.get_atm_data(); + foreach (NMSheetExpiration exp in _sheet_data.get_sorted_expirations()) { + NMSheetDriverData driver_data = driver_map.TryGetValue(exp, out driver_data) ? driver_data : null; + ATMData atm_data = atm_map.TryGetValue(exp, out atm_data) ? atm_data : null; + foreach (double k in _sheet_data.get_sorted_strikes()) { + if (_sheet_data.get_row_data(exp.nmsheet_symbol, exp.option_expiration, k, ref recv_array, out aux_data)) { + string k_line = _strike_data_to_string(exp, recv_array, driver_data, atm_data, _settings.setting_export_data_column_organization.column_configuration_list); + writer.WriteLine(k_line); + } + } + } + writer.Flush(); + writer.Close(); + } + } + } catch (Exception ex) { + bts.Log.Ui.error(ex.ToString()); + // TODO + //_threaded_bb.sec_thread_write(SparkTags.MessageDisplayTag, new bts.spark.MessageDisplayData("Save Error", String.Format("Failed to save data. The following error occured {0}", ex.ToString()), mbts.bb.MessageDisplayType.Error, true)); + } + }; + } + + private static string _strike_data_to_string(NMSheetExpiration exp, double[] values, NMSheetDriverData driver_data, ATMData atm_data, IEnumerable cols) { + StringBuilder sb = new StringBuilder(); + /// these cols always show up + sb.Append(String.Format("{0},{1},{2},", exp, + driver_data == null ? Double.NaN : driver_data.driver_price_at_computed_theo, + atm_data == null ? Double.NaN : atm_data.roll_offset)); + foreach (var c in cols.Where(c => c.is_visibile)) + sb.Append(String.Format("{0},", values[(int)c.column_name])); + return sb.ToString(); + } + + private string _get_saving_file_name() { + SaveFileDialog diag = new SaveFileDialog(); + diag.DefaultExt = ".csv"; + if (diag.ShowDialog(this) == System.Windows.Forms.DialogResult.OK) + return !diag.FileName.ToLower().EndsWith(diag.DefaultExt) ? diag.FileName + diag.DefaultExt : diag.FileName; + else + return null; + } + } +} \ No newline at end of file diff --git a/src/client/spark/NMSheets/UIComponents/MainSheet/NMSheetControlStatusBar.cs b/src/client/spark/NMSheets/UIComponents/MainSheet/NMSheetControlStatusBar.cs new file mode 100644 index 000000000..0ca1e3e7b --- /dev/null +++ b/src/client/spark/NMSheets/UIComponents/MainSheet/NMSheetControlStatusBar.cs @@ -0,0 +1,74 @@ +using System; + +using bts.api; + +namespace BCG { + partial class NMSheetControl { + private NMSheetTheoGrid.GridCell _last_mousemove_cell = null; + private readonly TimeSpan _statusbar_refresh_period = TimeSpan.FromMilliseconds(250); + private DateTime _last_statusbar_update_time = DateTime.Now; + private bool _statusbar_dirty = true; + + private void _on_statusbar_mousemove(NMSheetTheoGrid.GridCell cell) { + _last_mousemove_cell = cell; + _statusbar_dirty = true; + } + + private void _refresh_statusbar_data(bool force_update) { + if (_show_statusbar && _last_mousemove_cell != null) { + if (force_update || (_statusbar_dirty && DateTime.Now - _last_statusbar_update_time >= _statusbar_refresh_period)) { + uint sec_key = _refresh_status_security_data(); + _refresh_status_column_data(); + if (!_api_tasking_enabled) { + _refresh_task_data(sec_key); + } + _last_statusbar_update_time = DateTime.Now; + _statusbar_dirty = false; + } + } + } + + private uint _refresh_status_security_data() { + uint seckey = _get_seckey(); + string key_text = seckey == 0 ? "(Unlisted)" : String.Format("(Key:{0})", seckey); + _set_text_visibility(_statusbar_toolstripstatus_security, true, + String.Format("{0} {1} {2} {3}", _formatter.format_expiration(_last_mousemove_cell.expiration), _last_mousemove_cell.strike, _last_mousemove_cell.call_selected ? "C" : "P", key_text)); + return seckey; + } + + private uint _get_seckey() { + uint rv = 0; + return _sheet_data.get_security_key(_last_mousemove_cell.expiration, _last_mousemove_cell.strike, _last_mousemove_cell.call_selected, out rv) ? rv : 0; + } + + private void _refresh_status_column_data() { + _set_text_visibility(_statusbar_toolstripstatus_column, true, NMSheetColumnDisplayHelper.get_column_display_string(_last_mousemove_cell.col)); + } + + private void _refresh_task_data(uint seckey) { + string eye_task_text = String.Empty, quoter_task_text = String.Empty; + bool dummy, is_bid, is_ask; + NMSheetSettingColumnOrganization.parse_column(_last_mousemove_cell.col, out dummy, out dummy, out is_bid, out is_ask); + if (is_bid ^ is_ask) { + TaskingConsolidatedData task_data = _sheet_data.get_task_data(); + mbts.tasks.TaskLiveData eye_task_ld = task_data != null ? task_data.get_security_task(new mbts.engine.SecuritySideKey(seckey, is_bid ? Side.Buy : Side.Sell), mbts.tasks.TaskType.Eye) : null; + if (eye_task_ld != null) + eye_task_text = String.Format("Eye '{0}' {1} {2}", eye_task_ld.name, eye_task_ld.switch_state.ToString().ToUpper(), + eye_task_ld.abs_accumulation.ToString("0") + "/" + eye_task_ld.task.common.exit_condition_parameter.ToString("0")); + mbts.tasks.TaskLiveData quoter_task_ld = task_data != null ? task_data.get_security_task(new mbts.engine.SecuritySideKey(seckey, is_bid ? Side.Buy : Side.Sell), mbts.tasks.TaskType.Quoter) : null; + if (quoter_task_ld != null) + quoter_task_text += String.Format("Quoter '{0}' {1} {2}", quoter_task_ld.name, quoter_task_ld.switch_state.ToString().ToUpper(), + quoter_task_ld.abs_accumulation.ToString("0") + "/" + quoter_task_ld.task.common.exit_condition_parameter.ToString("0")); + } + _set_text_visibility(_statusbar_toolstripstatus_task, true, String.Format("{0}{1}{2}", eye_task_text, String.IsNullOrEmpty(eye_task_text) ? String.Empty : " ", quoter_task_text)); + } + + private static void _set_text_visibility(System.Windows.Forms.ToolStripStatusLabel l, bool new_visibility, string new_text) { + if (l.Visible != new_visibility) + l.Visible = new_visibility; + if (l.Visible) + if (!new_text.Equals(l.Text)) + l.Text = new_text; + } + } +} diff --git a/src/client/spark/NMSheets/UIComponents/MainSheet/NMSheetControlTask.cs b/src/client/spark/NMSheets/UIComponents/MainSheet/NMSheetControlTask.cs new file mode 100644 index 000000000..03fc56fd6 --- /dev/null +++ b/src/client/spark/NMSheets/UIComponents/MainSheet/NMSheetControlTask.cs @@ -0,0 +1,236 @@ +using mbts; +using mbts.tasks; +using System; +using System.Drawing; +using System.Collections.Generic; +using System.Linq; +using System.Windows.Forms; +using mbts.engine; +using BCG.Utilities.General; + +namespace BCG { + partial class NMSheetControl { + //private static readonly string _edge_menu_id = "Edge", _size_menu_id = "Size"; + //private TaskSecuritySelection _task_selection; + + #region Selection Encap + // private class TaskSecuritySelection { + // public readonly NMSheetColumnName col; + // public readonly NMSheetExpiration exp = null; + // public readonly IEnumerable strikes = null; + // public readonly NMSheetSettingColumnOrganization.NMSheetColumnInfo col_info = null; + // public readonly bool is_active = false; + // private readonly List> _key_text_tups = null; + + // public TaskSecuritySelection(NMSheetControl parent_control) { + // var sel_map = parent_control._theo_grid.theo_grid.get_selection_map_data(); + // if (sel_map.get_single_exp_single_col_sel(out exp, out col, out strikes)) { + // is_active = true; + // col_info = NMSheetSettingColumnOrganization.get_column_info(col); + // _key_text_tups = new List>(); + // /// loop for sec keys (not side) + // foreach (double k in strikes) { + // uint seckey; + // if (col_info.is_call) { + // if (parent_control._sheet_data.get_security_key(exp, k, true, out seckey)) + // _key_text_tups.Add(Tuple.Create(seckey, ContractUtilities.get_option_display_text(exp.nmsheet_symbol.option_name, exp.option_expiration, k, true))); + // } + // if (col_info.is_put) { + // if (parent_control._sheet_data.get_security_key(exp, k, false, out seckey)) + // _key_text_tups.Add(Tuple.Create(seckey, ContractUtilities.get_option_display_text(exp.nmsheet_symbol.option_name, exp.option_expiration, k, false))); + // } + // } + // } + // } + + // public TaskType? get_selected_edge_tasktype() { + // if (col == NMSheetColumnName.call_ee_set_ask_edge || col == NMSheetColumnName.call_ee_set_bid_edge || col == NMSheetColumnName.put_ee_set_ask_edge || col == NMSheetColumnName.put_ee_set_bid_edge) + // return TaskType.Eye; + // if (col == NMSheetColumnName.call_quoter_set_ask_edge || col == NMSheetColumnName.call_quoter_set_bid_edge || col == NMSheetColumnName.put_quoter_set_ask_edge || col == NMSheetColumnName.put_quoter_set_bid_edge) + // return TaskType.Quoter; + // return null; + // } + + // public TaskType? get_selected_size_tasktype() { + // if (col == NMSheetColumnName.call_ee_set_ask_size || col == NMSheetColumnName.call_ee_set_bid_size || col == NMSheetColumnName.put_ee_set_ask_size || col == NMSheetColumnName.put_ee_set_bid_size) + // return TaskType.Eye; + // if (col == NMSheetColumnName.call_quoter_set_ask_size || col == NMSheetColumnName.call_quoter_set_bid_size || col == NMSheetColumnName.put_quoter_set_ask_size || col == NMSheetColumnName.put_quoter_set_bid_size) + // return TaskType.Quoter; + // return null; + // } + + // public IEnumerable keys { get { return _key_text_tups.Select(t => t.Item1); } } + // public IEnumerable names { get { return _key_text_tups.Select(t => t.Item2); } } + // } + + + #endregion + + private void _init_task_ui() { + // _init_task_ee_ui(); + // _init_task_quoter_ui(); + // _threaded_bb.add_to_subscription_list(TaskingTags.TemplatesTag); + // _toolstripmenuitem_task_manage_templates.Click += (s, e) => _threaded_bb.sec_thread_write(TaskingTags.ShowTemplates, new object()); + // _toolstripmenuitem_task_eye_switch_all_off.Click += (s, e) => _threaded_bb.sec_thread_write(TaskingTags.SwitchOffAllTasksTag, false); + // _toolstripmenuitem_task_undo_edge_override.Click += (s, e) => _set_selection_edge(false); + // _toolstripmenuitem_task_enter_edge.Click += (s, e) => _show_task_edge_entry_dialog(); + // _toolstripmenuitem_task_undo_size_override.Click += (s, e) => _set_selection_size(false); + // _toolstripmenuitem_task_enter_size.Click += (s, e) => _show_task_size_entry_dialog(); + } + + private void _adapt_contextmenu_for_tasks() { + // _task_selection = new TaskSecuritySelection(this); + // _adapt_contextmenu_for_tasks_eye(); + // _adapt_contextmenu_for_tasks_quoter(); + // /// if selection is edge enable edge menu else disable it + // _toolstripmenuitem_task_override_edge.Enabled = false; + // _toolstripmenuitem_task_override_size.Enabled = false; + // TaskType? task_type; ElectronicTradingTask sel_task; IEnumerable sel_secs; + // if (_get_task_edge_size_selection(true, out task_type, out sel_task, out sel_secs)) { + // _toolstripmenuitem_task_override_edge.Enabled = true; + // _populate_edge_menu(); + // } + // if (_get_task_edge_size_selection(false, out task_type, out sel_task, out sel_secs)) { + // _toolstripmenuitem_task_override_size.Enabled = true; + // _populate_size_menu(); + // } + } + + #region Task Selection Edge + private void _populate_edge_menu() { + // CommonGUIUtilities.remove_items_from_menu_dropdown(_toolstripmenuitem_task_override_edge, ti => _edge_menu_id.Equals(ti.Tag)); + // IEnumerable edge_menu_items = _get_preconfigured_edges().Select(p => new ToolStripMenuItem(p.Item2, null, (s, e) => _set_selection_edge(true, p.Item1)) { Tag = _edge_menu_id }).ToArray(); + // _toolstripmenuitem_task_override_edge.DropDownItems.InsertRange(0, edge_menu_items); + } + + private void _show_task_edge_entry_dialog() { + // GridValueEditorWinForm editor_form = new GridValueEditorWinForm("Override Edge", typeof(double), PointToScreen(_theo_grid.theo_grid.get_last_mouse_clicked_point())); + // editor_form.on_commit_click += v => _set_selection_edge(true, (double)v); + // editor_form.ShowDialog(); + } + + private void _set_selection_edge(bool is_set, double edge = Double.NaN) { + + // TaskType? task_type; ElectronicTradingTask sel_task; IEnumerable sel_secs; + // if (_get_task_edge_size_selection(true, out task_type, out sel_task, out sel_secs)) { + // sel_task = is_set ? TaskingUtilityFunctions.update_edges(sel_task, sel_secs.Select(k => Tuple.Create(k, edge))) : TaskingUtilityFunctions.remove_edge_overrides(sel_task, sel_secs); + // _threaded_bb.sec_thread_write(TaskingTags.ModifyTaskTag, sel_task); + // } + } + + // private IEnumerable> _get_preconfigured_edges() { + // NMSheetSettings settings = _settings ?? new NMSheetSettings(); + // NMSheetColumnConfiguration col_conf = _settings.get_column_conf(NMSheetColumnName.call_quoter_set_bid_edge); + // TickConverter2.TickType tick_type = col_conf != null ? col_conf.display_format : TickConverter2.TickType.tickDecimal2; + // return _parse_edge_numbers(settings.setting_quoteset.preconfigured_edges, tick_type); + // } + + // private IEnumerable> _get_preconfigured_edge_shifts() { + // NMSheetSettings settings = _settings ?? new NMSheetSettings(); + // NMSheetColumnConfiguration col_conf = _settings.get_column_conf(NMSheetColumnName.call_quoter_set_bid_edge); + // TickConverter2.TickType tick_type = col_conf != null ? col_conf.display_format : TickConverter2.TickType.tickDecimal2; + // return _parse_edge_numbers(settings.setting_quoteset.preconfigured_edge_shifts, tick_type); + // } + + // private IEnumerable _get_preconfigured_sizes() { + // List rv = new List(); + // if (_settings != null && _settings.setting_quoteset != null && !String.IsNullOrEmpty(_settings.setting_quoteset.preconfigured_sizes)) { + // foreach (string s in _settings.setting_quoteset.preconfigured_sizes.Split(',')) { + // uint size = 0; + // if (uint.TryParse(s, out size)) + // rv.Add(size); + // } + // } + // rv.Sort(); + // return rv; + // } + + // private static IEnumerable> _parse_edge_numbers(string parsable_doubles, TickConverter2.TickType tick_type) { + // List> rv = new List>(); + // parsable_doubles = parsable_doubles ?? String.Empty; + // string[] preconf_edges = parsable_doubles.Split(',', ' '); + // foreach (string s in preconf_edges) { + // double d; + // if (!String.IsNullOrEmpty(s) && Double.TryParse(s, out d)) { + // double edge_d; + // string edge_s; + // try { + // TickConverter2.to_tick(d, TickConverter2.getTickTypeInfo(tick_type), true, out edge_s, out edge_d); + // rv.Add(new Tuple(edge_d, edge_s)); + // } catch (Exception ex) { mbts.Logger.log(bts.log.Level.Error, bts.log.Subsystem.ui, ex.Message); } + // } + // } + // rv.Sort((Tuple p1, Tuple p2) => { return p1.Item1.CompareTo(p2.Item1); }); + // return rv; + // } + + #endregion + + #region Task Selection Size + private void _populate_size_menu() { + // CommonGUIUtilities.remove_items_from_menu_dropdown(_toolstripmenuitem_task_override_size, ti => _size_menu_id.Equals(ti.Tag)); + // IEnumerable size_menu_items = _get_preconfigured_sizes().Select(p => new ToolStripMenuItem(p.ToString(), null, (s, e) => _set_selection_size(true, p)) { Tag = _size_menu_id }).ToArray(); + // _toolstripmenuitem_task_override_size.DropDownItems.InsertRange(0, size_menu_items); + } + + private void _show_task_size_entry_dialog() { + // GridValueEditorWinForm editor_form = new GridValueEditorWinForm("Override Size", typeof(uint), PointToScreen(_theo_grid.theo_grid.get_last_mouse_clicked_point())); + // editor_form.on_commit_click += s => _set_selection_size(true, (uint)s); + // editor_form.ShowDialog(); + } + + private void _set_selection_size(bool is_set, uint size = 0) { + // TaskType? task_type; ElectronicTradingTask sel_task; IEnumerable sel_secs; + // if (_get_task_edge_size_selection(false, out task_type, out sel_task, out sel_secs)) { + // sel_task = is_set ? TaskingUtilityFunctions.update_sizes(sel_task, sel_secs.Select(k => Tuple.Create(k, size))) : TaskingUtilityFunctions.remove_size_overrides(sel_task, sel_secs); + // _threaded_bb.sec_thread_write(TaskingTags.ModifyTaskTag, sel_task); + // } + } + + #endregion + + // private bool _get_task_edge_size_selection(bool is_edge, out TaskType? task_type, out ElectronicTradingTask task, out IEnumerable secsidekeys) { + // task_type = null; task = null; secsidekeys = null; + // task_type = is_edge ? _task_selection.get_selected_edge_tasktype() : _task_selection.get_selected_size_tasktype(); + // if (task_type != null) { + // secsidekeys = _task_selection.keys.Select(k => new SecuritySideKey(k, _task_selection.col_info.is_bid ? Side.Buy : bts.o2.msgs.Side.Sell)); + // TaskingConsolidatedData task_data = _sheet_data.get_task_data(); + // if (task_data != null) { + // IEnumerable owning_tasks = task_data.get_security_owning_tasks(secsidekeys, task_type.Value); + // if (owning_tasks != null && owning_tasks.Count() == 1) { + // task = owning_tasks.ElementAt(0).task; + // return true; + // } + // } + // } + // return false; + // } + + private void _handle_task_mouse_event(NMSheetTheoGrid.GridCell cell) { + // if (cell != null && cell.expiration != null) { + // NMSheetColumnType col_type = NMSheetSettingColumnOrganization.get_col_type(cell.col); + // bool is_ee_col = col_type == NMSheetColumnType.EE, is_quoter_col = col_type == NMSheetColumnType.Quoter; + // if (is_ee_col || is_quoter_col) { + // uint seckey; + // if (_sheet_data.get_security_key(cell.expiration, cell.strike, cell.call_selected ? true : false, out seckey)) { + // bool is_call, is_bid, is_ask; + // NMSheetSettingColumnOrganization.parse_column(cell.col, out is_call, out is_call, out is_bid, out is_ask); + // SecuritySideKey secsidekey = is_bid ? new SecuritySideKey(seckey, Side.Buy) : new SecuritySideKey(seckey, Side.Sell); + // IEnumerable owning_tasks = _sheet_data.get_task_data().get_security_owning_tasks(new SecuritySideKey[] { secsidekey }, is_ee_col ? TaskType.Eye : TaskType.Quoter); + // if (owning_tasks.Count() == 1) + // _threaded_bb.sec_thread_write(TaskingTags.ShowTaskDetails, owning_tasks.ElementAt(0)); + // } + // } + // } + } + + // private static ElectronicTradingTask _get_mod_task(ElectronicTradingTask task, TaskSecuritySelection sel) { + // List secs = new List(task.explicit_task.securities); + // List secs_desc = new List(task.explicit_task.security_descriptions); + // secs.AddRange(sel.keys); + // secs_desc.AddRange(sel.names); + // ElectronicTradingTask mod_task = task.with(explicit_task: task.explicit_task.with(securities: secs, security_descriptions: secs_desc)); + // return mod_task; + // } + } +} \ No newline at end of file diff --git a/src/client/spark/NMSheets/UIComponents/MainSheet/NMSheetControlTaskEye.cs b/src/client/spark/NMSheets/UIComponents/MainSheet/NMSheetControlTaskEye.cs new file mode 100644 index 000000000..42ca931b0 --- /dev/null +++ b/src/client/spark/NMSheets/UIComponents/MainSheet/NMSheetControlTaskEye.cs @@ -0,0 +1,92 @@ +using mbts; +using mbts.tasks; +using System; +using System.Drawing; +using System.Collections.Generic; +using System.Linq; +using System.Windows.Forms; + +namespace BCG { + partial class NMSheetControl { + // private const string _create_menu_tag = "Create"; + // private bool _task_ee_enabled = true; + + private void _init_task_ee_ui() { + // _task_ee_enabled = false;// TaskingUtilityFunctions.is_tasking_enabled(_nmsheet_symbol_list.Select(s => s.option_exchange)); + // if (_task_ee_enabled) + // _disable_task_ee_submenus(); + // else + // _toolstripmenuitem_task_eye.Enabled = false; + // _toolstripmenuitem_settings_show_task_ee_data.Click += (s, e) => _get_toolstripmenuitem_display_state_and_publish(_toolstripmenuitem_settings_show_task_ee_data, + // NMSheetSettingColumnOrganization.get_cols_for_type(NMSheetColumnType.EE).ToArray()); + // _toolstripmenuitem_task_manage_templates.Click += (s, e) => _threaded_bb.sec_thread_write(TaskingTags.ShowTemplates, new object()); + } + + private void _disable_task_ee_submenus() { + // _toolstripmenuitem_task_eye.Enabled = _toolstripmenuitem_task_eye_add_buys_to_task.Enabled = + // _toolstripmenuitem_task_eye_add_sells_to_task.Enabled = _toolstripmenuitem_task_eye_add_buys_and_sells_to_task.Enabled = false; + // _toolstripmenuitem_task_eye_add_buys_to_task.DropDownItems.Clear(); + // _toolstripmenuitem_task_eye_add_sells_to_task.DropDownItems.Clear(); + // _toolstripmenuitem_task_eye_add_buys_and_sells_to_task.DropDownItems.Clear(); + + // List create_menu_items = new List(); + // foreach (ToolStripItem ti in _toolstripmenuitem_task_eye.DropDownItems) + // if (_create_menu_tag.Equals(ti.Tag)) + // create_menu_items.Add(ti); + // create_menu_items.ForEach(ti => _toolstripmenuitem_task_eye.DropDownItems.Remove(ti)); + } + + private void _adapt_contextmenu_for_tasks_eye() { + // if (_task_ee_enabled) { + // _disable_task_ee_submenus(); + // if (_task_selection.is_active) { + // _toolstripmenuitem_task_eye.Enabled = true; + // ///Create + // IEnumerable templates = _threaded_bb.sec_thread_retrieve_from_cache(TaskingTags.TemplatesTag) as IEnumerable; + // templates = templates == null || templates.Count() == 0 ? new TaskCommon[] { TaskCommon.Default.with(name: "New Task") } : templates; + // double min_strike = _task_selection.strikes.Min(), max_strike = _task_selection.strikes.Max(); + // string name = TaskType.Eye.ToString() + " " + + // _task_selection.exp.get_display_text() + " " + + // (min_strike == max_strike ? min_strike.ToString("0.00") : String.Format("{0} - {1}", min_strike.ToString("0.00"), max_strike.ToString("0.00"))); + // int add_task_index = 0; + // foreach (TaskCommon t in templates) { + // ToolStripMenuItem add_task_item = new ToolStripMenuItem(t.name, null, (s, e) => { + // mbts.tasks.TaskCommon common_task = t.with(task_type: TaskType.Eye, name: name, side: TaskSide.None, id: Guid.NewGuid().ToString()); + // ExplicitTask explicit_task = ExplicitTask.Default.with(securities: _task_selection.keys, security_descriptions: _task_selection.names); + // _threaded_bb.sec_thread_write(TaskingTags.ShowCreateTask, new ElectronicTradingTask(common_task, explicit_task)); + // }); + // add_task_item.Tag = _create_menu_tag; + // add_task_item.Enabled = true; + // _toolstripmenuitem_task_eye.DropDownItems.Insert(add_task_index++, add_task_item); + // } + // /// Add Buys to + // TaskingConsolidatedData task_data = _sheet_data.get_task_data(); + // _toolstripmenuitem_task_eye_add_buys_to_task.Enabled = true; + // IEnumerable tasks = task_data.get_tasks(TaskType.Eye).OrderBy(t => t.name); + // foreach (TaskLiveData t in tasks) { + // ElectronicTradingTask mod_task = _get_mod_task(t.task, _task_selection); + // ToolStripMenuItem add_item = new ToolStripMenuItem(t.get_summary_text(), null, (s, e) => _threaded_bb.sec_thread_write(TaskingTags.ShowEditTask, mod_task)); + // add_item.Enabled = t.task.common.side != TaskSide.Sell; + // _toolstripmenuitem_task_eye_add_buys_to_task.DropDownItems.Add(add_item); + // } + // /// Add Sells to + // _toolstripmenuitem_task_eye_add_sells_to_task.Enabled = true; + // foreach (TaskLiveData t in tasks) { + // ElectronicTradingTask mod_task = _get_mod_task(t.task, _task_selection); + // ToolStripMenuItem add_item = new ToolStripMenuItem(t.get_summary_text(), null, (s, e) => _threaded_bb.sec_thread_write(TaskingTags.ShowEditTask, mod_task)); + // add_item.Enabled = t.task.common.side != TaskSide.Buy; + // _toolstripmenuitem_task_eye_add_sells_to_task.DropDownItems.Add(add_item); + // } + // /// Add Buys/Sells to + // _toolstripmenuitem_task_eye_add_buys_and_sells_to_task.Enabled = true; + // foreach (TaskLiveData t in tasks) { + // ElectronicTradingTask mod_task = _get_mod_task(t.task, _task_selection); + // ToolStripMenuItem add_item = new ToolStripMenuItem(t.get_summary_text(), null, (s, e) => _threaded_bb.sec_thread_write(TaskingTags.ShowEditTask, mod_task)); + // add_item.Enabled = t.task.common.side == (TaskSide.Buy | TaskSide.Sell); + // _toolstripmenuitem_task_eye_add_buys_and_sells_to_task.DropDownItems.Add(add_item); + // } + // } + // } + } + } +} \ No newline at end of file diff --git a/src/client/spark/NMSheets/UIComponents/MainSheet/NMSheetControlTaskQuoter.cs b/src/client/spark/NMSheets/UIComponents/MainSheet/NMSheetControlTaskQuoter.cs new file mode 100644 index 000000000..08ce8c327 --- /dev/null +++ b/src/client/spark/NMSheets/UIComponents/MainSheet/NMSheetControlTaskQuoter.cs @@ -0,0 +1,99 @@ +using mbts; +using mbts.tasks; +using System; +using System.Drawing; +using System.Collections.Generic; +using System.Linq; +using System.Windows.Forms; + +namespace BCG { + partial class NMSheetControl { + //private bool _task_quoter_enabled = true; + + private void _init_task_quoter_ui() { + // _task_quoter_enabled = true; + // if (_task_quoter_enabled) + // _disable_task_quoter_submenus(); + // else + // _toolstripmenuitem_task_quoter.Enabled = false; + // _toolstripmenuitem_settings_show_task_quoter_data.Click += (s, e) => _get_toolstripmenuitem_display_state_and_publish(_toolstripmenuitem_settings_show_task_quoter_data, + // NMSheetSettingColumnOrganization.get_cols_for_type(NMSheetColumnType.Quoter).ToArray()); + } + + private void _disable_task_quoter_submenus() { + // _toolstripmenuitem_task_quoter.Enabled = _toolstripmenuitem_task_quoter_add_buys_to_task.Enabled = + // _toolstripmenuitem_task_quoter_add_sells_to_task.Enabled = _toolstripmenuitem_task_quoter_add_buys_and_sells_to_task.Enabled = false; + // _toolstripmenuitem_task_quoter_add_buys_to_task.DropDownItems.Clear(); + // _toolstripmenuitem_task_quoter_add_sells_to_task.DropDownItems.Clear(); + // _toolstripmenuitem_task_quoter_add_buys_and_sells_to_task.DropDownItems.Clear(); + + // List create_menu_items = new List(); + // foreach (ToolStripItem ti in _toolstripmenuitem_task_quoter.DropDownItems) + // if (_create_menu_tag.Equals(ti.Tag)) + // create_menu_items.Add(ti); + // create_menu_items.ForEach(ti => _toolstripmenuitem_task_quoter.DropDownItems.Remove(ti)); + } + + private void _adapt_contextmenu_for_tasks_quoter() { + // if (_task_quoter_enabled) { + // _disable_task_quoter_submenus(); + // if (_task_selection.is_active) { + // _toolstripmenuitem_task_quoter.Enabled = true; + // ///Create + // IEnumerable templates = _threaded_bb.sec_thread_retrieve_from_cache(TaskingTags.TemplatesTag) as IEnumerable; + // templates = templates == null || templates.Count() == 0 ? new TaskCommon[] { TaskCommon.Default.with(name: "New Task") } : templates; + // double min_strike = _task_selection.strikes.Min(), max_strike = _task_selection.strikes.Max(); + // string name = TaskType.Quoter.ToString() + " " + + // _task_selection.exp.get_display_text() + " " + + // (min_strike == max_strike ? min_strike.ToString("0.00") : String.Format("{0} - {1}", min_strike.ToString("0.00"), max_strike.ToString("0.00"))); + // int add_task_index = 0; + // foreach (TaskCommon t in templates) { + // ToolStripMenuItem add_task_item = new ToolStripMenuItem(t.name, null, (s, e) => { + // mbts.tasks.TaskCommon common_task = t.with(task_type: TaskType.Quoter, name: name, side: TaskSide.None, id: Guid.NewGuid().ToString()); + // ExplicitTask explicit_task = ExplicitTask.Default.with(securities: _task_selection.keys, security_descriptions: _task_selection.names); + // _threaded_bb.sec_thread_write(TaskingTags.ShowCreateTask, new ElectronicTradingTask(common_task, explicit_task)); + // }); + // add_task_item.Tag = _create_menu_tag; + // add_task_item.Enabled = true; + // _toolstripmenuitem_task_quoter.DropDownItems.Insert(add_task_index++, add_task_item); + // } + // //Add Buys to + // TaskingConsolidatedData task_data = _sheet_data.get_task_data(); + // _toolstripmenuitem_task_quoter_add_buys_to_task.Enabled = true; + // IEnumerable tasks = task_data.get_tasks(TaskType.Quoter).OrderBy(t => t.name); + // foreach (TaskLiveData t in tasks) { + // ElectronicTradingTask mod_task = _get_mod_task(t.task, _task_selection); + // ToolStripMenuItem add_item = new ToolStripMenuItem(t.get_summary_text(), null, (s, e) => _threaded_bb.sec_thread_write(TaskingTags.ShowEditTask, mod_task)); + // add_item.Enabled = t.task.common.side != TaskSide.Sell; + // _toolstripmenuitem_task_quoter_add_buys_to_task.DropDownItems.Add(add_item); + // } + // /// Add Sells to + // _toolstripmenuitem_task_quoter_add_sells_to_task.Enabled = true; + // foreach (TaskLiveData t in tasks) { + // ElectronicTradingTask mod_task = _get_mod_task(t.task, _task_selection); + // ToolStripMenuItem add_item = new ToolStripMenuItem(t.get_summary_text(), null, (s, e) => _threaded_bb.sec_thread_write(TaskingTags.ShowEditTask, mod_task)); + // add_item.Enabled = t.task.common.side != TaskSide.Buy; + // _toolstripmenuitem_task_quoter_add_sells_to_task.DropDownItems.Add(add_item); + // } + // /// Add Buys/Sells to + // _toolstripmenuitem_task_quoter_add_buys_and_sells_to_task.Enabled = true; + // foreach (TaskLiveData t in tasks) { + // ElectronicTradingTask mod_task = _get_mod_task(t.task, _task_selection); + // ToolStripMenuItem add_item = new ToolStripMenuItem(t.get_summary_text(), null, (s, e) => _threaded_bb.sec_thread_write(TaskingTags.ShowEditTask, mod_task)); + // add_item.Enabled = t.task.common.side == (TaskSide.Buy | TaskSide.Sell); + // _toolstripmenuitem_task_quoter_add_buys_and_sells_to_task.DropDownItems.Add(add_item); + // } + // } + // } + } + + // private ElectronicTradingTask _get_task_quoter_mod_task(ElectronicTradingTask task) { + // List secs = new List(task.explicit_task.securities); + // List secs_desc = new List(task.explicit_task.security_descriptions); + // secs.AddRange(_task_selection.keys); + // secs_desc.AddRange(_task_selection.names); + // ElectronicTradingTask mod_task = task.with(explicit_task: task.explicit_task.with(securities: secs, security_descriptions: secs_desc)); + // return mod_task; + // } + } +} \ No newline at end of file diff --git a/src/client/spark/NMSheets/UIComponents/MainSheet/NMSheetControlTheosAcceptanceConfirmation.cs b/src/client/spark/NMSheets/UIComponents/MainSheet/NMSheetControlTheosAcceptanceConfirmation.cs new file mode 100644 index 000000000..0ce0b3108 --- /dev/null +++ b/src/client/spark/NMSheets/UIComponents/MainSheet/NMSheetControlTheosAcceptanceConfirmation.cs @@ -0,0 +1,72 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Drawing; + +namespace BCG { + /// This partial class controls the Theo Acceptance Confirmation Button. + /// If the Theo Acceptance Confirmation is set to true, any theo changes + /// caused by input changes. + /// This class ONLY works for one Vol Surface. Since this is the common + /// case I am taking this shortcut (2/6/17). + partial class NMSheetControl { + // private readonly TimeSpan _theo_acceptance_poll_period = TimeSpan.FromMilliseconds(500); + // private DateTime _last_theo_confirmation_check_time = DateTime.MinValue; + private void _init_theo_acceptance_button() { + // _button_theo_acceptance_confirmation.Location = _theo_grid.Location; + // _button_theo_acceptance_confirmation.Visible = false; + // _button_theo_acceptance_confirmation.Click += _button_theo_acceptance_confirmation_click; + } + + private void _button_theo_acceptance_confirmation_click(object sender, EventArgs e) { + // VolSurfaceTheoAlertData curr_alert_data = _threaded_bb.sec_thread_retrieve_from_cache(new VolSurfaceBlackboardTags.VolSurfaceTheoAlertTag()) as VolSurfaceTheoAlertData; + // if (curr_alert_data != null) + // { + // _threaded_bb.sec_thread_write(new VolSurfaceBlackboardTags.VolSurfaceLocalTheosTag(curr_alert_data.vs_id), curr_alert_data.theos); + // _threaded_bb.sec_thread_write(new VolSurfaceBlackboardTags.VolSurfaceTheoAcceptanceConfirmationTag(), curr_alert_data.guid); + // } + } + + private void _poll_theo_acceptance_button() { + // if (_is_theo_acceptance_confirmation_on) + // { + // if (DateTime.Now - _last_theo_confirmation_check_time >= _theo_acceptance_poll_period) + // { + // _last_theo_confirmation_check_time = DateTime.Now; + // VolSurfaceTheoAlertData curr_alert_data = _threaded_bb.sec_thread_retrieve_from_cache(new VolSurfaceBlackboardTags.VolSurfaceTheoAlertTag()) as VolSurfaceTheoAlertData; + // string last_accepted_id = (_threaded_bb.sec_thread_retrieve_from_cache(new VolSurfaceBlackboardTags.VolSurfaceTheoAcceptanceConfirmationTag()) as string) ?? String.Empty; + // if (curr_alert_data != null) + // { + // if (String.Compare(curr_alert_data.guid, last_accepted_id) != 0) + // /// This means the last acceptance (from any sheet) is not the same as the + // /// last theo alert + // _flash_theo_acceptance_button(); + // else + // /// This means a sheet has confirmed the theos and has sent out + // /// confirmation that matches the last theo alert + // _button_theo_acceptance_confirmation.Visible = false; + // } + // } + // } + } + + private void _flash_theo_acceptance_button() { + // _button_theo_acceptance_confirmation.Visible = true; + // _button_theo_acceptance_confirmation.BackColor = _button_theo_acceptance_confirmation.BackColor.Equals(Color.Green) ? Color.Red : Color.Green; + } + + private bool _is_theo_acceptance_confirmation_on { + get { + // SymbolBasedSettingsManager click_trade_manager = _threaded_bb.sec_thread_retrieve_from_cache(new ClickTradeSettingsTag()) as SymbolBasedSettingsManager; + // if (click_trade_manager != null) { + // GeneralClickTradeSettings gen_settings = click_trade_manager.fetch_associated_general_settings(); + // if (gen_settings != null) + // return gen_settings.theo_acceptance_confirmation; + // } + return false; + } + } + } +} diff --git a/src/client/spark/NMSheets/UIComponents/MainSheet/NMSheetFormattedTheos.cs b/src/client/spark/NMSheets/UIComponents/MainSheet/NMSheetFormattedTheos.cs new file mode 100644 index 000000000..db5334e42 --- /dev/null +++ b/src/client/spark/NMSheets/UIComponents/MainSheet/NMSheetFormattedTheos.cs @@ -0,0 +1,99 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Drawing; +using System.Collections; +using bts.api; + +namespace BCG { + internal class NMSheetFormattedTheos { + public readonly string[] sorted_formatted_expirations; + public readonly string[] sorted_formatted_strikes; + private readonly Dictionary> _atm_map = new Dictionary>(); + /// This is how the grid accesses the data + /// All values belonging to a single item/type of data. its stored in + /// the same order as ITheoData returns expiration and strike. + /// Its keyed only O(1) per type of element in one draw. + public readonly Dictionary> col_vs_valuelist_map = new Dictionary>(); + private NMSheetFixedExpStrikeDataMap _aux_data_map; + public readonly double formatter_hit_ratio; + + public NMSheetFormattedTheos(INMSheetGridFacingData sheet_data, NMSheetColumnName[] visible_cell_elements, NMSheetDisplayFormatter formatter) { + formatter.start(); + /// visible elem array + _aux_data_map = new NMSheetFixedExpStrikeDataMap(sheet_data.get_sorted_expirations(), sheet_data.get_sorted_strikes()); + /// expirations and strikes + sorted_formatted_expirations = new string[_aux_data_map.get_sorted_expirations().Count()]; + sorted_formatted_strikes = new string[sorted_strikes.Length]; + List[] indexed_theo_values = new List[visible_cell_elements.Length]; + for (int i = 0; i < indexed_theo_values.Length; i++) + indexed_theo_values[i] = new List(); + double[] cp_row = new double[Enum.GetNames(typeof(NMSheetColumnName)).Length]; + int exp_index = 0; + foreach (NMSheetExpiration nmsheet_expiration in _aux_data_map.get_sorted_expirations()) { + sorted_formatted_expirations[exp_index] = formatter.format_expiration(nmsheet_expiration); + int strike_index = 0; + foreach (double strike in _aux_data_map.get_sorted_strikes()) { + sorted_formatted_strikes[strike_index] = formatter.format_value(NMSheetColumnName.strike, strike); + NMSheetRowAuxiliaryData aux_data = null; + if (sheet_data.get_row_data(nmsheet_expiration.nmsheet_symbol, nmsheet_expiration.option_expiration, strike, ref cp_row, out aux_data)) { + _aux_data_map.set_value(exp_index, strike_index, aux_data); + for (int i = 0; i < visible_cell_elements.Length; i++) + indexed_theo_values[i].Add(formatter.format_value(visible_cell_elements[i], cp_row[(int)visible_cell_elements[i]])); + } + strike_index++; + } + exp_index++; + } + col_vs_valuelist_map = new Dictionary>(); + for (int i = 0; i < visible_cell_elements.Length; i++) + col_vs_valuelist_map[visible_cell_elements[i]] = indexed_theo_values[i]; + /// converts exp vs atm strikes to exp vs strike indices + foreach (KeyValuePair exp_atm_elem in sheet_data.get_atm_data()) { + HashSet this_exp_map = new HashSet(); + foreach (double atm_strike in exp_atm_elem.Value.strike_vs_data.Keys) + this_exp_map.Add(Array.BinarySearch(sorted_strikes, atm_strike)); + _atm_map[Array.IndexOf(_aux_data_map.get_sorted_expirations(), exp_atm_elem.Key)] = this_exp_map; + } + formatter.stop(out formatter_hit_ratio); + } + + public double[] sorted_strikes { get { return _aux_data_map.get_sorted_strikes(); } } + + public NMSheetExpiration[] sorted_expirations { get { return _aux_data_map.get_sorted_expirations(); } } + + public bool contains_contract(NMSheetExpiration exp, double strike) { return _aux_data_map.contains(exp, strike); } + + public bool contains_contract(int exp_index, int strike_index) { return _aux_data_map.contains(exp_index, strike_index); } + + public NMSheetTheoBBOCross get_theo_md_cross_state(int exp_index, int strike_index, bool is_call) { + NMSheetRowAuxiliaryData aux_data = null; + if (_aux_data_map.get_value(exp_index, strike_index, out aux_data)) + return aux_data.cross_state.get_data(is_call ? PutOrCall.Call : PutOrCall.Put); + else + return NMSheetTheoBBOCross.get_nulled_obj(); + } + + public NMSheetTradeAlert get_trade_alert(int exp_index, int strike_index, bool is_call) { + NMSheetRowAuxiliaryData aux_data = null; + if (_aux_data_map.get_value(exp_index, strike_index, out aux_data)) { + NMSheetTickerData d = is_call ? aux_data.call_ticker_data : aux_data.put_ticker_data; + return d != null ? d.trade_alert : NMSheetTradeAlert.None; + } + return NMSheetTradeAlert.None; + } + + public NMSheetRowAuxiliaryData get_aux_data(int exp_index, int strike_index) { + NMSheetRowAuxiliaryData rv; + return _aux_data_map.get_value(exp_index, strike_index, out rv) ? rv : null; + } + + public IDictionary> get_atm_map() { return _atm_map; } + + public int get_strike_index(double strike) { return Array.BinarySearch(sorted_strikes, strike); } + + public int get_expiration_index(NMSheetExpiration exp) { return Array.BinarySearch(sorted_expirations, exp); } + } +} \ No newline at end of file diff --git a/src/client/spark/NMSheets/UIComponents/MainSheet/NMSheetGeometricLayout.cs b/src/client/spark/NMSheets/UIComponents/MainSheet/NMSheetGeometricLayout.cs new file mode 100644 index 000000000..fe8a1759d --- /dev/null +++ b/src/client/spark/NMSheets/UIComponents/MainSheet/NMSheetGeometricLayout.cs @@ -0,0 +1,166 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Drawing; +using System.Collections; + +namespace BCG { + internal class NMSheetGeometricLayout { + private readonly bool _pack_tight_ignoring_dec_jitters = false; + private readonly uint _min_horizontal_size_decrement_before_resize = 8; + private const int _min_vertical_size_decrement_before_resize = 4; + private const char _widest_elem = '8'; + private const char _longest_elem = '1'; + + private NMSheetGeometricLayout _prev_geometric_lo_info; + private readonly Size _header_size; /// complete header size, width = width of grid, height = height of exp header (by def :) ) + /// _header_size is not used for any internal calculations here. get_item_rectangle_in_grid and + /// get_strike_rectangle_in_grid are purely + public readonly Size cell_size; /// size of one expiration cell (width = sum of width of all cols, height = height of one cell) + public readonly Size grid_size; /// purely the size of grid + private readonly IDictionary _col_cell_size_map = new Dictionary(); /// size of one col cell, width = width of col, height = max text height of that col + private readonly IDictionary _col_x_map = new Dictionary(); /// x of a column withing an exp + private readonly SizeF[] _exp_size_arr; /// exp text size + + public bool cell_layout_is_same(NMSheetGeometricLayout other_geometry) { + if (_col_cell_size_map.Count != other_geometry._col_cell_size_map.Count) + return false; + + foreach (NMSheetColumnName item in _col_cell_size_map.Keys) + if (get_item_cell_size(item) != other_geometry.get_item_cell_size(item)) + return false; + + if (!Enumerable.SequenceEqual(_exp_size_arr, other_geometry._exp_size_arr)) + return false; + + return true; + } + + private IGraphicsWrapper _get_graphics_wrapper(Graphics g) { return new GDI32Wrapper(g); } + + public NMSheetGeometricLayout(Graphics g, NMSheetSettings settings, NMSheetVisualLayout visual_lo_info, NMSheetFormattedTheos formatted_theos, NMSheetGeometricLayout prev_geometric_lo_info, bool pack_tight_ignoring_dec_jitters) { + _prev_geometric_lo_info = prev_geometric_lo_info; + _pack_tight_ignoring_dec_jitters = pack_tight_ignoring_dec_jitters; + _min_horizontal_size_decrement_before_resize = settings.setting_grid_internal.min_column_size_dec_before_refitting.Value; + if (_prev_geometric_lo_info != null) + _prev_geometric_lo_info._break_chain(); + + using (IGraphicsWrapper wp = _get_graphics_wrapper(g)) { + float item_x = 0; + foreach (NMSheetColumnName item in visual_lo_info.visible_cols) { + _col_x_map[item] = item_x; + List elem_val_list; + int n_max_chars = 0; + if (formatted_theos.col_vs_valuelist_map.TryGetValue(item, out elem_val_list)) { + foreach (string v in elem_val_list) + if (v.Length > n_max_chars) + n_max_chars = v.Length; + } + SizeF max_size = _get_adjusted_max_size(visual_lo_info, wp, item, n_max_chars, settings.setting_grid_internal.horizontal_padding, settings.setting_grid_internal.vertical_padding); + max_size = new SizeF(Math.Max(max_size.Width, Convert.ToSingle(settings.setting_column_organization.get_column_min_width(item))), max_size.Height); + _col_cell_size_map[item] = max_size; + item_x += max_size.Width; + } + + /// finding the cell_size which is the addition of all + /// item sizes + PointF pf = new PointF(0, 0); + + foreach (NMSheetColumnName k in visual_lo_info.visible_cols) { + SizeF element_cell_size = get_item_cell_size(k); + pf.X += element_cell_size.Width; + pf.Y = Math.Max(element_cell_size.Height, pf.Y); + } + cell_size = new Size((int)pf.X, (int)pf.Y); + + /// measure exps + _exp_size_arr = new SizeF[formatted_theos.sorted_formatted_expirations.Length]; + wp.selectFont(settings.setting_expiration_header.expiration_font); + int exp_no = 0; + float max_exp_height = 0; + foreach (string formatted_exp in formatted_theos.sorted_formatted_expirations) { + SizeF formatted_exp_size = wp.measureString(formatted_exp); + max_exp_height = formatted_exp_size.Height > max_exp_height ? formatted_exp_size.Height : max_exp_height; + _exp_size_arr[exp_no++] = new SizeF(formatted_exp_size.Width, formatted_exp_size.Height + settings.setting_grid_internal.header_vertical_padding); + } + + _header_size = new Size(cell_size.Width * formatted_theos.sorted_formatted_expirations.Length, (int)max_exp_height + settings.setting_grid_internal.header_vertical_padding); + grid_size = new Size(cell_size.Width * formatted_theos.sorted_formatted_expirations.Length, cell_size.Height * formatted_theos.sorted_formatted_strikes.Length); + } + } + + private void _break_chain() { _prev_geometric_lo_info = null; } + + private SizeF _get_adjusted_max_size(NMSheetVisualLayout visual_lo_info, IGraphicsWrapper wp, NMSheetColumnName item, int n_max_chars, int hp, int vp) { + wp.selectFont(visual_lo_info.get_element_font(item)); + SizeF text_size = new SizeF(wp.measureString(new String(_widest_elem, n_max_chars)).Width, wp.measureString(new String(_longest_elem, 1)).Height); + if (_prev_geometric_lo_info == null) + return new SizeF(text_size.Width + hp, text_size.Height + vp); + else { + SizeF old_max_size = _prev_geometric_lo_info.get_item_cell_size(item); + float new_width = text_size.Width + hp, new_height = text_size.Height + vp; + /// So a new size is set if the size increases or it decreases by g.t.e _min_size_dec_before_readj. + /// It is guarded by the _min_size_dec_before_readj buffer, so that the size doesnt continually shrink and expand. + new_width = (_pack_tight_ignoring_dec_jitters || new_width >= old_max_size.Width || old_max_size.Width - new_width >= _min_horizontal_size_decrement_before_resize) ? new_width : old_max_size.Width; + new_height = (_pack_tight_ignoring_dec_jitters || new_height >= old_max_size.Height || old_max_size.Height - new_height >= _min_vertical_size_decrement_before_resize) ? new_height : old_max_size.Height; + /// the following was done earlier (prior 4/17 - the size was never decreased) + //SizeF newSize = new SizeF(Math.Max(size.Width + hp, oldMaxSize.Width), Math.Max(size.Height + vp, oldMaxSize.Height)); + return new SizeF(new_width, new_height); + } + } + + #region Readonly Accessors + /// gets the size of the column (its the same across expirations) + public SizeF get_item_cell_size(NMSheetColumnName item) { + SizeF rv; + return _col_cell_size_map.TryGetValue(item, out rv) ? rv : new SizeF(0, 0); + } + + /// gets the starting X of a column (this is relative to within an exp) + public int get_item_x_in_exp(NMSheetVisualLayout visual_lo_info, NMSheetColumnName the_item) { + float rv = 0; + return Convert.ToInt32(_col_x_map.TryGetValue(the_item, out rv) ? rv : 0); + } + + /// this is the full vertical rectangle for a column, + /// it spans multiple strikes + /// (height = height of grid) + public Rectangle get_item_rectangle_in_grid(NMSheetVisualLayout visual_layout_info, int exp_no, NMSheetColumnName item) { + int item_x = (exp_no * cell_size.Width) + get_item_x_in_exp(visual_layout_info, item); + SizeF item_cell_size = get_item_cell_size(item); + return new Rectangle(item_x, 0, Convert.ToInt32(item_cell_size.Width), grid_size.Height); + } + + /// this is the full horizontal rectangle for a strike, + /// it spans across all expirations and all columns + /// (width = width of grid) + public Rectangle get_strike_rectangle_in_grid(int strike_no) { + return new Rectangle(0, (cell_size.Height * strike_no), grid_size.Width, cell_size.Height); + } + + public Size get_header_size() { return _header_size; } + + /// gets the text size of the expirations + public SizeF[] get_exp_text_sizes() { return _exp_size_arr; } + + /// Given all visible cols, and an bitmap_x in the bitmap, + /// it returns the column that falls on that bitmap_x + public bool get_column(int bitmap_x, NMSheetColumnName[] all_cols, ref NMSheetColumnName col) { + bitmap_x = bitmap_x % cell_size.Width; + foreach (NMSheetColumnName c in all_cols) { + float col_x; + SizeF col_size; + if (_col_x_map.TryGetValue(c, out col_x) && _col_cell_size_map.TryGetValue(c, out col_size)) + if (bitmap_x >= col_x && bitmap_x <= col_x + col_size.Width) { + col = c; + return true; + } + } + return false; + } + + #endregion + } +} \ No newline at end of file diff --git a/src/client/spark/NMSheets/UIComponents/MainSheet/NMSheetQuoterHelper.cs b/src/client/spark/NMSheets/UIComponents/MainSheet/NMSheetQuoterHelper.cs new file mode 100644 index 000000000..762121d10 --- /dev/null +++ b/src/client/spark/NMSheets/UIComponents/MainSheet/NMSheetQuoterHelper.cs @@ -0,0 +1,149 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Runtime.InteropServices; +using bts.api; +using bts.utils; + +namespace BCG { + public class NMSheetQuoterHelper { + private static HashSet _quoteset_resolved_edge_col_map = new HashSet( + new NMSheetColumnName[] + { + NMSheetColumnName.call_quoteset_resolved_bid_edge, + NMSheetColumnName.call_quoteset_resolved_ask_edge, + NMSheetColumnName.put_quoteset_resolved_bid_edge, + NMSheetColumnName.put_quoteset_resolved_ask_edge + }); + private static HashSet _quoteset_resolved_size_col_map = new HashSet( + new NMSheetColumnName[] + { + NMSheetColumnName.call_quoteset_resolved_bid_size, + NMSheetColumnName.call_quoteset_resolved_ask_size, + NMSheetColumnName.put_quoteset_resolved_bid_size, + NMSheetColumnName.put_quoteset_resolved_ask_size, + }); + private static HashSet _quoter_set_edge_col_map = new HashSet( + new NMSheetColumnName[] + { + NMSheetColumnName.call_quoter_set_bid_edge, + NMSheetColumnName.call_quoter_set_ask_edge, + NMSheetColumnName.put_quoter_set_bid_edge, + NMSheetColumnName.put_quoter_set_ask_edge + }); + private static HashSet _quoter_set_size_col_map = new HashSet( + new NMSheetColumnName[] + { + NMSheetColumnName.call_quoter_set_bid_size, + NMSheetColumnName.call_quoter_set_ask_size, + NMSheetColumnName.put_quoter_set_bid_size, + NMSheetColumnName.put_quoter_set_ask_size, + }); + private static NMSheetColumnName[] _quoter_price_col_map = new NMSheetColumnName[] + { + NMSheetColumnName.call_quoter_bid_price, + NMSheetColumnName.call_quoter_ask_price, + NMSheetColumnName.put_quoter_bid_price, + NMSheetColumnName.put_quoter_ask_price + }; + private static NMSheetColumnName[] _quoter_size_col_map = new NMSheetColumnName[] + { + NMSheetColumnName.call_quoter_bid_size, + NMSheetColumnName.call_quoter_ask_size, + NMSheetColumnName.put_quoter_bid_size, + NMSheetColumnName.put_quoter_ask_size, + }; + + private static void _parse_quoter_col(NMSheetColumnName col, out bool is_call, out bool is_put, + out bool is_bid, out bool is_ask) { + is_call = is_put = is_bid = is_ask = false; + if (col == NMSheetColumnName.call_theo || col == NMSheetColumnName.call_quoteset_mid_price) + is_call = is_bid = is_ask = true; + else if (col == NMSheetColumnName.put_theo || col == NMSheetColumnName.put_quoteset_mid_price) + is_put = is_bid = is_ask = true; + else if (col == NMSheetColumnName.strike) + is_call = is_put = is_bid = is_ask = true; + else + NMSheetSettingColumnOrganization.parse_column(col, out is_call, out is_put, out is_bid, out is_ask); + } + + public static IEnumerable get_quoteset_edge_size_cols() { return CollectionHelper.append_arrays(_quoteset_resolved_edge_col_map, _quoteset_resolved_size_col_map); } + + public static IEnumerable get_quoter_set_edge_size_cols() { return CollectionHelper.append_arrays(_quoter_set_edge_col_map, _quoter_set_size_col_map); } + + public static IEnumerable get_quoter_price_size_cols() { return CollectionHelper.append_arrays(_quoter_price_col_map, _quoter_size_col_map); } + + public static IEnumerable get_selected_securities(IDictionary>> selection_map, + Func get_secside_key) { + HashSet rv = new HashSet(); + foreach (KeyValuePair>> p in selection_map) { + NMSheetExpiration nmsheet_exp = p.Key; + foreach (KeyValuePair> col_map in p.Value) { + HashSet selected_strike_map = col_map.Value; + bool is_call, is_put, is_bid, is_ask; + _parse_quoter_col(col_map.Key, out is_call, out is_put, out is_bid, out is_ask); + foreach (double k in selected_strike_map) { + if (is_call) { + if (is_bid) + rv.Add(get_secside_key(nmsheet_exp, k, PutOrCall.Call, Side.Buy)); + if (is_ask) + rv.Add(get_secside_key(nmsheet_exp, k, PutOrCall.Call, Side.Sell)); + } + if (is_put) { + if (is_bid) + rv.Add(get_secside_key(nmsheet_exp, k, PutOrCall.Put, Side.Buy)); + if (is_ask) + rv.Add(get_secside_key(nmsheet_exp, k, PutOrCall.Put, Side.Sell)); + } + } + } + } + return rv; + } + + public static NMSheetSettings get_default_quoter_control_settings(int quoter_id, IEnumerable sym_list) { + NMSheetSettings rv = new NMSheetSettings(); + rv.setting_option_list = new List(sym_list); + rv.setting_quoter = new NMSheetSettingsQuoting(Convert.ToUInt32(quoter_id)); + rv.set_col_visibility(false, NMSheetSettingColumnOrganization.get_cols_for_type(NMSheetColumnType.BBO)); + rv.set_col_visibility(true, get_quoter_set_edge_size_cols()); + rv.set_col_visibility(true, get_quoter_price_size_cols()); + rv.set_col_visibility(false, new List { NMSheetColumnName.vol, NMSheetColumnName.vol_change }); + rv.setting_status_bar = new NMSheetSettingStatusBar() { show_statusbar = true, show_quote_data = true }; + rv.setting_mouse.classical_mode_scrolling_mouse_button = System.Windows.Forms.MouseButtons.Left; + rv.setting_mouse.enable_selection = true; + rv.setting_mouse.selection_mouse_button = System.Windows.Forms.MouseButtons.Right; + rv.setting_mouse.limit_selection_to_single_column = true; + rv.setting_layout.show_exp_atm_header = false; + return rv; + } + + #region Rounding + [DllImport("bts_conn.dll", CharSet = CharSet.Ansi)] + private static extern double raw_get_tick_size(double price, double min_price_increment, double display_factor, int vtt); + + [DllImport("bts_conn.dll", CharSet = CharSet.Ansi)] + private static extern double raw_round_to_quote_price(double p, double ts, Side buy_sell); + + internal static double round_price_to_market(Security security, Side side, double price, bool nan_if_not_found = false) { + return price; + // if (Double.IsNaN(price)) + // return Double.NaN; + // else { + // if (security != null) { + // double tick_size = 0; + // if (security.cme_vtt == 0) + // tick_size = raw_get_tick_size(price, security.cme_min_price_increment, security.display_factor, security.cme_vtt); + // else + // tick_size = raw_get_tick_size(price, 0, security.display_factor, security.cme_vtt); + // return raw_round_to_quote_price(price, tick_size, side); + // } else + // return nan_if_not_found ? Double.NaN : price; + // } + } + + #endregion + } +} diff --git a/src/client/spark/NMSheets/UIComponents/MainSheet/NMSheetTheoGrid.cs b/src/client/spark/NMSheets/UIComponents/MainSheet/NMSheetTheoGrid.cs new file mode 100644 index 000000000..68c2b43b0 --- /dev/null +++ b/src/client/spark/NMSheets/UIComponents/MainSheet/NMSheetTheoGrid.cs @@ -0,0 +1,352 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.ComponentModel; +using System.Drawing; +using System.Data; +using System.Windows.Forms; +using System.Drawing.Imaging; +using System.Drawing.Drawing2D; + +using BCG.Utilities; +using BCG.Utilities.General; + +namespace BCG { + public partial class NMSheetTheoGrid : System.Windows.Forms.UserControl { + public enum Gesture { + Left, + Right, + Up, + Down + } + + private readonly bool _is_remoted = mbts.config.Configuration.get().is_remote_app; + private readonly PerfStatsLogger _recorder = new PerfStatsLogger(); + private readonly HighPerformanceTimer _timer = new HighPerformanceTimer(); + private System.ComponentModel.Container components = null; + + private NMSheetFormattedTheos _formatted_theos; + private NMSheetGeometricLayout _geo_layout_info; + private NMSheetVisualLayout _visual_layout_info; + private NMSheetTheoGridSelectionMap _selected_items_map = NMSheetTheoGridSelectionMap.get_empty_map(); + + private NMSheetSettings _settings = new NMSheetSettings(); + private int _horizontal_scroll_step, _vertical_scroll_step; + + // _visible_rect_topleft is the position inside + // the bitmap that corresponds to 0,exp_header.Width on this control. + private Point _visible_rect_topleft = new Point(); + + // _scroll_position is an intermediate bitmap position + // between an initial point where a scroll request + // was issued and _visible_rect_topleft. In a steady + // state _scroll_position == _visible_rect_topleft + private Point _scroll_position = new Point(); + private bool _is_set_for_quoting; + + public delegate void TheoGridDelegate(object sender, object[] args); + public event Action> onMouseUp; + public event Action> onDoubleClick; + public event Action onMouseUpOutsideBitmap = (b) => { }; + public event Action onMouseMove; + public event TheoGridDelegate onDisplayChange; + public event Action> onGesture; + + public NMSheetTheoGrid() { + Name = "TheoGrid"; + Size = new Size(150, 152); + SetStyle(ControlStyles.UserPaint, true); + SetStyle(ControlStyles.AllPaintingInWmPaint, true); + SetStyle(ControlStyles.Opaque, true); + SetStyle(ControlStyles.DoubleBuffer, true); + } + + public void init() { _assign_events(); } + + internal void reset_data(NMSheetSettings settings, NMSheetVisualLayout visual_lo_info, NMSheetFormattedTheos formatted_theos, NMSheetGeometricLayout geometric_lo_info) { + _settings = settings; + _cache_alert_settings(settings); + _is_set_for_quoting = _settings.setting_quoter.is_quoter_enabled(); + if (settings != null && visual_lo_info != null && formatted_theos != null && geometric_lo_info != null) { + _visual_layout_info = visual_lo_info; + _formatted_theos = formatted_theos; + _geo_layout_info = geometric_lo_info; + + _timer.start(); + /// if the cache is invalidated, the selection is cleared + if (new MyCacheInvalidationHelperData(_formatted_theos, _geo_layout_info, _settings).is_cache_invalidated(_cache_invalidation_data)) + _selected_items_map = NMSheetTheoGridSelectionMap.get_empty_map(); + _scroller.reset_settings(_settings); + double hit_ratio = _draw_on_bitmap(); + Invalidate(); + _timer.stop(); + _recorder.log("NMSheetTheoGridDraw.HitRatio", "NMSheetTheoGridDraw.HitRatio", hit_ratio); + _recorder.log("NMSheetTheoGridDraw.DrawTime", "NMSheetTheoGridDraw.DrawTime", _timer.lastIntervalTime); + } + } + + private void _assign_events() { + MouseDown += _on_mousedown; + _scroller = new MyMouseDragger(this); + Resize += (s, e) => { + if (has_layout()) + _fire_display_change_event(); + }; + DoubleClick += _on_doubleclick; + MouseUp += _on_mouseup; + MouseWheel += _on_mousewheel; + MouseMove += _on_mouse_move; + _scroller.on_drag_start += _on_drag_start; + _scroller.on_drag_continue += _on_drag_continue; + KeyDown += _on_keydown; + if (TC2Settings.instance.get_scroll_mode() == SheetsScrollMode.Gesture) + onGesture += _on_gesture; + } + + protected override void OnPaintBackground(PaintEventArgs pevent) { } + + protected override void OnPaint(PaintEventArgs e) { + /// aside from the jump_to, this is the only + /// place where the _scroll_position is changed + if (_geo_layout_info != null) { + e.Graphics.Clear(SystemColors.ControlDark); + + if (Math.Abs(_scroll_position.X - _visible_rect_topleft.X) < _horizontal_scroll_step) + _scroll_position.X = _visible_rect_topleft.X; + + if (Math.Abs(_scroll_position.Y - _visible_rect_topleft.Y) < _vertical_scroll_step) + _scroll_position.Y = _visible_rect_topleft.Y; + + _copy_bitmap_to_screen(e.Graphics); + _paint_directly(e.Graphics); + _fire_display_change_event(); + if (!(_scroll_position.X == _visible_rect_topleft.X && _scroll_position.Y == _visible_rect_topleft.Y)) { + _scroll_position.X += _horizontal_scroll_step * Math.Sign(_visible_rect_topleft.X - _scroll_position.X); + _scroll_position.Y += _vertical_scroll_step * Math.Sign(_visible_rect_topleft.Y - _scroll_position.Y); + Invalidate(); + } + } else + e.Graphics.Clear(Color.Beige); + } + + private void _paint_directly(Graphics g) { + _paint_selected_region_directly(g); + _paint_atm_background_directly(g); + } + + /// "Directly" because this does not deal with + /// bitmaps but paints directly to the screen + private void _paint_selected_region_directly(Graphics g) { + if (_selected_items_map.is_active()) { + Color select_color = _settings.setting_grid_internal.selection_back_color.HasValue ? _settings.setting_grid_internal.selection_back_color.Value : Color.CornflowerBlue; + SolidBrush semi_trans_brush = new SolidBrush(Color.FromArgb(128, select_color)); + List screen_rect_list = new List(); + IEnumerable bm_rect_list = _selected_items_map.get_selected_bitmap_rectangles(_formatted_theos, _geo_layout_info, _visual_layout_info); + foreach (Rectangle bm_rect in bm_rect_list) { + Rectangle screen_rect = _convert_to_control_rect(bm_rect); + if (screen_rect.Width > 0 && screen_rect.Height > 0) + screen_rect_list.Add(screen_rect); + } + if (screen_rect_list.Count > 0) + g.FillRectangles(semi_trans_brush, screen_rect_list.ToArray()); + } + } + + #region navigation + + private bool _is_navigation_mode_jump() { + NMSheetSettingGridInternal.NavigationMode navigation_mode = _settings.setting_grid_internal.navigation_mode; + return navigation_mode == NMSheetSettingGridInternal.NavigationMode.Auto ? _is_remoted : (navigation_mode == NMSheetSettingGridInternal.NavigationMode.Jump) ? true : false; + } + + public void jump_by_contract(double n_expirations, double n_strikes) { + if (_geo_layout_info == null) + return; + + Point delta = new Point(); + if (this.Width < _geo_layout_info.grid_size.Width) + delta.X = (int)(_geo_layout_info.cell_size.Width * n_expirations); + else + delta.X = 0; + + if (this.Height < _geo_layout_info.grid_size.Height) + delta.Y = (int)(_geo_layout_info.cell_size.Height * n_strikes); + else + delta.Y = 0; + + jump_to_point(new Point(_visible_rect_topleft.X + delta.X, _visible_rect_topleft.Y + delta.Y)); + } + + public void navigate_to_expiration(NMSheetExpiration target_expiration) { + if (_geo_layout_info != null && _formatted_theos != null) { + int cell_width = _geo_layout_info.cell_size.Width; + int target_exp_index = Array.IndexOf(_formatted_theos.sorted_expirations, target_expiration); + if (target_exp_index >= 0 && target_exp_index < _formatted_theos.sorted_expirations.Length) { + Point target_point = new Point(target_exp_index * cell_width, _visible_rect_topleft.Y); + if (_is_navigation_mode_jump()) + jump_to_point(target_point); + else + scroll_to_point(target_point); + } + } + } + + public void navigate_to_expiration_target(NMSheetExpiration expiration_at_target_location, NMSheetExpiration target_expiration) { + if (_geo_layout_info != null && _formatted_theos != null) { + /// this is the same as moving the moving_expiration all the + /// way to the start and then adjusting for the dest_expiration's offset from the start + int cell_width = _geo_layout_info.cell_size.Width; + int expiration_at_target_location_index = Array.IndexOf(_formatted_theos.sorted_expirations, expiration_at_target_location), + target_expiration_index = Array.IndexOf(_formatted_theos.sorted_expirations, target_expiration); + int target_offset = (target_expiration_index - expiration_at_target_location_index) * cell_width + _visible_rect_topleft.X; + Point target_point = new Point(target_offset, _visible_rect_topleft.Y); + if (_is_navigation_mode_jump()) + jump_to_point(target_point); + else + scroll_to_point(target_point); + } + } + + public void navigate_to_strike(double target_strike, double ratio_from_top) { + if (_geo_layout_info != null && _formatted_theos != null) { + double[] all_strikes = _formatted_theos.sorted_strikes; + int cell_height = _geo_layout_info.cell_size.Height; + int n_visible_strikes = (Height - _geo_layout_info.get_header_size().Height) / cell_height; + int n_visible_strikes_above_target = Convert.ToInt32(n_visible_strikes * ratio_from_top) - 1; /// geometrically above, numerically below + int target_strike_index = Array.IndexOf(all_strikes, target_strike); + int strike_at_top_index = Math.Max(0, target_strike_index - n_visible_strikes_above_target); + if (strike_at_top_index >= 0 && strike_at_top_index < all_strikes.Length) { + Point target_point = new Point(_visible_rect_topleft.X, strike_at_top_index * cell_height); + if (_is_navigation_mode_jump()) + jump_to_point(target_point); + else + scroll_to_point(target_point); + } + } + } + + private void _slide_scroll(Point start, Point dx) { + System.Diagnostics.Trace.WriteLine(String.Format("{0}->{1}", start, dx)); + if (_geo_layout_info == null) + return; + + Point delta = new Point(); + if (this.Width < _geo_layout_info.grid_size.Width) { + delta.X = dx.X; + if (Math.Abs(dx.X) > _settings.setting_grid_internal.distance_for_page) + delta.X = this.Width * Math.Sign(dx.X); + else + delta.X = _geo_layout_info.cell_size.Width * Math.Sign(dx.X); + } else + delta.X = 0; + + if (this.Height < _geo_layout_info.grid_size.Height) { + delta.Y = dx.Y; + if (Math.Abs(dx.Y) > _settings.setting_grid_internal.distance_for_page) + delta.Y = this.Height * Math.Sign(dx.Y); + else + delta.Y = _geo_layout_info.cell_size.Height * Math.Sign(dx.Y); + } else + delta.Y = 0; + scroll_to_point(new Point(_visible_rect_topleft.X + delta.X, _visible_rect_topleft.Y + delta.Y)); + } + + private enum MyGridScrollMode { Scroll = 0, Jump } + private void _move_to_point(Point candidate_position, MyGridScrollMode move_mode) { + if (_geo_layout_info != null) { + candidate_position.X = Math.Max(0, candidate_position.X); + candidate_position.X = Math.Min(Math.Max(_geo_layout_info.grid_size.Width - Width, 0), candidate_position.X); + candidate_position.Y = Math.Max(0, candidate_position.Y); + candidate_position.Y = Math.Min(Math.Max(_geo_layout_info.grid_size.Height - Height + _geo_layout_info.get_header_size().Height, 0), candidate_position.Y); + int n_frames = _settings.setting_grid_internal.scroll_max_frames; + if (candidate_position.X != _visible_rect_topleft.X || candidate_position.Y != _visible_rect_topleft.Y) { + if (move_mode == MyGridScrollMode.Scroll) { + _horizontal_scroll_step = Math.Max(Math.Abs(candidate_position.X - _visible_rect_topleft.X) / n_frames, + _settings.setting_grid_internal.horizontal_scroll_step); + _vertical_scroll_step = Math.Max(Math.Abs(candidate_position.Y - _visible_rect_topleft.Y) / n_frames, + _settings.setting_grid_internal.vertical_scroll_step); + } else if (move_mode == MyGridScrollMode.Jump) + _horizontal_scroll_step = _vertical_scroll_step = Int32.MaxValue; + else { + bts.Log.Ui.error("Incorrect Scroll mode"); + return; + } + _visible_rect_topleft = candidate_position; + Invalidate(); + } + } + } + + public void scroll_to_point(Point candidate_position) { _move_to_point(candidate_position, MyGridScrollMode.Scroll); } + + public void jump_to_point(Point candidate_position) { _move_to_point(candidate_position, MyGridScrollMode.Jump); } + + #endregion + + private void _fire_display_change_event() { + if (onDisplayChange != null && _geo_layout_info != null && _geo_layout_info.grid_size.Width > 0 && _geo_layout_info.grid_size.Height > 0) { + object[] grid_size = new object[] { + (double) _scroll_position.X / _geo_layout_info.grid_size.Width, + (double) _scroll_position.Y / _geo_layout_info.grid_size.Height, + (double) (_scroll_position.X + this.Width) / _geo_layout_info.grid_size.Width, + (double) (_scroll_position.Y + this.Height - _geo_layout_info.get_header_size().Height) / _geo_layout_info.grid_size.Height, + _geo_layout_info.cell_size.Width, + _geo_layout_info.grid_size.Width + }; + onDisplayChange(this, grid_size); + } + } + + private double _get_strike_from_index(int strike_index) { + return _formatted_theos.sorted_strikes.Length == 0 ? 0 : _formatted_theos.sorted_strikes[Math.Min(strike_index, _formatted_theos.sorted_strikes.Length - 1)]; + } + + #region Public accessors + + public bool has_layout() { return _geo_layout_info != null; } + + public int get_exp_index() { return (int)((_scroll_position.X + _geo_layout_info.cell_size.Width * .55) / _geo_layout_info.cell_size.Width); } + + public IDictionary>> get_selection_map() { + return _selected_items_map.get_selection_map(_formatted_theos); + } + + internal NMSheetTheoGridSelectionMap get_selection_map_data() { return _selected_items_map; } + + public Point get_last_mouse_clicked_point() { return _last_mousedown_control_coords; } + + /// [viewable_rect_left, viewable_rect_top, viewable_rect_width, viewable_rect_height, + /// cell_width, cell_height, total_width, total_height] + public double[] get_position_details() { + return new double[] { + Convert.ToDouble (_scroll_position.X), + Convert.ToDouble (_scroll_position.Y), + Convert.ToDouble (Width), + Convert.ToDouble (Height - _geo_layout_info.get_header_size().Height), + Convert.ToDouble (_geo_layout_info.cell_size.Width), + Convert.ToDouble (_geo_layout_info.cell_size.Height), + Convert.ToDouble (_geo_layout_info.grid_size.Width), + Convert.ToDouble (_geo_layout_info.grid_size.Height) + }; + } + + public void get_lowest_and_highest_visible_strikes(out double lowest, out double highest) { + Point top_of_window = _scroll_position; + Point bottom_of_window = new Point(_scroll_position.X, top_of_window.Y + Size.Height); + lowest = _get_strike_from_index(top_of_window.Y / _geo_layout_info.cell_size.Height); + highest = _get_strike_from_index((top_of_window.Y + Size.Height) / _geo_layout_info.cell_size.Height); + } + + #endregion + + #region IDisposable + protected override void Dispose(bool disposing) { + if (disposing) { + if (components != null) + components.Dispose(); + } + base.Dispose(disposing); + } + #endregion + } +} \ No newline at end of file diff --git a/src/client/spark/NMSheets/UIComponents/MainSheet/NMSheetTheoGrid.resx b/src/client/spark/NMSheets/UIComponents/MainSheet/NMSheetTheoGrid.resx new file mode 100644 index 000000000..eadcc1c10 --- /dev/null +++ b/src/client/spark/NMSheets/UIComponents/MainSheet/NMSheetTheoGrid.resx @@ -0,0 +1,130 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + False + + + True + + + True + + + 80 + + + (Default) + + + False + + + Private + + + TheoGrid + + + 8, 8 + + \ No newline at end of file diff --git a/src/client/spark/NMSheets/UIComponents/MainSheet/NMSheetTheoGridAlerts.cs b/src/client/spark/NMSheets/UIComponents/MainSheet/NMSheetTheoGridAlerts.cs new file mode 100644 index 000000000..6526ce862 --- /dev/null +++ b/src/client/spark/NMSheets/UIComponents/MainSheet/NMSheetTheoGridAlerts.cs @@ -0,0 +1,201 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.ComponentModel; +using System.Drawing; +using System.Data; +using System.Windows.Forms; +using System.Drawing.Imaging; +using System.Drawing.Drawing2D; + +using BCG.Utilities; +using BCG.Utilities.General; + + +namespace BCG { + /// All the alert detection code resides here + /// _get_back_color_override is the only + /// function called externally + public partial class NMSheetTheoGrid { + private uint _n_proximity_alert_ticks = 0; + private class MyAlertHelperData { + private static HashSet _ee_set_edge_size_cols = new HashSet( + new NMSheetColumnName[] {NMSheetColumnName.call_ee_set_bid_edge, NMSheetColumnName.call_ee_set_bid_size, + NMSheetColumnName.call_ee_set_ask_edge, NMSheetColumnName.call_ee_set_ask_size, + NMSheetColumnName.put_ee_set_bid_edge, NMSheetColumnName.put_ee_set_bid_size, + NMSheetColumnName.put_ee_set_ask_edge, NMSheetColumnName.put_ee_set_ask_size}); + private static HashSet _ee_price_cols = new HashSet( + new NMSheetColumnName[] {NMSheetColumnName.call_ee_bid_price, + NMSheetColumnName.call_ee_ask_price, + NMSheetColumnName.put_ee_bid_price, + NMSheetColumnName.put_ee_ask_price}); + public bool is_theo = false; + public bool is_bbo = false; + public bool is_quoteset_mid_price = false; + public bool is_quoteset_edge_or_size = false; + public bool is_quoter_price_or_size = false; + public bool is_quoter_set_edge_or_size = false; + public bool is_ee_set_edge_or_size = false; + public bool is_ee_price = false; + + public bool is_size = false; + public bool is_call = false; + public bool is_bid = false; + + public MyAlertHelperData(NMSheetColumnName col_name) { + NMSheetColumnType col_type = NMSheetSettingColumnOrganization.get_col_type(col_name); + bool temp_is_put, temp_is_ask; + /// for the purpose of this (just because we know the cols that can are painted on alerts, + /// we can make the assumption that a col is either is_call or is_put but not both (same with is_bid and is_ask) + NMSheetSettingColumnOrganization.parse_column(col_name, out is_call, out temp_is_put, out is_bid, out temp_is_ask); + is_size = col_name.ToString().Contains("size"); + if (col_type == NMSheetColumnType.Greeks) { + is_theo = col_name == NMSheetColumnName.call_theo || col_name == NMSheetColumnName.put_theo; + } else if (col_type == NMSheetColumnType.BBO) { + is_bbo = true; + } else if (col_type == NMSheetColumnType.Quoteset) { + is_quoteset_edge_or_size = new HashSet(NMSheetQuoterHelper.get_quoteset_edge_size_cols()).Contains(col_name); + is_quoteset_mid_price = (col_name == NMSheetColumnName.call_quoteset_mid_price || col_name == NMSheetColumnName.put_quoteset_mid_price); + } else if (col_type == NMSheetColumnType.Quoter) { + is_quoter_price_or_size = new HashSet(NMSheetQuoterHelper.get_quoter_price_size_cols()).Contains(col_name); + is_quoter_set_edge_or_size = new HashSet(NMSheetQuoterHelper.get_quoter_set_edge_size_cols()).Contains(col_name); + } else if (col_type == NMSheetColumnType.EE) { + is_ee_set_edge_or_size = _ee_set_edge_size_cols.Contains(col_name); + is_ee_price = _ee_price_cols.Contains(col_name); + } + } + } + + private void _cache_alert_settings(NMSheetSettings settings) { + _n_proximity_alert_ticks = settings.setting_alerts.n_proximity_alert_max_ticks.Value; + } + + private bool _get_back_color_override(NMSheetSettings settings, MyAlertHelperData helper_data, NMSheetColumnName col_name, int exp_no, int strike_no, ref Color out_color) { + if (_get_quoter_switch_override(settings, helper_data, exp_no, strike_no, ref out_color)) + return true; + if (_get_ee_switch_override(settings, helper_data, exp_no, strike_no, ref out_color)) + return true; + if (_get_trade_alert_override(settings, helper_data, exp_no, strike_no, ref out_color)) + return true; + if (_get_cross_alert_color_override(settings, helper_data, exp_no, strike_no, ref out_color)) + return true; + return false; + } + + private bool _get_ee_switch_override(NMSheetSettings settings, MyAlertHelperData helper_data, int exp_index, int strike_index, ref Color out_color) { + if (helper_data.is_ee_set_edge_or_size || helper_data.is_ee_price) { + NMSheetRowAuxiliaryData aux_data = _formatted_theos.get_aux_data(exp_index, strike_index); + if (aux_data != null) { + NMSheetCallPutBidAskWrapper eye_data = aux_data.task_ee_data; + if (eye_data != null) { + NMSheetTaskEyeData secside_eye_data = eye_data.get_data(helper_data.is_call, helper_data.is_bid); + if (secside_eye_data != null && secside_eye_data.eye_data != null) { + if (helper_data.is_ee_price) { + if (secside_eye_data.is_eye_cross) { + out_color = _settings.setting_alerts.ee_fire_color.Value; + return true; + } + } + if (secside_eye_data.eye_data.is_on) { + out_color = _settings.setting_alerts.ee_on_color.Value; + return true; + } + } + } + } + } + return false; + } + + private bool _get_quoter_switch_override(NMSheetSettings settings, MyAlertHelperData helper_data, int exp_index, int strike_index, ref Color out_color) { + if (helper_data.is_quoter_price_or_size || helper_data.is_quoter_set_edge_or_size) { + NMSheetRowAuxiliaryData aux_data = _formatted_theos.get_aux_data(exp_index, strike_index); + if (aux_data != null) { + NMSheetCallPutBidAskWrapper sheet_quoter_data = aux_data.task_quoter_data; + if (sheet_quoter_data != null) { + NMSheetTaskQuoterData secside_quoter_data = sheet_quoter_data.get_data(helper_data.is_call, helper_data.is_bid); + if (secside_quoter_data != null && secside_quoter_data.quoter_data != null) { + if (secside_quoter_data.quoter_data.is_on) { + out_color = _settings.setting_alerts.ee_on_color.Value; + return true; + } + } + } + } + } + return false; + } + + private bool _get_trade_alert_override(NMSheetSettings settings, MyAlertHelperData helper_data, int exp_index, int strike_index, ref Color out_color) { + if (helper_data.is_theo) { + NMSheetTradeAlert ticker_alert = _formatted_theos.get_trade_alert(exp_index, strike_index, helper_data.is_call); + if (ticker_alert == NMSheetTradeAlert.None) + return false; + else if (ticker_alert == NMSheetTradeAlert.OverTheo) { + out_color = settings.setting_alerts.trade_price_over_theo_alert_color.Value; + return true; + } else if (ticker_alert == NMSheetTradeAlert.UnderTheo) { + out_color = settings.setting_alerts.trade_price_under_theo_alert_color.Value; + return true; + } + } + return false; + } + + private bool _get_cross_alert_color_override(NMSheetSettings settings, MyAlertHelperData helper_data, int exp_no, int strike_no, ref Color out_color) { + if (settings.setting_alerts.alert_display_value == CrossAlertPaintMode.None) { + return false; + } else if (settings.setting_alerts.alert_display_value == CrossAlertPaintMode.Price && helper_data.is_bbo && !helper_data.is_size) { + if (helper_data.is_bid) { + NMSheetTheoBBOCross cross_state = _formatted_theos.get_theo_md_cross_state(exp_no, strike_no, helper_data.is_call); + { + if (cross_state.cross_state == NMSheetTheoBBOCross.CrossState.none) { + return false; + } else if (cross_state.cross_state == NMSheetTheoBBOCross.CrossState.bid_cross) { + out_color = settings.setting_alerts.sell_alert_color; + return true; + } else if (cross_state.cross_state == NMSheetTheoBBOCross.CrossState.bid_proximity && cross_state.tick_distance <= _n_proximity_alert_ticks) { + out_color = settings.setting_alerts.proximity_sell_alert_color.Value; + return true; + } else + return false; + } + } else { + NMSheetTheoBBOCross cross_state = _formatted_theos.get_theo_md_cross_state(exp_no, strike_no, helper_data.is_call); + { + if (cross_state.cross_state == NMSheetTheoBBOCross.CrossState.none) { + return false; + } else if (cross_state.cross_state == NMSheetTheoBBOCross.CrossState.ask_cross) { + out_color = settings.setting_alerts.buy_alert_color; + return true; + } else if (cross_state.cross_state == NMSheetTheoBBOCross.CrossState.ask_proximity && cross_state.tick_distance <= _n_proximity_alert_ticks) { + out_color = settings.setting_alerts.proximity_buy_alert_color.Value; + return true; + } else + return false; + } + } + } else if (settings.setting_alerts.alert_display_value == CrossAlertPaintMode.Theo && helper_data.is_theo || + settings.setting_alerts.alert_display_value == CrossAlertPaintMode.QuotesetMid && helper_data.is_quoteset_mid_price) { + NMSheetTheoBBOCross cross_data = _formatted_theos.get_theo_md_cross_state(exp_no, strike_no, helper_data.is_call); + if (cross_data.cross_state == NMSheetTheoBBOCross.CrossState.none) { + return false; + } + if (cross_data.cross_state == NMSheetTheoBBOCross.CrossState.ask_cross) { + out_color = settings.setting_alerts.buy_alert_color; + return true; + } else if (cross_data.cross_state == NMSheetTheoBBOCross.CrossState.bid_cross) { + out_color = settings.setting_alerts.sell_alert_color; + return true; + } else if (cross_data.cross_state == NMSheetTheoBBOCross.CrossState.bid_proximity && cross_data.tick_distance <= _n_proximity_alert_ticks) { + out_color = settings.setting_alerts.proximity_sell_alert_color.Value; + return true; + } else if (cross_data.cross_state == NMSheetTheoBBOCross.CrossState.ask_proximity && cross_data.tick_distance <= _n_proximity_alert_ticks) { + out_color = settings.setting_alerts.proximity_buy_alert_color.Value; + return true; + } + } + return false; + } + } +} \ No newline at end of file diff --git a/src/client/spark/NMSheets/UIComponents/MainSheet/NMSheetTheoGridBitmapDrawing.cs b/src/client/spark/NMSheets/UIComponents/MainSheet/NMSheetTheoGridBitmapDrawing.cs new file mode 100644 index 000000000..1cd278301 --- /dev/null +++ b/src/client/spark/NMSheets/UIComponents/MainSheet/NMSheetTheoGridBitmapDrawing.cs @@ -0,0 +1,278 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.ComponentModel; +using System.Drawing; +using System.Data; +using System.Windows.Forms; +using System.Drawing.Imaging; +using System.Drawing.Drawing2D; +using bts.utils; + +using BCG.Utilities; +using BCG.Utilities.General; + +namespace BCG { + /// All the bitmap manipulation code resides here + /// This is pretty much standalone, the first 2 + /// functions are called externally + partial class NMSheetTheoGrid { + /// + /// This keeps data such that if any of that changes + /// the changes the whole cache is invalidated + /// + private class MyCacheInvalidationHelperData { + private readonly HashSet _exp_map; + private readonly HashSet _strike_map; + private readonly NMSheetGeometricLayout _geo_layout_info; + private readonly NMSheetSettings _settings; + + public MyCacheInvalidationHelperData(NMSheetFormattedTheos theo_data, NMSheetGeometricLayout geo_layout_info, NMSheetSettings settings) { + _exp_map = new HashSet(theo_data.sorted_expirations); + _strike_map = new HashSet(theo_data.sorted_strikes); + _geo_layout_info = geo_layout_info; + _settings = settings; + } + + public bool is_cache_invalidated(MyCacheInvalidationHelperData prev_data) { + return prev_data == null || + !_geo_layout_info.cell_layout_is_same(prev_data._geo_layout_info) || + _settings != prev_data._settings || + !CollectionHelper.hashset_equals(_exp_map, prev_data._exp_map) || + !CollectionHelper.hashset_equals(_strike_map, prev_data._strike_map); + } + } + + private struct CellInfo { + public string text; + public Color back_color; + public bool is_equal(string other_text, Color other_back_color) { return text == other_text && back_color == other_back_color; } + } + CellInfo[] _cell_paint_cache; + + // this is used to write the grid bitmaps to an + // offscreen bitmap + private IGraphicsWrapper _grid_bitmap_wrapper = null; + // the size of the bitmap used for the grid + private Size _grid_bitmap_size = new Size(0, 0); + // this is used to write the grid bitmaps to an + // offscreen bitmap + private IGraphicsWrapper _header_bitmap_wrapper = null; + // the size of the bitmap used for the grid + private Size _header_bitmap_size = new Size(0, 0); + private MyCacheInvalidationHelperData _cache_invalidation_data; + + private double _draw_on_bitmap() { + if (_grid_bitmap_wrapper == null || + _geo_layout_info.grid_size.Width > _grid_bitmap_size.Width || + _geo_layout_info.grid_size.Height > _grid_bitmap_size.Height || + _geo_layout_info.get_header_size().Height > _header_bitmap_size.Height || + _geo_layout_info.get_header_size().Width > _header_bitmap_size.Width) { + _grid_bitmap_size = new Size((int)(_geo_layout_info.grid_size.Width * TC2Settings.instance.horizontalBitmapGrowthCushion), + (int)(_geo_layout_info.grid_size.Height * TC2Settings.instance.verticalBitmapGrowthCushion)); + if (_grid_bitmap_wrapper != null) + _grid_bitmap_wrapper.Dispose(); + _grid_bitmap_wrapper = new GDI32BitWrapper(this.CreateGraphics(), _grid_bitmap_size.Width, _grid_bitmap_size.Height); + _header_bitmap_size = new Size((int)(_geo_layout_info.get_header_size().Width * TC2Settings.instance.horizontalBitmapGrowthCushion), + (int)(_geo_layout_info.get_header_size().Height * TC2Settings.instance.verticalBitmapGrowthCushion)); + if (_header_bitmap_wrapper != null) + _header_bitmap_wrapper.Dispose(); + _header_bitmap_wrapper = new GDI32BitWrapper(this.CreateGraphics(), _header_bitmap_size.Width, _header_bitmap_size.Height); + } + _draw_header(_header_bitmap_wrapper); + double hit_ratio = _draw_grid_fast(_grid_bitmap_wrapper); + return hit_ratio; + } + + private void _copy_bitmap_to_screen(Graphics g) { + _header_bitmap_wrapper.paint(g, _scroll_position.X, 0, 0, 0, + Math.Min(this.Width, _geo_layout_info.get_header_size().Width - _scroll_position.X), + Math.Min(this.Height, _geo_layout_info.get_header_size().Height)); + _grid_bitmap_wrapper.paint(g, _scroll_position.X, _scroll_position.Y, 0, Math.Min(this.Height, _geo_layout_info.get_header_size().Height), + Math.Min(this.Width, _geo_layout_info.grid_size.Width - _scroll_position.X), + Math.Min(this.Height - _geo_layout_info.get_header_size().Height, _geo_layout_info.grid_size.Height - _scroll_position.Y)); + } + + private void _draw_header(IGraphicsWrapper w) { + double start_ms = _timer.runningMilliseconds(), stop_ms; + w.selectPen(w.createPen(_settings.setting_grid_internal.row_seperator_line_color /*cfg.lineColor*/)); + w.selectFont(_settings.setting_expiration_header.expiration_font /*cfg.HeaderFont*/); + w.set_text_align(_convert_horizontal_alignment_setting_to_mask(NMSheetSettingGridInternal.NMSheetGridHorizontalTextAlignment.Left)); + + SizeF[] exp_text_sizes = _geo_layout_info.get_exp_text_sizes(); + + for (int x = 0, i = 0; i < _formatted_theos.sorted_formatted_expirations.Length; i++, x += _geo_layout_info.cell_size.Width) { + Color exp_back_color = i % 2 == 0 ? _settings.setting_expiration_header.expiration_background_color_1 : _settings.setting_expiration_header.expiration_background_color_2; + w.selectBrush(w.createSolidBrush(exp_back_color)); + w.fillRectangle(x, 0, _geo_layout_info.cell_size.Width, _geo_layout_info.get_header_size().Height); + w.setTextColor(i % 2 == 0 ? _settings.setting_expiration_header.expiration_font_color_1 : _settings.setting_expiration_header.expiration_font_color_2); + if (x > 0) + w.drawLine(x, 0, x, _geo_layout_info.get_header_size().Height); + + SizeF this_size = exp_text_sizes[i]; + + int adjx = (int)Math.Max((_geo_layout_info.cell_size.Width - this_size.Width) / 2, 0); + + int adjy = (int)Math.Max((_geo_layout_info.get_header_size().Height - this_size.Height) / 2, 0); + + w.drawString(_formatted_theos.sorted_formatted_expirations[i], x + adjx, 0 + adjy); + } + stop_ms = _timer.runningMilliseconds(); + _recorder.log("Header draw time", "Header draw time", stop_ms - start_ms); + } + + private void _paint_seperate_areas(IGraphicsWrapper w) { + double start_ms = _timer.runningMilliseconds(); + foreach (NMSheetColumnName col in _visual_layout_info.visible_cols) { + int element_width = (int)_geo_layout_info.get_item_cell_size(col).Width, + element_offset = _geo_layout_info.get_item_x_in_exp(_visual_layout_info, col); + for (int i = 0; i < _formatted_theos.sorted_formatted_expirations.Length; i++) { + w.selectBrush(w.createSolidBrush(_visual_layout_info.get_element_background_color(col, i))); + w.fillRectangle(i * _geo_layout_info.cell_size.Width + element_offset, + 0, + element_width, + _geo_layout_info.cell_size.Height * _formatted_theos.sorted_formatted_strikes.Length); + } + } + double stop_ms = _timer.runningMilliseconds(); + _recorder.log("NMSheetTheosGrid._paint_seperate_areas", "NMSheetTheosGrid._paint_seperate_areas", stop_ms - start_ms); + w.selectPen(w.createPen(Color.Black)); + } + + private double _draw_grid_fast(IGraphicsWrapper gr_wrapper) { + double hit_ratio = Double.NaN; + int skipped_cell_count = 0; + MyCacheInvalidationHelperData new_cache_data = new MyCacheInvalidationHelperData(_formatted_theos, _geo_layout_info, _settings); + bool cache_invalidated = new_cache_data.is_cache_invalidated(_cache_invalidation_data); + try { + // paint alternate colors with expiration1 and expiration2 colors + gr_wrapper.set_text_align(_get_grid_text_alignment_mask(_settings)); + if (cache_invalidated) + _paint_seperate_areas(gr_wrapper); + + int global_cell_index = 0; + if (cache_invalidated) + _cell_paint_cache = new CellInfo[_visual_layout_info.visible_cols.Length * _formatted_theos.sorted_formatted_expirations.Length * _formatted_theos.sorted_formatted_strikes.Length]; + foreach (NMSheetColumnName col in _visual_layout_info.visible_cols) { + MyAlertHelperData alert_helper_data = new MyAlertHelperData(col); + gr_wrapper.selectFont(_visual_layout_info.get_element_font(col)); + SizeF item_cell_size = _geo_layout_info.get_item_cell_size(col); + IList item_text_list = _formatted_theos.col_vs_valuelist_map[col]; + + int item_no = 0; + int item_relative_start_x = _geo_layout_info.get_item_x_in_exp(_visual_layout_info, col); /// ie within exp + Point text_offset_within_cell = _get_text_offset_within_cell(item_cell_size, _settings.setting_grid_internal.horizontal_padding, _settings.setting_grid_internal.vertical_padding, _settings); + for (int exp_no = 0; exp_no < _formatted_theos.sorted_formatted_expirations.Length; exp_no++) { + Color item_exp_font_color = _visual_layout_info.get_element_font_color(col, exp_no); + gr_wrapper.setTextColor(item_exp_font_color); + Color standard_back_color = _visual_layout_info.get_element_background_color(col, exp_no); + int item_start_x = exp_no * _geo_layout_info.cell_size.Width + item_relative_start_x; + int item_text_x = item_start_x + text_offset_within_cell.X; + + for (int strike_no = 0; strike_no < _formatted_theos.sorted_formatted_strikes.Length; strike_no++) { + if (_formatted_theos.contains_contract(exp_no, strike_no)) { + string cell_text = item_text_list[item_no]; + Color overriden_backcolor = Color.White; + bool standard_background = !_get_back_color_override(_settings, alert_helper_data, col, exp_no, strike_no, ref overriden_backcolor); + Color this_cell_backcolor = standard_background ? standard_back_color : overriden_backcolor; + if (cache_invalidated || !_cell_paint_cache[global_cell_index].is_equal(cell_text, this_cell_backcolor)) { + int strike_start_y = strike_no * _geo_layout_info.cell_size.Height; + _paint_rectangle(gr_wrapper, this_cell_backcolor, item_start_x, strike_start_y, (int)item_cell_size.Width, _geo_layout_info.cell_size.Height); + _draw_text(gr_wrapper, item_exp_font_color, cell_text, item_text_x, strike_start_y); + + _cell_paint_cache[global_cell_index].text = cell_text; + _cell_paint_cache[global_cell_index].back_color = this_cell_backcolor; + } else + skipped_cell_count++; + item_no++; + global_cell_index++; + } + } + } + } + _draw_grid_lines(gr_wrapper); + hit_ratio = 100.0 * skipped_cell_count / global_cell_index; + } catch (Exception e) { + bts.Log.Ui.error(e.Message); + bts.Log.Ui.error(e.StackTrace); + } + _cache_invalidation_data = new_cache_data; + _last_back_color = Color.FromKnownColor(KnownColor.Transparent); + _last_text_color = Color.FromKnownColor(KnownColor.Transparent); + return hit_ratio; + } + + private Color _last_text_color = Color.FromKnownColor(KnownColor.Transparent); + private void _draw_text(IGraphicsWrapper gr_wrapper, Color text_color, string cell_text, int item_text_x, int item_text_y) { + if (_last_text_color != text_color) { + _last_text_color = text_color; + gr_wrapper.setTextColor(_last_text_color); + } + gr_wrapper.drawString(cell_text, item_text_x, item_text_y); + } + + + private Color _last_back_color = Color.FromKnownColor(KnownColor.Transparent); + private void _paint_rectangle(IGraphicsWrapper gr_wrapper, Color back_color, int x, int y, int width, int height) { + if (_last_back_color != back_color) { + _last_back_color = back_color; + gr_wrapper.selectBrush(gr_wrapper.createSolidBrush(back_color)); + } + gr_wrapper.fillRectangle(x, y, width, height); + } + + private void _paint_atm_background_directly(Graphics g) { + SolidBrush semi_trans_brush = new SolidBrush(Color.FromArgb(128, _settings.setting_atm.atm_strike_row_row_back_color)); + foreach (KeyValuePair> p in _formatted_theos.get_atm_map()) + foreach (int strike_index in p.Value) { + Rectangle bm_rect = new Rectangle(p.Key * _geo_layout_info.cell_size.Width, strike_index * _geo_layout_info.cell_size.Height, _geo_layout_info.cell_size.Width, _geo_layout_info.cell_size.Height); + Rectangle screen_rect = _convert_to_control_rect(bm_rect); + g.FillRectangle(semi_trans_brush, screen_rect); + } + } + + private void _draw_grid_lines(IGraphicsWrapper w) { + w.selectPen(w.createPen(_settings.setting_grid_internal.row_seperator_line_color)); + // draw horizontal lines + if (_settings.setting_grid_internal.draw_row_separator_line) + for (int n = 0; n < _formatted_theos.sorted_formatted_strikes.Length; n++) + w.drawLine(0, n * _geo_layout_info.cell_size.Height, _geo_layout_info.grid_size.Width, n * _geo_layout_info.cell_size.Height); + + // draw vertical lines + w.selectPen(w.createPen(_settings.setting_grid_internal.expiration_seperator_line_color)); + for (int i = 0; i < _formatted_theos.sorted_formatted_expirations.Length; i++) + w.drawLine(i * _geo_layout_info.cell_size.Width, 0, i * _geo_layout_info.cell_size.Width, _geo_layout_info.cell_size.Height * _formatted_theos.sorted_formatted_strikes.Length); + w.selectPen(w.createPen(_settings.setting_grid_internal.row_seperator_line_color)); /// reverting back + } + + private static NMSheetSettingGridInternal.NMSheetGridHorizontalTextAlignment _get_horizontal_text_alignment_setting(NMSheetSettings settings) { + Nullable a = settings.setting_grid_internal.horizontal_text_alignment; + return (a != null && a.HasValue) ? a.Value : NMSheetSettingGridInternal.NMSheetGridHorizontalTextAlignment.Center; + } + + private static int _get_grid_text_alignment_mask(NMSheetSettings settings) { + NMSheetSettingGridInternal.NMSheetGridHorizontalTextAlignment h_a = settings.setting_grid_internal.horizontal_text_alignment.Value; + return _convert_horizontal_alignment_setting_to_mask(h_a); + /// vertical alignment is top, which is 0 + } + + private static int _convert_horizontal_alignment_setting_to_mask(NMSheetSettingGridInternal.NMSheetGridHorizontalTextAlignment h_a) { + if (h_a == NMSheetSettingGridInternal.NMSheetGridHorizontalTextAlignment.Center) + return 6; + else if (h_a == NMSheetSettingGridInternal.NMSheetGridHorizontalTextAlignment.Left) + return 0; + else + return 2; + } + + private static Point _get_text_offset_within_cell(SizeF cell_size, int horizonatal_padding, int vertical_padding, NMSheetSettings setting) { + NMSheetSettingGridInternal.NMSheetGridHorizontalTextAlignment h_a = setting.setting_grid_internal.horizontal_text_alignment.Value; + if (h_a == NMSheetSettingGridInternal.NMSheetGridHorizontalTextAlignment.Left) + return new Point(0, 0); + else if (h_a == NMSheetSettingGridInternal.NMSheetGridHorizontalTextAlignment.Right) + return new Point((int)(cell_size.Width), 0); + else + return new Point((int)(cell_size.Width / 2.0), 0); + } + } +} \ No newline at end of file diff --git a/src/client/spark/NMSheets/UIComponents/MainSheet/NMSheetTheoGridCurrentCell.cs b/src/client/spark/NMSheets/UIComponents/MainSheet/NMSheetTheoGridCurrentCell.cs new file mode 100644 index 000000000..39d1fc212 --- /dev/null +++ b/src/client/spark/NMSheets/UIComponents/MainSheet/NMSheetTheoGridCurrentCell.cs @@ -0,0 +1,105 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.ComponentModel; +using System.Drawing; +using bts.api; +using System.Data; +using System.Windows.Forms; +using System.Drawing.Imaging; +using System.Drawing.Drawing2D; + +using BCG.Utilities; +using BCG.Utilities.General; + +namespace BCG { + partial class NMSheetTheoGrid { + // class used to mark the currently selected contract(s) + // i.e. the contract(s) that will be highlighted when paiting + // and sent as an argument to onContractSelected + // when a double click is detected. + public class GridCell { + public readonly NMSheetExpiration expiration; + public readonly double strike; + public readonly NMSheetColumnName col; + public readonly bool call_selected; + public readonly bool put_selected; + public static GridCell empty = new GridCell(new NMSheetExpiration(Venue.Sim, String.Empty, DateTime.MinValue), Double.NaN, NMSheetColumnName.strike); + public GridCell(NMSheetExpiration the_expiration, double the_strike, NMSheetColumnName the_col) { + expiration = the_expiration; + strike = the_strike; + col = the_col; + bool temp; + NMSheetSettingColumnOrganization.parse_column(col, out call_selected, out put_selected, out temp, out temp); + } + public override string ToString() { return expiration.ToString() + " , " + strike.ToString() + " , " + (call_selected ? "call" : "put"); } + } + + private GridCell _selected_cell = null; + /// Called from the click (and gesture) + private void _set_cell_selection(Point control_coords) { + Point bitmap_coords = _convert_to_bitmap_coords(control_coords); + _selected_cell = _get_gridcell_from_bitmap_coords(bitmap_coords); + } + + #region Coord transformation helpers + private GridCell _get_gridcell_from_bitmap_coords(Point bitmap_coords) { + if (_formatted_theos != null && _geo_layout_info != null && _visual_layout_info != null) { + int exp_index = bitmap_coords.X / _geo_layout_info.cell_size.Width; + int strike_index = bitmap_coords.Y / _geo_layout_info.cell_size.Height; + if (exp_index >= 0 && exp_index < _formatted_theos.sorted_expirations.Length && strike_index >= 0 && strike_index < _formatted_theos.sorted_strikes.Length) { + NMSheetColumnName col_name = NMSheetColumnName.standard_strike; + if (_geo_layout_info.get_column(bitmap_coords.X, _visual_layout_info.visible_cols, ref col_name)) + return new GridCell(_formatted_theos.sorted_expirations[exp_index], _formatted_theos.sorted_strikes[strike_index], col_name); + } + } + return null; + } + + private GridCell _get_gridcell_from_control_coords(Point control_coords) { + Point bitmap_coords = _convert_to_bitmap_coords(control_coords); + return _get_gridcell_from_bitmap_coords(bitmap_coords); + } + + private Rectangle _convert_to_control_rect(Rectangle bm_rect) { + int exp_header_height = _geo_layout_info.get_header_size().Height; + Rectangle control_rect = new Rectangle(_convert_to_control_coords(new Point(bm_rect.Left, bm_rect.Top)), bm_rect.Size); + /// the following restricts the bm_rect to the control + control_rect = Rectangle.Intersect(control_rect, new Rectangle(0, exp_header_height, Width, Height - exp_header_height)); + return control_rect; + } + + private Point _convert_to_control_coords(Point bitmap_coords) { + /// note this coord might be outside the control + if (_geo_layout_info != null /*&& _visible_rect_topleft != null*/) + return new Point(bitmap_coords.X - _visible_rect_topleft.X, bitmap_coords.Y - _visible_rect_topleft.Y + _geo_layout_info.get_header_size().Height); + else + return new Point(0, 0); + } + + /// Converts control coords to data bitmap coords + /// (The control includes the grid and the exp header, + /// the data bitmap is the bitmap fopr the grid part only) + private Point _convert_to_bitmap_coords(Point control_coords) { + if (/*control_coords != null && _visible_rect_topleft != null &&*/ _geo_layout_info != null) + return new Point(control_coords.X + _visible_rect_topleft.X, _visible_rect_topleft.Y + control_coords.Y - _geo_layout_info.get_header_size().Height); + return + new Point(0, 0); + } + + /// This returns the rectangle on the bitmap + /// that is copied to the screen + private Rectangle _get_visible_grid_rect() { + /// The height and size are lowerbounded because the control + /// can be made to extend beyond the bitmap (ex scroll all the + /// way and then extend the resize the control - though there + /// is a growth cushion) + int control_grid_h = Height - _geo_layout_info.get_header_size().Height; + return new Rectangle(_visible_rect_topleft.X, _visible_rect_topleft.Y, + Math.Min(_grid_bitmap_size.Width - _visible_rect_topleft.X, Width), + Math.Min(_grid_bitmap_size.Height - _visible_rect_topleft.Y, control_grid_h)); + } + + #endregion + } +} diff --git a/src/client/spark/NMSheets/UIComponents/MainSheet/NMSheetTheoGridMouseHandling.cs b/src/client/spark/NMSheets/UIComponents/MainSheet/NMSheetTheoGridMouseHandling.cs new file mode 100644 index 000000000..2dfd197fd --- /dev/null +++ b/src/client/spark/NMSheets/UIComponents/MainSheet/NMSheetTheoGridMouseHandling.cs @@ -0,0 +1,183 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.ComponentModel; +using System.Drawing; +using System.Data; +using System.Windows.Forms; +using System.Drawing.Imaging; +using System.Drawing.Drawing2D; + +using BCG.Utilities; +using BCG.Utilities.General; +namespace BCG { + partial class NMSheetTheoGrid { + // the last point where the mouse was pressed down, + // used to diferentiate a click from a drag. + // this is set in the mouse down event only. + // this is in control coordinates (ie not in + // bitmap coordinats) + private Point _last_mousedown_control_coords = new Point(Int32.MaxValue, Int32.MaxValue); + + private void _on_doubleclick(object sender, EventArgs e) { + if (has_layout() && onDoubleClick != null && _selected_cell != null) + onDoubleClick(new Pair((e as MouseEventArgs).Button, _selected_cell)); + } + + private void _on_mousedown(object sender, MouseEventArgs e) { + if (has_layout()) + _last_mousedown_control_coords = new Point(e.X, e.Y); + } + + private void _on_mouseup(object sender, MouseEventArgs e) { + if (has_layout()) { + int dx = Math.Abs(e.X - _last_mousedown_control_coords.X); + int dy = Math.Abs(e.Y - _last_mousedown_control_coords.Y); + int d = (int)Math.Sqrt(Math.Pow(dx, 2) + Math.Pow(dy, 2)); + if (d < 5) /// d less than 5 distinguishes a scroll from a click + _handle_click(e); + else { + if (e.Button == System.Windows.Forms.MouseButtons.Right && onGesture != null) + _handle_gesture(sender, e, d, dx, dy); + } + } + } + + private void _handle_click(MouseEventArgs e) { + _set_cell_selection(e.Location); + if (_selected_cell == null) { + /// _selected_cell would be null if the click happens outside + /// bitmap. This always clears the selection + _selected_items_map = NMSheetTheoGridSelectionMap.get_empty_map(); + Invalidate(); + onMouseUpOutsideBitmap(e.Button); + } else { + /// If selection is enabled then the + /// left and right click behaviour are independent + /// of the scrolling and selection mouse settings. + /// Right click : If the click is inside the selected region, the selection + /// is not changed. If it is outside, it makes the current cell the + /// selection (Outside used to be a No-op as well, but with better + /// context menu re-org we are making this change as of Indepedence + /// Day 2016) + /// Left Click : Always makes the current cell the selection + if (_settings.setting_mouse.enable_selection) { + if (e.Button == System.Windows.Forms.MouseButtons.Right) { + if (!_selected_items_map.contains(_selected_cell.expiration, _selected_cell.strike, _selected_cell.col)) { + _selected_items_map = new NMSheetTheoGridSelectionMap(_selected_cell.expiration, _selected_cell.strike, _selected_cell.col); + Invalidate(); + } + } else if (e.Button == System.Windows.Forms.MouseButtons.Left) { + _selected_items_map = new NMSheetTheoGridSelectionMap(_selected_cell.expiration, _selected_cell.strike, _selected_cell.col); + Invalidate(); + } + } + if (_selected_cell != null && onMouseUp != null) + onMouseUp(new Pair(e.Button, _selected_cell)); + } + } + + private void _on_mouse_move(object sender, MouseEventArgs e) { + if (onMouseMove != null) { + GridCell grid_cell = _get_gridcell_from_control_coords(e.Location); + if (grid_cell != null) + onMouseMove(grid_cell); + } + } + + private void _on_mousewheel(object sender, MouseEventArgs e) { + if (System.Windows.Forms.Control.ModifierKeys == Keys.Shift) + jump_to_point(new Point(_visible_rect_topleft.X + _geo_layout_info.cell_size.Width * -Math.Sign(e.Delta), _visible_rect_topleft.Y)); + else + for (int i = 0; i < 5; i++) + _slide_scroll(new Point(), new Point(0, (_settings.setting_grid_internal.distance_for_page - 1) * -Math.Sign(e.Delta))); + } + + #region Gestures + private void _on_gesture(Tuple args) { + if (_geo_layout_info == null) + return; + + Gesture this_gest = args.Item1; + int distance = args.Item2; + if (this_gest == NMSheetTheoGrid.Gesture.Left || this_gest == NMSheetTheoGrid.Gesture.Right) { + int jump = this_gest == NMSheetTheoGrid.Gesture.Left ? 1 : -1; + if (distance > _geo_layout_info.cell_size.Width) + jump *= (this.Width / _geo_layout_info.cell_size.Width); + jump_by_contract(jump, 0); + } else { + int jump = this_gest == NMSheetTheoGrid.Gesture.Down ? -1 : 1; + if (distance < (5 * _geo_layout_info.cell_size.Height)) + jump *= 5; + else + jump *= ((this.Height - _geo_layout_info.get_header_size().Height) / _geo_layout_info.cell_size.Height); + jump_by_contract(0, jump); + } + } + + private void _handle_gesture(object sender, System.Windows.Forms.MouseEventArgs e, int d, int dx, int dy) { + Point p0 = _last_mousedown_control_coords; + _set_cell_selection(p0); + if (_selected_cell != null) { + // Gestures. We try do discern one of 4 possible gestures: + // Up, Down, Left or Right. To do this we are going to draw two imaginary + // lines that intersect the gesture start point (p0). One of the lines will have slope + // 1 and the other -1. + + // origin + // + // \ / + // \ U / + // \ / line1: slope = -1 + // \ / + // L (p0x,p0y) R + // /\ + // / \ + // / D \ + // / \ line 2: slope = 1 + + // so for line 1 we have, y=mx+b, where y= p0y, x= p0x and m=-1, or + // line1: y = -x + (p0y+p0x) + // and simmetrically for line2: + // line2: y = x + (p0y-p0x) + + // Now we just have to figure out in which of the 4 quadrants (U, D, L, R) the + // gesture final point (p1) lies. + // let line1_y = -p1.x+(p0y+p0x) + // line2_y = p1.x+(p0y-p0x) + // then: + // U: p1.y < line1_y and p1.y < line2_y + // D: p1.y > line1_y and p1.y > line2_y + // L: p1.y < line1_y and p1.y > line2_y + // R: p1.y > line1_y and p1.y < line2_y + int b1 = p0.Y + p0.X; + int b2 = p0.Y - p0.X; + + Point p1 = new Point(e.X, e.Y); + int line1_y = -p1.X + b1; + int line2_y = p1.X + b2; + // To disambiguate between quadrants when p1 lies on either line1 or line2 + // we use <= and >= rathern than < and > and just pick the first quadrant + // that matches + if (p1.Y <= line1_y && p1.Y <= line2_y) + onGesture(new Tuple(NMSheetTheoGrid.Gesture.Up, dy, e.Button, _selected_cell)); + else if (p1.Y >= line1_y && p1.Y >= line2_y) + onGesture(new Tuple(NMSheetTheoGrid.Gesture.Down, dy, e.Button, _selected_cell)); + else if (p1.Y <= line1_y && p1.Y >= line2_y) + onGesture(new Tuple(NMSheetTheoGrid.Gesture.Left, dx, e.Button, _selected_cell)); + else + onGesture(new Tuple(NMSheetTheoGrid.Gesture.Right, dx, e.Button, _selected_cell)); + } + } + #endregion + + #region Keyboard + private void _on_keydown(object sender, KeyEventArgs e) { + if (e.KeyCode == Keys.Escape) { + _selected_items_map = NMSheetTheoGridSelectionMap.get_empty_map(); + Invalidate(); + } + } + #endregion + } +} \ No newline at end of file diff --git a/src/client/spark/NMSheets/UIComponents/MainSheet/NMSheetTheoGridScrolling.cs b/src/client/spark/NMSheets/UIComponents/MainSheet/NMSheetTheoGridScrolling.cs new file mode 100644 index 000000000..3913c5a22 --- /dev/null +++ b/src/client/spark/NMSheets/UIComponents/MainSheet/NMSheetTheoGridScrolling.cs @@ -0,0 +1,135 @@ +using System; +using System.ComponentModel; +using System.Drawing; +using System.Windows.Forms; + +namespace BCG +{ + partial class NMSheetTheoGrid + { + /// Helps NMSheetTheoGrid's scrolling by hooking to mouse down + /// and monitoring the mouse motion + public class MyMouseDragger + { + private readonly UserControl _parent_control; + public delegate void DragStart(Point start, MouseButtons mouse_button); + public event DragStart on_drag_start; + /// The start point is wrt to the screen coordinates + /// (which means that in the grid they have to be + /// adjusted for where the bitmap currently is) + public delegate void DragContinue(Point start, Size dp); + public event DragContinue on_drag_continue; + + private int _speed_threshhold = 100, _scrolls_per_second = 8; + private DateTime _last_scroll_time = DateTime.Now; + private Point _scroll_start_point = new Point(0, 0); + + public MyMouseDragger(UserControl f) + { + _parent_control = f; + SheetsScrollMode scroll_mode = TC2Settings.instance.get_scroll_mode(); + if (scroll_mode == SheetsScrollMode.Mixed || scroll_mode == SheetsScrollMode.Classic) + _parent_control.MouseDown += _on_mousedown; + } + + + public void reset_settings(NMSheetSettings settings) + { + _scrolls_per_second = settings.setting_grid_internal.scroll_per_second; + _speed_threshhold = settings.setting_grid_internal.speed_threshhold; + } + + private void _on_mousedown(object sender, MouseEventArgs e) + { + _last_scroll_time = DateTime.Now; + _scroll_start_point = new Point(e.X, e.Y); + on_drag_start(_scroll_start_point, e.Button); + _parent_control.MouseUp += _on_mouseup; + _parent_control.MouseMove += _on_mousemove; + } + + private void _on_mouseup(object sender, MouseEventArgs e) + { + _parent_control.MouseMove -= _on_mousemove; + _parent_control.MouseUp -= _on_mouseup; + } + + private void _on_mousemove(object sender, MouseEventArgs e) + { + if (DateTime.Now - _last_scroll_time >= new TimeSpan(TimeSpan.TicksPerSecond / _scrolls_per_second)) + { + _last_scroll_time = DateTime.Now; + if (on_drag_continue != null) + on_drag_continue(_scroll_start_point, new Size(e.X - _scroll_start_point.X, e.Y - _scroll_start_point.Y)); + } + } + } + + private MyMouseDragger _scroller; + + private readonly Size _selection_drag_move_threshold = new Size(5, 5); + /// the values are below are set at scroll start and + /// then used as the mouse is dragged + private bool _is_selection_mode = false; + private Point _drag_start_visible_topleft = Point.Empty, /// this is the _visible_rect_top_left at the time scrolling starts (its used to figure how much to jump while scrolling) + _drag_start_topleft = Point.Empty; /// this is the point the user grabs to scroll + private GridCell _data_at_drag_start = null; + private Size _move_since_dragging_start = Size.Empty; + + private void _on_drag_start(Point start, MouseButtons buttons) + { + _is_selection_mode = buttons == _settings.setting_mouse.selection_mouse_button; + _drag_start_visible_topleft = _visible_rect_topleft; + _drag_start_topleft = _convert_to_bitmap_coords(start); + _data_at_drag_start = _get_gridcell_from_bitmap_coords(_drag_start_topleft); + _move_since_dragging_start = Size.Empty; + } + + private void _on_drag_continue(Point start, Size dp) + { + if (_is_selection_mode) + { + if (_settings.setting_mouse.enable_selection) + { + if (Math.Abs(dp.Width - _move_since_dragging_start.Width) >= _selection_drag_move_threshold.Width || Math.Abs(dp.Height - _move_since_dragging_start.Height) >= _selection_drag_move_threshold.Height) + { + _move_since_dragging_start = dp; + _timer.start(); + Rectangle selected_rectangle = _get_selected_rectangle(dp); + _selected_items_map = new NMSheetTheoGridSelectionMap(_formatted_theos, _visual_layout_info, _geo_layout_info, _settings, selected_rectangle, _data_at_drag_start); + Invalidate(); + _timer.stop(); + System.Diagnostics.Trace.WriteLine(String.Format("{0}:{1}:{2}:{3} , Time {4} msecs , Rect {5} dp {6}", DateTime.Now.Hour, DateTime.Now.Minute, DateTime.Now.Second, + DateTime.Now.Millisecond, _timer.lastIntervalTime, selected_rectangle, dp)); + } + } + } + else + { + /// this is where the scrolling really happens + scroll_to_point(new Point(_drag_start_visible_topleft.X - dp.Width, _drag_start_visible_topleft.Y - dp.Height)); + } + } + + private Rectangle _get_selected_rectangle(Size dp) + { + Rectangle visible_rect = _get_visible_grid_rect(); + Point bm_start_pos = _drag_start_topleft; + int bm_rect_left = bm_start_pos.X, bm_rect_width = dp.Width; + if (dp.Width < 0) + { + bm_rect_left = Math.Max(0, bm_start_pos.X + dp.Width); + bm_rect_width = bm_start_pos.X - bm_rect_left; + } + int bm_rect_top = bm_start_pos.Y, bm_rect_height = dp.Height; + if (dp.Height < 0) + { + bm_rect_top = Math.Max(0, bm_start_pos.Y + dp.Height); + bm_rect_height = bm_start_pos.Y - bm_rect_top; + } + Rectangle bm_rect = new Rectangle(new Point(bm_rect_left, bm_rect_top), new Size(bm_rect_width, bm_rect_height)); + bm_rect = Rectangle.Intersect(bm_rect, visible_rect); + return bm_rect; + } + } +} \ No newline at end of file diff --git a/src/client/spark/NMSheets/UIComponents/MainSheet/NMSheetTheoGridSelectionMap.cs b/src/client/spark/NMSheets/UIComponents/MainSheet/NMSheetTheoGridSelectionMap.cs new file mode 100644 index 000000000..6975fefe4 --- /dev/null +++ b/src/client/spark/NMSheets/UIComponents/MainSheet/NMSheetTheoGridSelectionMap.cs @@ -0,0 +1,155 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Drawing; +using bts.api; +using mbts.engine; + +namespace BCG { + internal class NMSheetTheoGridSelectionMap { + private readonly Dictionary>> _selection_map = new Dictionary>>(); + private readonly HashSet _selected_cols = new HashSet(); + + public static NMSheetTheoGridSelectionMap get_empty_map() { return new NMSheetTheoGridSelectionMap(); } + + private NMSheetTheoGridSelectionMap() { } + + public NMSheetTheoGridSelectionMap(NMSheetExpiration expiration, double strike, NMSheetColumnName col_name) { + _selection_map.Add(expiration, new Dictionary>()); + _selection_map[expiration].Add(col_name, new HashSet(new double[] { strike })); + _selected_cols.Add(col_name); + } + + public NMSheetTheoGridSelectionMap(NMSheetFormattedTheos theo_data, NMSheetVisualLayout vis_layout, NMSheetGeometricLayout geo_layout, + NMSheetSettings settings, Rectangle sel_rect, NMSheetTheoGrid.GridCell drag_start_cell) { + drag_start_cell = drag_start_cell ?? new NMSheetTheoGrid.GridCell(new NMSheetExpiration(Venue.Sim, String.Empty, DateTime.MinValue), Double.NaN, NMSheetColumnName.standard_strike); + /// adjusts it for the header (header is part of the bitmap) + /// sel_rect = new Rectangle(sel_rect.X, Math.Max(0, sel_rect.Y - geo_layout.get_header_size().Height), sel_rect.Width, sel_rect.Height); + /// the min here is because the bitmap > grid so the + /// rectangle can be off the grid + HashSet strike_sel_map = new HashSet(); + int top_strike_no = Math.Max(0, sel_rect.Y / geo_layout.cell_size.Height), + bottom_strike_no = Math.Min(theo_data.sorted_strikes.Length - 1, sel_rect.Bottom / geo_layout.cell_size.Height); + for (int strike_index = top_strike_no; strike_index <= bottom_strike_no; strike_index++) + strike_sel_map.Add(theo_data.sorted_strikes[strike_index]); + + int left_exp_no = Math.Max(sel_rect.Left / geo_layout.cell_size.Width, 0), + right_exp_no = Math.Min(theo_data.sorted_expirations.Length - 1, sel_rect.Right / geo_layout.cell_size.Width); + + for (int exp_no = left_exp_no; exp_no <= right_exp_no; exp_no++) { + NMSheetExpiration exp = theo_data.sorted_expirations[exp_no]; + Dictionary> within_exp_col_map = new Dictionary>(); + _selection_map.Add(exp, within_exp_col_map); + HashSet exp_col_map = new HashSet(); + foreach (NMSheetColumnName col in vis_layout.visible_cols) { + /// if limited to single selection then it has to be the col from which the selection started + if (!settings.setting_mouse.limit_selection_to_single_column || (col == drag_start_cell.col && exp.Equals(drag_start_cell.expiration))) { + Rectangle item_rect = geo_layout.get_item_rectangle_in_grid(vis_layout, exp_no, col); + if (sel_rect.IntersectsWith(item_rect)) { + exp_col_map.Add(col); + within_exp_col_map.Add(col, strike_sel_map); + _selected_cols.Add(col); + } + } + } + } + } + + /// Converts the selected data into grid + /// bitmap rectangles + public IEnumerable get_selected_bitmap_rectangles(NMSheetFormattedTheos theos, NMSheetGeometricLayout geo_layout, NMSheetVisualLayout visual_layout) { + List rv = new List(); + foreach (KeyValuePair>> p in _selection_map) { + int exp_index = theos.get_expiration_index(p.Key); + foreach (KeyValuePair> col_strike_map in p.Value) { + Rectangle col_rect = geo_layout.get_item_rectangle_in_grid(visual_layout, exp_index, col_strike_map.Key); + foreach (double strike in col_strike_map.Value) { + int strike_no = theos.get_strike_index(strike); + Rectangle strike_rect = geo_layout.get_strike_rectangle_in_grid(strike_no); + rv.Add(Rectangle.Intersect(col_rect, strike_rect)); + } + } + } + return rv; + } + + public Dictionary>> get_selection_map(NMSheetFormattedTheos theo_data) { + Dictionary>> rv = new Dictionary>>(); + foreach (KeyValuePair>> within_exp_col_map in _selection_map) { + NMSheetExpiration exp = within_exp_col_map.Key; + rv.Add(exp, new Dictionary>()); + foreach (KeyValuePair> col_strike_map in within_exp_col_map.Value) { + NMSheetColumnName col_name = col_strike_map.Key; + HashSet strike_map = col_strike_map.Value, adjusted_strike_map = new HashSet(); + foreach (double k in strike_map) + if (theo_data.contains_contract(exp, k)) + adjusted_strike_map.Add(k); + rv[exp].Add(col_name, adjusted_strike_map); + } + } + return rv; + } + + public bool contains(NMSheetExpiration expiration, double strike, NMSheetColumnName col_name) { + Dictionary> col_sel_map; + if (_selection_map.TryGetValue(expiration, out col_sel_map)) { + HashSet strike_sel_map; + if (col_sel_map.TryGetValue(col_name, out strike_sel_map)) + return strike_sel_map.Contains(strike); + } + return false; + } + + public bool is_selection_limited_to_cols(params NMSheetColumnName[] arg_cols) { + HashSet arg_col_map = new HashSet(arg_cols); + foreach (NMSheetColumnName col in _selected_cols) + if (!arg_col_map.Contains(col)) + return false; + return true; + } + + public IDictionary> get_selection_keys(Func get_key) { + IDictionary> rv = new Dictionary>(); + foreach (KeyValuePair>> exp_kv in _selection_map) { + NMSheetExpiration exp = exp_kv.Key; + foreach (KeyValuePair> col_kv in exp_kv.Value) { + foreach (double strike in col_kv.Value) { + bool is_call, is_put, is_bid, is_ask; + NMSheetSettingColumnOrganization.parse_column(col_kv.Key, out is_call, out is_put, out is_bid, out is_ask); + if (is_call) { + uint call_seckey = get_key(exp, strike, true); + if (!is_bid && !is_ask) + is_bid = is_ask = true; + if (is_bid) rv[new SecuritySideKey(call_seckey, Side.Buy)] = Tuple.Create(exp, strike, PutOrCall.Call, Side.Buy); + if (is_ask) rv[new SecuritySideKey(call_seckey, Side.Sell)] = Tuple.Create(exp, strike, PutOrCall.Call, Side.Sell); + } + if (is_put) { + uint put_seckey = get_key(exp, strike, false); + if (!is_bid && !is_ask) + is_bid = is_ask = true; + if (is_bid) rv[new SecuritySideKey(put_seckey, Side.Buy)] = Tuple.Create(exp, strike, PutOrCall.Put, Side.Buy); + if (is_ask) rv[new SecuritySideKey(put_seckey, Side.Sell)] = Tuple.Create(exp, strike, PutOrCall.Put, Side.Sell); + } + } + } + } + return rv; + } + + public bool get_single_exp_single_col_sel(out NMSheetExpiration exp, out NMSheetColumnName col, out IEnumerable strikes) { + exp = null; col = NMSheetColumnName.strike; strikes = null; + if (_selection_map.Count == 1 && _selected_cols.Count == 1) { + exp = _selection_map.ElementAt(0).Key; + col = _selected_cols.ElementAt(0); + strikes = _selection_map[exp][col]; + return true; + } else + return false; + } + + public bool is_active() { return _selection_map.Count > 0; } + + } +} diff --git a/src/client/spark/NMSheets/UIComponents/MainSheet/NMSheetTheoGridWithScrollbars.Designer.cs b/src/client/spark/NMSheets/UIComponents/MainSheet/NMSheetTheoGridWithScrollbars.Designer.cs new file mode 100644 index 000000000..e18725d06 --- /dev/null +++ b/src/client/spark/NMSheets/UIComponents/MainSheet/NMSheetTheoGridWithScrollbars.Designer.cs @@ -0,0 +1,45 @@ +namespace BCG +{ + partial class NMSheetTheoGridWithScrollbars + { + /// + /// 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(); + // + // TheoGridWithScrollbars + // + this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.Name = "TheoGridWithScrollbars"; + this.Size = new System.Drawing.Size(238, 171); + this.ResumeLayout(false); + + } + + #endregion + } +} diff --git a/src/client/spark/NMSheets/UIComponents/MainSheet/NMSheetTheoGridWithScrollbars.cs b/src/client/spark/NMSheets/UIComponents/MainSheet/NMSheetTheoGridWithScrollbars.cs new file mode 100644 index 000000000..97b8fc6d6 --- /dev/null +++ b/src/client/spark/NMSheets/UIComponents/MainSheet/NMSheetTheoGridWithScrollbars.cs @@ -0,0 +1,165 @@ +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; + +namespace BCG { + public enum SheetsScrollMode { + Classic = 0, + Mixed, + SideScroll, + Gesture + } + + public partial class NMSheetTheoGridWithScrollbars : UserControl { + private NMSheetControl _owner; + private System.Windows.Forms.VScrollBar _v_scroll_bar; + private System.Windows.Forms.HScrollBar _h_scroll_bar; + private NMSheetTheoGrid _main_grid; + private double[] _grid_position_details = new double[8]; + private readonly int _scroll_bar_thickness = 17; + private bool _scroll_mode_set; + private const int _hor_scroll_max = 100; + private const int _vert_scroll_max = 100; + + public NMSheetTheoGridWithScrollbars(NMSheetControl owner) { + _owner = owner; + InitializeComponent(); + _init_controls(); + } + + private void _init_controls() { + SheetsScrollMode scroll_mode = TC2Settings.instance.get_scroll_mode(); + _scroll_mode_set = (scroll_mode == SheetsScrollMode.Mixed || scroll_mode == SheetsScrollMode.SideScroll || scroll_mode == SheetsScrollMode.Gesture); + /// grid + _main_grid = new NMSheetTheoGrid(); + _main_grid.Location = new Point(0, 0); + if (_scroll_mode_set) { + /// grid + _main_grid.Size = new Size(Width - _scroll_bar_thickness, Height - _scroll_bar_thickness); + _main_grid.Anchor = AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Top | AnchorStyles.Bottom; + Controls.Add(_main_grid); + /// vertical scroll + _v_scroll_bar = new VScrollBar(); + _v_scroll_bar.Size = new System.Drawing.Size(_scroll_bar_thickness, Height - _scroll_bar_thickness); + _v_scroll_bar.Location = new Point(Width - _scroll_bar_thickness, 0); + _v_scroll_bar.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Right; + Controls.Add(_v_scroll_bar); + /// horizontal scroll + _h_scroll_bar = new HScrollBar(); + _h_scroll_bar.Size = new System.Drawing.Size(Width - _scroll_bar_thickness, _scroll_bar_thickness); + _h_scroll_bar.Location = new Point(0, Height - _scroll_bar_thickness); + _h_scroll_bar.Anchor = AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Bottom; + Controls.Add(_h_scroll_bar); + + _assign_events(); + } else { + /// This control essentially becomes a wrapper + /// around TheoGrid, offering no functionality + _main_grid.Dock = DockStyle.Fill; + Controls.Add(_main_grid); + _main_grid.onDisplayChange += new NMSheetTheoGrid.TheoGridDelegate((o, oo) => { _owner.update_visible_strike_range(); }); + } + } + + private void _assign_events() { + bts.Log.assert(_scroll_mode_set, "_assign_events can only be called when side scrolling is active"); + _v_scroll_bar.Scroll += new ScrollEventHandler(_on_v_scroll); + _h_scroll_bar.Scroll += new ScrollEventHandler(_on_h_scroll); + _main_grid.onDisplayChange += _main_grid_on_display_change; + } + + private void _on_h_scroll(object sender, ScrollEventArgs e) { + if (_main_grid.has_layout()) { + bts.Log.assert(_scroll_mode_set, "_on_h_scroll can only be called when side scrolling is active"); + if (e.Type == ScrollEventType.EndScroll) { + double val = _h_scroll_bar.Value; + double ratio = val / _h_scroll_bar.Maximum; + double[] grid_position_details = _main_grid.get_position_details(); + double new_x = ratio * grid_position_details[6], + new_y = grid_position_details[1]; + + _main_grid.onDisplayChange -= _main_grid_on_display_change; + _main_grid.jump_to_point(new Point(Convert.ToInt32(new_x), Convert.ToInt32(new_y))); + _main_grid.onDisplayChange += _main_grid_on_display_change; + _owner.update_strike_navigator_after_scroll(theo_grid.get_exp_index()); + } + } + } + + private void _on_v_scroll(object sender, ScrollEventArgs e) { + if (_main_grid.has_layout()) { + bts.Log.assert(_scroll_mode_set, "_on_v_scroll can only be called when side scrolling is active"); + if (e.Type == ScrollEventType.EndScroll) { + double val = _v_scroll_bar.Value; + double ratio = val / _v_scroll_bar.Maximum; + double[] grid_position_details = _main_grid.get_position_details(); + double new_x = grid_position_details[0], + new_y = ratio * grid_position_details[7]; + /// since the scroll_to guards against coordinates moving + /// out of range, hence we dont have to guard against that + _main_grid.onDisplayChange -= _main_grid_on_display_change; + _main_grid.scroll_to_point(new Point(Convert.ToInt32(new_x), Convert.ToInt32(new_y))); + _main_grid.onDisplayChange += _main_grid_on_display_change; + _owner.update_visible_strike_range(); + } + } + } + + private void _main_grid_on_display_change(object sender, object[] args) { + bts.Log.assert(_scroll_mode_set, "_main_grid_on_display_change can only be called when side scrolling is active"); + _adjust_scrolls_from_grid(); + } + + private void _adjust_scrolls_from_grid() { + bts.Log.assert(_scroll_mode_set, "_adjust_scrolls_from_grid can only be called when side scrolling is active"); + double[] new_grid_position_details = _main_grid.get_position_details(); + if (!Enumerable.SequenceEqual(new_grid_position_details, _grid_position_details)) { + if (_size_ratios_changed(new_grid_position_details)) { + /// LargeChange/Maximum should be one page / total + _v_scroll_bar.Maximum = _vert_scroll_max; + _v_scroll_bar.LargeChange = Convert.ToInt32(_v_scroll_bar.Maximum * (new_grid_position_details[3] / new_grid_position_details[7])); + _h_scroll_bar.Maximum = _hor_scroll_max; + _h_scroll_bar.LargeChange = Convert.ToInt32(_h_scroll_bar.Maximum * (new_grid_position_details[2] / new_grid_position_details[6])); + } + _grid_position_details = new_grid_position_details; + /// adjust scrolls (for the above case, or when + /// the user uses the classic TC2 scrolling + _v_scroll_bar.Value = _curtail_bw_min_and_max(Convert.ToInt32(_v_scroll_bar.Maximum * (new_grid_position_details[1] / new_grid_position_details[7])), 0, _vert_scroll_max); + _h_scroll_bar.Value = _curtail_bw_min_and_max(Convert.ToInt32(_h_scroll_bar.Maximum * (new_grid_position_details[0] / new_grid_position_details[6])), 0, _hor_scroll_max); + } + } + + private static int _curtail_bw_min_and_max(int value, int min, int max) { + return value < min ? min : (value > max ? max : value); + } + + /// detects if the view area's length ratios changes wrt the total area + private bool _size_ratios_changed(double[] new_grid_position_details) { + return _grid_position_details[2] != new_grid_position_details[2] || _grid_position_details[3] != new_grid_position_details[3] || + _grid_position_details[6] != new_grid_position_details[6] || _grid_position_details[7] != new_grid_position_details[7]; + } + + public NMSheetTheoGrid theo_grid { get { return _main_grid; } } + + public void post_construct_init(Blackboard bb, string option_symbol) { + if (_scroll_mode_set) { + GridConfig grid_config = (GridConfig)bb.read(new TheoGridConfigTag(option_symbol)); + if (grid_config != null) { + /// to reduce bw for scrolling the scroll step is set + /// really large + grid_config.HorizontalScrollStep = grid_config.VerticalScrollStep = Int32.MaxValue; + bb.write(new TheoGridConfigTag(option_symbol), grid_config); + } + } + } + + public void update_strike_navigator_after_scroll(int exp_index) { _owner.update_strike_navigator_after_scroll(exp_index); } + + public void get_lowest_and_highest_visible_strikes(out double lowest, out double highest) { theo_grid.get_lowest_and_highest_visible_strikes(out lowest, out highest); } + } +} diff --git a/src/client/spark/NMSheets/UIComponents/MainSheet/NMSheetTheoGridWithScrollbars.resx b/src/client/spark/NMSheets/UIComponents/MainSheet/NMSheetTheoGridWithScrollbars.resx new file mode 100644 index 000000000..1af7de150 --- /dev/null +++ b/src/client/spark/NMSheets/UIComponents/MainSheet/NMSheetTheoGridWithScrollbars.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/NMSheets/UIComponents/MainSheet/NMSheetVisualLayout.cs b/src/client/spark/NMSheets/UIComponents/MainSheet/NMSheetVisualLayout.cs new file mode 100644 index 000000000..180d9490b --- /dev/null +++ b/src/client/spark/NMSheets/UIComponents/MainSheet/NMSheetVisualLayout.cs @@ -0,0 +1,46 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Drawing; +using System.Collections; + +namespace BCG { + /// Mantains information about which columns to display, + /// what fonts to use, what font colors to use (all + /// based on GridConfig settings) (NO geomtery is done here) + internal class NMSheetVisualLayout { + public readonly NMSheetColumnName[] visible_cols; + private readonly Dictionary _hashed_cell_elements = new Dictionary(); + private readonly NMSheetColumnConfiguration _default_col_config = new NMSheetColumnConfiguration(); + + public NMSheetVisualLayout(NMSheetSettings grid_settings) { + List col_list = new List(); + foreach (NMSheetColumnConfiguration col in grid_settings.get_visible_columns()) { + _hashed_cell_elements[col.column_name] = col; + col_list.Add(col.column_name); + } + visible_cols = col_list.ToArray(); + _log_msg(); + } + + private void _log_msg() { + string log_msg = String.Empty; + foreach (NMSheetColumnName c in visible_cols) + log_msg += (String.IsNullOrEmpty(log_msg) ? String.Empty : " ") + c; + bts.Log.Ui.diag(String.Format("NMSheetVisualLayout constructed with {0}", log_msg)); + } + + private NMSheetColumnConfiguration _get_col_config(NMSheetColumnName cell_element) { + NMSheetColumnConfiguration col_config = null; + return _hashed_cell_elements.TryGetValue(cell_element, out col_config) ? col_config : _default_col_config; + } + + public Font get_element_font(NMSheetColumnName element) { return _get_col_config(element).font; } + + public Color get_element_font_color(NMSheetColumnName element, int exp_no) { return exp_no % 2 == 0 ? _get_col_config(element).font_color_1 : _get_col_config(element).font_color_2; } + + public Color get_element_background_color(NMSheetColumnName element, int exp_no) { return exp_no % 2 == 0 ? _get_col_config(element).back_color_1 : _get_col_config(element).back_color_2; } + } +} diff --git a/src/client/spark/core/FontsAndColors/BTSColors.cs b/src/client/spark/core/FontsAndColors/BTSColors.cs index a3b3f4a3e..2db2f0dbf 100644 --- a/src/client/spark/core/FontsAndColors/BTSColors.cs +++ b/src/client/spark/core/FontsAndColors/BTSColors.cs @@ -86,7 +86,10 @@ namespace mbts.ui { [DisplayInfo(name = "Market Data")] public static BTSColor default_background { get { return BTSCoreColors.blue_light_lighter; } } public static BTSColor default_text { get { return BTSCoreColors.black; } } - + [DisplayInfo(name = "Ask Text")] + public static BTSColor ask_text { get { return BTSCoreColors.red_dark; } } + [DisplayInfo(name = "Bid Text")] + public static BTSColor bid_text { get { return BTSCoreColors.blue; } } //Another bid color option: 40,70,200 public static BTSColor bid { get; } public static BTSColor bid_alt { get { return BTSCoreColors.blue_light; } }