TC2 is part of Spark now - we will rule the crypto options space
This commit is contained in:
1 parent
a08dd1e22d
commit
3da7741f24
195 files changed
+21509
-2
No files matched your search
@@ -200,7 +200,8 @@ namespace mbts.spark {
|
||||
return null;
|
||||
}
|
||||
|
||||
public IEnumerable<DateTime> get_option_expirations(string option_name) {
|
||||
public IEnumerable<DateTime> 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<double> get_all_option_strikes(string option_name) {
|
||||
HashSet<double> rv = new HashSet<double>();
|
||||
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<DateTime> 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);
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -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<Triplet<NMSheetExpiration, bool, double>> expiration_request_list;
|
||||
public NMSheetDataRequest(IEnumerable<Triplet<NMSheetExpiration, bool, double>> 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<Triplet<NMSheetExpiration, bool, double>> rv = new List<Triplet<NMSheetExpiration, bool, double>>();
|
||||
foreach (Triplet<NMSheetExpiration, bool, double> 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<NMSheetExpiration> exps)
|
||||
{
|
||||
HashSet<NMSheetExpiration> exp_map = new HashSet<NMSheetExpiration>(exps);
|
||||
List<Triplet<NMSheetExpiration, bool, double>> rv = new List<Triplet<NMSheetExpiration, bool, double>>();
|
||||
foreach (Triplet<NMSheetExpiration, bool, double> t in request.expiration_request_list)
|
||||
if (exp_map.Contains(t.first))
|
||||
rv.Add(t);
|
||||
return new NMSheetDataRequest(rv);
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -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<NMSheetSymbol, NMSheetSingleOptionData>
|
||||
/// 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<NMSheetSymbol, NMSheetSingleOptionData> _sym_data_map;
|
||||
private readonly IDictionary<NMSheetSymbol, IDictionary<uint, BBOPacket>> _bbo_map;
|
||||
private readonly IDictionary<uint, NMSheetTickerData> _complete_ticker_data;
|
||||
private readonly TaskingConsolidatedData _task_data;
|
||||
|
||||
private readonly double[] _cached_sorted_strikes;
|
||||
private readonly NMSheetExpiration[] _cached_sorted_expirations;
|
||||
private readonly SortedDictionary<NMSheetExpiration, NMSheetDriverData> _cached_driver_data_map = new SortedDictionary<NMSheetExpiration, NMSheetDriverData>();
|
||||
private readonly SortedDictionary<NMSheetExpiration, ATMData> _cached_atm_data;
|
||||
|
||||
public NMSheetData(IDictionary<NMSheetSymbol, NMSheetSingleOptionData> sym_data_map,
|
||||
IDictionary<NMSheetSymbol, IDictionary<uint, BBOPacket>> bbo_map,
|
||||
IDictionary<uint, NMSheetTickerData> 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<NMSheetSymbol, NMSheetSingleOptionData> p in sym_data_map)
|
||||
{
|
||||
IDictionary<uint, BBOPacket> 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<uint> restricted_seckey_map)
|
||||
{
|
||||
Dictionary<NMSheetSymbol, NMSheetSingleOptionData> main_data_map = new Dictionary<NMSheetSymbol, NMSheetSingleOptionData>();
|
||||
foreach (KeyValuePair<NMSheetSymbol, NMSheetSingleOptionData> 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<uint> 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<uint> all_secs = new HashSet<uint>(Enumerable.Concat(eye_secs, quoter_secs));
|
||||
return filter_data(this, all_secs);
|
||||
}
|
||||
else
|
||||
return this;
|
||||
}
|
||||
|
||||
public NMSheetData filter_for_positive_edge()
|
||||
{
|
||||
List<uint> filtered_key_list = new List<uint>();
|
||||
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<uint>(filtered_key_list));
|
||||
}
|
||||
public IDictionary<NMSheetExpiration, NMSheetDriverData> get_driver_data() { return _cached_driver_data_map; }
|
||||
|
||||
public HashSet<NMSheetExpiration> get_expirations_with_same_driver(NMSheetExpiration nmsheet_expiration)
|
||||
{
|
||||
HashSet<NMSheetExpiration> rv = new HashSet<NMSheetExpiration>();
|
||||
NMSheetDriverData driver_data = null;
|
||||
if (_cached_driver_data_map.TryGetValue (nmsheet_expiration, out driver_data))
|
||||
{
|
||||
foreach (KeyValuePair<NMSheetExpiration, NMSheetDriverData> 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<NMSheetExpiration, ATMData> 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<NMSheetExpiration, ATMData> _assemble_atm_data_from_symbols(IDictionary<NMSheetSymbol, NMSheetSingleOptionData> sym_data_map)
|
||||
{
|
||||
SortedDictionary<NMSheetExpiration, ATMData> rv = new SortedDictionary<NMSheetExpiration, ATMData>();
|
||||
foreach (KeyValuePair<NMSheetSymbol, NMSheetSingleOptionData> symbol_elem in sym_data_map)
|
||||
{
|
||||
Dictionary<DateTime, ATMData> symbol_atm_map = symbol_elem.Value.get_atm_data();
|
||||
foreach (KeyValuePair<DateTime, ATMData> 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<NMSheetSymbol, NMSheetSingleOptionData> sym_data_map)
|
||||
{
|
||||
HashSet<double> all_sym_strikes = new HashSet<double>();
|
||||
foreach (NMSheetSingleOptionData d in sym_data_map.Values)
|
||||
Array.ForEach(d.get_strikes(), (double k) => all_sym_strikes.Add(k));
|
||||
List<double> strike_list = all_sym_strikes.ToList();
|
||||
strike_list.Sort();
|
||||
return strike_list.ToArray();
|
||||
}
|
||||
|
||||
private static SortedDictionary<NMSheetExpiration, NMSheetDriverData> _assemble_driver_data_from_symbols(IDictionary<NMSheetSymbol, NMSheetSingleOptionData> symbol_data_map)
|
||||
{
|
||||
SortedDictionary<NMSheetExpiration, NMSheetDriverData> rv = new SortedDictionary<NMSheetExpiration, NMSheetDriverData>();
|
||||
foreach (KeyValuePair<NMSheetSymbol, NMSheetSingleOptionData> option_data_pair in symbol_data_map)
|
||||
{
|
||||
NMSheetSymbol nmsheet_symbol = option_data_pair.Key;
|
||||
NMSheetSingleOptionData symbol_data = option_data_pair.Value;
|
||||
Dictionary<DateTime, NMSheetDriverData> symbol_driver_data = symbol_data.get_driver_data();
|
||||
foreach (KeyValuePair<DateTime, NMSheetDriverData> p in symbol_driver_data)
|
||||
rv[new NMSheetExpiration(nmsheet_symbol, p.Key)] = p.Value;
|
||||
}
|
||||
return rv;
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,291 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using bts.api;
|
||||
using System.Text;
|
||||
|
||||
using bts.utils;
|
||||
|
||||
namespace BCG {
|
||||
/// <summary>
|
||||
/// 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
|
||||
/// </summary>
|
||||
public partial class NMSheetSingleOptionData {
|
||||
private readonly NMSheetSymbol _nmsheet_option;
|
||||
private readonly NMSheetDataRequest _data_request;
|
||||
private readonly ExpStrikeKeyedData<Triplet<mbts.TheoPoint, uint, uint>> _theo_data_map = new ExpStrikeKeyedData<Triplet<mbts.TheoPoint, uint, uint>>();
|
||||
private readonly Dictionary<DateTime, NMSheetDriverData> _option_exp_driver_data;
|
||||
private readonly OptionContractKeyedData<double> _theo_shift_map;
|
||||
private readonly IDictionary<DateTime, ATMData> _atm_data_map;
|
||||
private readonly OptionContractKeyedData<PNLRollOverDataUnit> _roll_over_data;
|
||||
private readonly ExpStrikeKeyedData<Tuple<double, double>> _position_map;
|
||||
private readonly ExpStrikeKeyedData<mbts.analytics.Theos> _presaved_aw2_theos;
|
||||
private readonly NMSheetSettings _settings;
|
||||
private readonly object /*IDictionary<DateTime, IBlueRow>*/ _option_exp_driver_rows = "TODO";
|
||||
private readonly IDictionary<DateTime, Tuple<double, double>> _option_exp_driver_detailed_price_data = new Dictionary<DateTime, Tuple<double, double>>();
|
||||
private IDictionary<uint, BBOPacket> _bbo_data_map = new Dictionary<uint, BBOPacket>();
|
||||
private IDictionary<uint, NMSheetTickerData> _ticker_data = new Dictionary<uint, NMSheetTickerData>();
|
||||
private TaskingConsolidatedData _tasking_data;
|
||||
private readonly ExchangeSecurityMap _sec_map;
|
||||
|
||||
public NMSheetSingleOptionData(NMSheetSymbol option,
|
||||
NMSheetDataRequest data_request,
|
||||
ExpStrikeKeyedData<Triplet<mbts.TheoPoint, uint, uint>> theo_data_map,
|
||||
Dictionary<DateTime, NMSheetDriverData> option_exp_driver_data,
|
||||
OptionContractKeyedData<double> theo_shift_map,
|
||||
IDictionary<DateTime, ATMData> atm_data,
|
||||
OptionContractKeyedData<PNLRollOverDataUnit> roll_over_data,
|
||||
ExpStrikeKeyedData<Tuple<double, double>> position_map,
|
||||
ExpStrikeKeyedData<mbts.analytics.Theos> 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<DateTime, IBlueRow> kvp in _option_exp_driver_rows)
|
||||
// _option_exp_driver_detailed_price_data[kvp.Key] = Tuple.Create(BlueDataUtility.get_row_value<double>(kvp.Value, "bid_price", Double.NaN),
|
||||
// BlueDataUtility.get_row_value<double>(kvp.Value, "ask_price", Double.NaN));
|
||||
}
|
||||
|
||||
public static NMSheetSingleOptionData filter_data(NMSheetSingleOptionData data, HashSet<uint> seckey_map) {
|
||||
ExpStrikeKeyedData<Triplet<mbts.TheoPoint, uint, uint>> theo_data_map = new ExpStrikeKeyedData<Triplet<mbts.TheoPoint, uint, uint>>();
|
||||
foreach (Triplet<DateTime, double, Triplet<mbts.TheoPoint, uint, uint>> 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<NMSheetExpiration> exp_map = new HashSet<NMSheetExpiration>(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<DateTime, NMSheetDriverData> driver_data = new Dictionary<DateTime, NMSheetDriverData>();
|
||||
foreach (KeyValuePair<DateTime, NMSheetDriverData> 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<uint> get_crossed_keys() {
|
||||
HashSet<uint> filtered_keys = new HashSet<uint>();
|
||||
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<uint, BBOPacket> bbo_data) { _bbo_data_map = bbo_data; }
|
||||
|
||||
public void set_ticker(IDictionary<uint, NMSheetTickerData> 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<DateTime, NMSheetDriverData> get_driver_data() { return _option_exp_driver_data; }
|
||||
|
||||
public Dictionary<DateTime, ATMData> get_atm_data() {
|
||||
Dictionary<DateTime, ATMData> rv = new Dictionary<DateTime, ATMData>(_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<mbts.TheoPoint, uint, uint> 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<mbts.TheoPoint, uint, uint> 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<double, double> 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<NMSheetTaskEyeData> eye_data;
|
||||
_fill_eye_data(tp_with_seckey, driver_bid_ask, call_bbo_packet, put_bbo_packet, ref cp_row, out eye_data);
|
||||
NMSheetCallPutBidAskWrapper<NMSheetTaskQuoterData> 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<NMSheetTheoBBOCross> cross_data;
|
||||
_fill_cross_alert(call_bbo_packet, put_bbo_packet, cp_row, v, out cross_data);
|
||||
aux_data = new NMSheetRowAuxiliaryData(new NMSheetCallPutWrapper<BBOPacket>(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<NMSheetTheoBBOCross> 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<NMSheetTheoBBOCross>(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<double, double> 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<double, double> 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
using System;
|
||||
|
||||
using bts.api;
|
||||
|
||||
namespace BCG {
|
||||
public partial class NMSheetSingleOptionData {
|
||||
private void _fill_eye_data(Triplet<mbts.TheoPoint, uint, uint> tp_with_seckeys, Tuple<double, double> driver_bid_ask, BBOPacket call_bbo, BBOPacket put_bbo,
|
||||
ref double[] cp_row, out NMSheetCallPutBidAskWrapper<NMSheetTaskEyeData> 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<NMSheetTaskEyeData>(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<double, double> 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));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
using System;
|
||||
|
||||
using bts.api;
|
||||
|
||||
namespace BCG {
|
||||
public partial class NMSheetSingleOptionData {
|
||||
private void _fill_quoter_data(Triplet<mbts.TheoPoint, uint, uint> tp_with_seckeys, Tuple<double, double> driver_bid_ask, double[] cp_row, out NMSheetCallPutBidAskWrapper<NMSheetTaskQuoterData> 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<NMSheetTaskQuoterData>(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<double, double> 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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 {
|
||||
/// <summary>
|
||||
/// All these tags are for a single instance of a sheet
|
||||
/// (which has a unique id)
|
||||
/// </summary>
|
||||
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() { }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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 {
|
||||
/// <summary>
|
||||
/// Publishes the list of all expirations that are active
|
||||
/// in the sheets. This is used as a proxy for the active
|
||||
/// list of contracts
|
||||
/// </summary>
|
||||
public class NMSheetActiveExpirationsProvider : IDisposable {
|
||||
private HashSet<NMSheetExpiration> _active_exp_map = new HashSet<NMSheetExpiration>();
|
||||
private readonly ThreadedBlackboard _bb;
|
||||
private IDictionary<NMSheetTags.NMSheetSettingsTag, NMSheetSettings> _setting_map = new Dictionary<NMSheetTags.NMSheetSettingsTag, NMSheetSettings>();
|
||||
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<NMSheetExpiration> new_active_exps = new HashSet<NMSheetExpiration>();
|
||||
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<NMSheetExpiration> _get_single_sheet_exps(mbts.spark.SystemContractData contract_data, NMSheetSettings settings) {
|
||||
HashSet<NMSheetExpiration> rv = new HashSet<NMSheetExpiration>();
|
||||
if (contract_data != null && settings != null) {
|
||||
foreach (NMSheetSymbol symbol in settings.setting_option_list) {
|
||||
IEnumerable<DateTime> exps = contract_data.get_option_expirations(symbol.option_name, false);
|
||||
rv.AddRange(exps.Select(e => new NMSheetExpiration(symbol, e)));
|
||||
}
|
||||
HashSet<NMSheetExpiration> removed_exps = new HashSet<NMSheetExpiration>(settings.setting_unselected_expirations);
|
||||
rv.RemoveWhere(e => removed_exps.Contains(e));
|
||||
}
|
||||
return rv;
|
||||
}
|
||||
|
||||
#region Disposable
|
||||
public void Dispose() {
|
||||
_bb.data_callback -= _handle_data;
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
@@ -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<NMSheetSymbol, OptionContractKeyedData<BBOPacket>>
|
||||
public class NMSheetBBODataSource : IDisposable {
|
||||
private readonly ThreadedBlackboard _threaded_bb;
|
||||
private readonly Dictionary<object, NMSheetSymbol> _tag_to_nmsymbol = new Dictionary<object, NMSheetSymbol>();
|
||||
private Dictionary<NMSheetSymbol, IDictionary<uint, BBOPacket>> _data_map = new Dictionary<NMSheetSymbol, IDictionary<uint, BBOPacket>>();
|
||||
private Action _cb;
|
||||
|
||||
public NMSheetBBODataSource(ThreadedBlackboard threaded_bb, List<NMSheetSymbol> 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<uint, BBOPacket>)value;
|
||||
_cb();
|
||||
}
|
||||
}
|
||||
|
||||
public IDictionary<NMSheetSymbol, IDictionary<uint, BBOPacket>> get_all_data() {
|
||||
return new Dictionary<NMSheetSymbol, IDictionary<uint, BBOPacket>>(_data_map);
|
||||
}
|
||||
|
||||
public void Dispose() { _threaded_bb.data_callback -= _react_to_bb; }
|
||||
}
|
||||
}
|
||||
@@ -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<NMSheetSingleOptionMainDataSource> _data_sources;
|
||||
private Dictionary<NMSheetSymbol, NMSheetSingleOptionData> _option_data = new Dictionary<NMSheetSymbol, NMSheetSingleOptionData>();
|
||||
private Action _cb;
|
||||
|
||||
public NMSheetMainDataSource(ThreadedBlackboard threaded_bb, object req_id, List<NMSheetSymbol> nmsheet_symbol_list, Action cb) {
|
||||
_cb = cb;
|
||||
_data_sources = new List<NMSheetSingleOptionMainDataSource>();
|
||||
foreach (NMSheetSymbol s in nmsheet_symbol_list)
|
||||
_data_sources.Add(new NMSheetSingleOptionMainDataSource(req_id, threaded_bb, s, _on_data));
|
||||
}
|
||||
|
||||
private void _on_data(Pair<NMSheetSymbol, NMSheetSingleOptionData> 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<NMSheetSymbol, NMSheetSingleOptionData> get_data() { return new Dictionary<NMSheetSymbol, NMSheetSingleOptionData>(_option_data); }
|
||||
|
||||
#region IDisposable
|
||||
public void Dispose() {
|
||||
foreach (NMSheetSingleOptionMainDataSource d in _data_sources)
|
||||
d.Dispose();
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
@@ -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<NMSheetSymbol> _symbols;
|
||||
// private readonly object _req_id;
|
||||
// private readonly object _in_usage_tag = new VolSurfaceBlackboardTags.VolSurfaceUsageTag();
|
||||
// private IDictionary<NMSheetSymbol, int> _usage_map = new Dictionary<NMSheetSymbol, int>();
|
||||
|
||||
public NMSheetPresavedTheosProvider(ThreadedBlackboard bb, IEnumerable<NMSheetSymbol> 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<Tuple<bts.o2.msgs.SecurityType, string, int>> usage_list = data as IEnumerable<Tuple<bts.o2.msgs.SecurityType, string, int>>;
|
||||
// if (usage_list != null) {
|
||||
// foreach (NMSheetSymbol s in _symbols) {
|
||||
// Tuple<bts.o2.msgs.SecurityType, string, int> 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<NMSheetSymbol, ExpStrikeKeyedData<mbts.analytics.Theos>> rv = new Dictionary<NMSheetSymbol, ExpStrikeKeyedData<mbts.analytics.Theos>>();
|
||||
// if (_usage_map != null)
|
||||
// foreach (KeyValuePair<NMSheetSymbol, int> 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<mbts.analytics.Theos>();
|
||||
// }
|
||||
// _bb.sec_thread_write(new NMSheetTags.NMSheetPresavedTheosTag(_req_id), rv);
|
||||
}
|
||||
|
||||
#region IDisposable
|
||||
public void Dispose() {
|
||||
// _bb.data_callback -= _on_bb_data;
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
@@ -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<Pair<NMSheetSymbol, NMSheetSingleOptionData>> _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<Pair<NMSheetSymbol, NMSheetSingleOptionData>> 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<Triplet<NMSheetExpiration, bool, double>>());
|
||||
data_request = NMSheetDataRequest.restrict_for_symbol(data_request, _nmsheet_symbol);
|
||||
Dictionary<DateTime, Triplet<string, DateTime, double>> live_driver_map = (Dictionary<DateTime, Triplet<string, DateTime, double>>)_threaded_bb.sec_thread_retrieve_from_cache(_in_bb_live_driver_bbo_tag);
|
||||
IDictionary<NMSheetSymbol, ExpStrikeKeyedData<mbts.analytics.Theos>> sym_presaved_aw2_theos = _threaded_bb.sec_thread_retrieve_from_cache(_in_bb_presaved_aw2_theos_tag) as IDictionary<NMSheetSymbol, ExpStrikeKeyedData<mbts.analytics.Theos>>;
|
||||
ExpStrikeKeyedData<mbts.analytics.Theos> 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<mbts.TheoPoint> shared_live_theo_data_map = (ExpStrikeKeyedData<mbts.TheoPoint>)_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<mbts.TheoPoint> 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<Triplet<mbts.TheoPoint, uint, uint>> output_theo_key_data_map = _attach_sec_keys(output_theo_data_map);
|
||||
Dictionary<DateTime, NMSheetDriverData> 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<double>)_threaded_bb.sec_thread_retrieve_from_cache(_in_bb_symbol_theo_shift_tag) ?? new OptionContractKeyedData<double>(),
|
||||
_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<DateTime, IBlueRow> ?? new Dictionary<DateTime, IBlueRow>()*/,
|
||||
_threaded_bb.sec_thread_retrieve_from_cache(_in_bb_secmap_tag) as ExchangeSecurityMap,
|
||||
sheet_settings);
|
||||
timer.stop();
|
||||
_cb(new Pair<NMSheetSymbol, NMSheetSingleOptionData>(_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<mbts.TheoPoint> _limit_to_requested_securities(ExpStrikeKeyedData<mbts.TheoPoint> theo_data, NMSheetDataRequest data_request, NMSheetSettings sheet_settings) {
|
||||
HashSet<DateTime> selected_exp_map = new HashSet<DateTime>();
|
||||
HashSet<double> selected_strike_map = new HashSet<double>(sheet_settings.setting_unselected_strikes);
|
||||
foreach (Triplet<NMSheetExpiration, bool, double> 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<Triplet<mbts.TheoPoint, uint, uint>> _attach_sec_keys(ExpStrikeKeyedData<mbts.TheoPoint> theo_map) {
|
||||
theo_map = theo_map ?? new ExpStrikeKeyedData<mbts.TheoPoint>();
|
||||
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<Triplet<mbts.TheoPoint, uint, uint>> rv = new ExpStrikeKeyedData<Triplet<mbts.TheoPoint, uint, uint>>();
|
||||
foreach (Triplet<DateTime, double, mbts.TheoPoint> t in theo_map.get_data_linearly())
|
||||
rv.set_data(t.first, t.second, new Triplet<mbts.TheoPoint, uint, uint>(t.third, 0, 0));
|
||||
return rv;
|
||||
}
|
||||
}
|
||||
|
||||
private ExpStrikeKeyedData<mbts.TheoPoint> _adjust_for_freezes(ExpStrikeKeyedData<mbts.TheoPoint> live_theo_map, NMSheetDataRequest data_request) {
|
||||
return live_theo_map;
|
||||
// TODO
|
||||
// ExpStrikeKeyedData<mbts.TheoPoint> rv = new ExpStrikeKeyedData<mbts.TheoPoint>();
|
||||
// OptionTheoInterpolationData interp_sparse_theo_data = (OptionTheoInterpolationData)_threaded_bb.sec_thread_retrieve_from_cache(_in_bb_precomputed_sparse_theos_tag);
|
||||
// foreach (Triplet<NMSheetExpiration, bool, double> 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<double> strike_list_for_exp = live_theo_map.get_strike_list_for_expiration(nm_exp.option_expiration);
|
||||
// Dictionary<double, mbts.TheoPoint> 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<double, mbts.TheoPoint> 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<DateTime, NMSheetDriverData> _get_option_exp_driver_data_map(NMSheetDataRequest data_request,
|
||||
ExpStrikeKeyedData<mbts.TheoPoint> output_theo_data_map, ExpStrikeKeyedData<mbts.TheoPoint> shared_live_theo_data_map,
|
||||
Dictionary<DateTime, Triplet<string, DateTime, double>> live_driver_map) {
|
||||
Dictionary<DateTime, NMSheetDriverData> rv = new Dictionary<DateTime, NMSheetDriverData>();
|
||||
foreach (Triplet<NMSheetExpiration, bool, double> theo_request in data_request.expiration_request_list) {
|
||||
DateTime option_expiration = theo_request.first.option_expiration;
|
||||
/// live driver
|
||||
Triplet<string, DateTime, double> live_driver_info;
|
||||
live_driver_map.TryGetValue(option_expiration, out live_driver_info);
|
||||
live_driver_info = live_driver_info ?? new Triplet<string, DateTime, double>(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<mbts.TheoPoint> theo_data_map, DateTime option_expiration) {
|
||||
IDictionary<double, mbts.TheoPoint> 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<DateTime, ATMData> _get_atm_data(ExpStrikeKeyedData<mbts.TheoPoint> theo_data) {
|
||||
NMSheetSettings sheet_settings = (NMSheetSettings)_threaded_bb.sec_thread_retrieve_from_cache(_in_bb_sheet_settings_tag) ?? new NMSheetSettings();
|
||||
IDictionary<DateTime, double> option_exp_roll_data = (_threaded_bb.sec_thread_retrieve_from_cache(_in_exp_param_tag) as IDictionary<DateTime, double>) ?? new Dictionary<DateTime, double>();
|
||||
IDictionary<DateTime, ATMData> 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<PNLRollOverDataUnit> _get_rollover_data() { return (OptionContractKeyedData<PNLRollOverDataUnit>)_threaded_bb.sec_thread_retrieve_from_cache(_in_bb_rollover_data_tag); }
|
||||
|
||||
private ExpStrikeKeyedData<Tuple<double, double>> _get_position_map() { return (ExpStrikeKeyedData<Tuple<double, double>>)_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<double>(BlueDataUtility.extractRow(dp.newRows, 0), "scalarData", 0.0);
|
||||
// }
|
||||
return 0.0;
|
||||
}
|
||||
|
||||
#region Vol Shift
|
||||
|
||||
private void _add_vol_shift(ExpStrikeKeyedData<mbts.TheoPoint> 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<NMSheetExpiration, double>);
|
||||
}
|
||||
|
||||
internal static void add_vol_shift(NMSheetSymbol apply_to_symbol, ExpStrikeKeyedData<mbts.TheoPoint> theo_data, Dictionary<NMSheetExpiration, double> exp_shift_map) {
|
||||
foreach (KeyValuePair<NMSheetExpiration, double> 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<double, mbts.TheoPoint> exp_theos = theo_data.get_data_for_single_exp(option_expiration);
|
||||
if (exp_theos != null) {
|
||||
Dictionary<double, mbts.TheoPoint> shifted_exp_theos = new Dictionary<double, mbts.TheoPoint>();
|
||||
foreach (KeyValuePair<double, mbts.TheoPoint> 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
|
||||
}
|
||||
}
|
||||
@@ -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<NMSheetSymbol> _nmsheet_symbol_list;
|
||||
// private Action _cb;
|
||||
// private readonly Dictionary<GeneralTradeTickerData.GeneralTradeTickerDataTag, NMSheetSymbol> _in_data_tag_map = new Dictionary<GeneralTradeTickerData.GeneralTradeTickerDataTag, NMSheetSymbol>();
|
||||
// private readonly Dictionary<GeneralTradeTickerRequest.GeneralTradeTickerRequestTag, NMSheetSymbol> _out_req_tag = new Dictionary<GeneralTradeTickerRequest.GeneralTradeTickerRequestTag, NMSheetSymbol>();
|
||||
// private readonly NMSheetTags.NMSheetSettingsTag _in_nmsheet_setting_tag;
|
||||
// private IDictionary<uint, NMSheetTickerData> _data_map = new Dictionary<uint, NMSheetTickerData>();
|
||||
// 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<NMSheetSymbol> 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<GeneralTradeTickerRequest.GeneralTradeTickerRequestTag, NMSheetSymbol> 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<uint>(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<double>(r, _trade_price_index, Double.NaN);
|
||||
// uint trade_size = BlueDataUtility.get_row_value<uint>(r, _trade_size_index, 0);
|
||||
// double trade_theo = BlueDataUtility.get_row_value<double>(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<uint, NMSheetTickerData> get_data() {
|
||||
return new Dictionary<uint, NMSheetTickerData>();
|
||||
// _cleanup_old_trades();
|
||||
// return new Dictionary<uint, NMSheetTickerData>(_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<uint, NMSheetTickerData> 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
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
|
||||
using bts.api;
|
||||
|
||||
namespace BCG {
|
||||
public class NMSheetCallPutWrapper<T> {
|
||||
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<T> {
|
||||
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<T> {
|
||||
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<NMSheetTheoBBOCross> cross_state;
|
||||
public readonly NMSheetCallPutWrapper<BBOPacket> bbo_data;
|
||||
public readonly NMSheetTickerData call_ticker_data, put_ticker_data;
|
||||
public readonly NMSheetCallPutBidAskWrapper<NMSheetTaskEyeData> task_ee_data;
|
||||
public readonly NMSheetCallPutBidAskWrapper<NMSheetTaskQuoterData> task_quoter_data;
|
||||
|
||||
public NMSheetRowAuxiliaryData(NMSheetCallPutWrapper<BBOPacket> the_bbo_data,
|
||||
NMSheetCallPutWrapper<NMSheetTheoBBOCross> the_cross_state,
|
||||
NMSheetTickerData the_call_trade_alert,
|
||||
NMSheetTickerData the_put_trade_alert,
|
||||
NMSheetCallPutBidAskWrapper<NMSheetTaskEyeData> the_task_ee_data,
|
||||
NMSheetCallPutBidAskWrapper<NMSheetTaskQuoterData> 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<NMSheetExpiration, ATMData> get_atm_data();
|
||||
bool get_row_data(NMSheetSymbol nmsheet_symbol, DateTime option_expiration, double strike, ref double[] row_value, out NMSheetRowAuxiliaryData aux_data);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace BCG {
|
||||
/// <summary>
|
||||
/// Formatter for the NMSheetTheoGrid. Mainly
|
||||
/// 2 functions format_expiration and format_value.
|
||||
/// Uses NMSheetFormattingCacheHelper to cache values
|
||||
/// to avoid formatting.
|
||||
/// </summary>
|
||||
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<NMSheetColumnName> _empty_nan_col_map = new HashSet<NMSheetColumnName>(
|
||||
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<NMSheetColumnName> _empty_zero_col_map = new HashSet<NMSheetColumnName>(
|
||||
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]);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<NMSheetExpiration> filter_expirations(mbts.spark.SystemContractData contract_data, List<NMSheetSymbol> symbol_list, List<NMSheetExpiration> excluded_exp_list) {
|
||||
List<NMSheetExpiration> rv = new List<NMSheetExpiration>();
|
||||
if (contract_data != null && symbol_list != null && excluded_exp_list != null) {
|
||||
HashSet<NMSheetExpiration> exluded_exp_map = new HashSet<NMSheetExpiration>(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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<T>
|
||||
{
|
||||
private class MyTWrapper<S>
|
||||
{
|
||||
public readonly S data;
|
||||
public MyTWrapper(S the_data) { data = the_data; }
|
||||
}
|
||||
|
||||
private MyTWrapper<T>[,] _data_map;
|
||||
private readonly NMSheetExpiration[] _sorted_exps;
|
||||
private readonly double[] _sorted_strikes;
|
||||
private readonly T _def_value = default(T);
|
||||
|
||||
public NMSheetFixedExpStrikeDataMap(IEnumerable<NMSheetExpiration> sorted_exps, IEnumerable<double> sorted_strikes)
|
||||
{
|
||||
_sorted_exps = sorted_exps.ToArray();
|
||||
_sorted_strikes = sorted_strikes.ToArray();
|
||||
_data_map = new MyTWrapper<T>[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<T>(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<T> 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<NMSheetExpiration>(_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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<NMSheetColumnName, Dictionary<double, CacheEntry>> _cached_data = new Dictionary<NMSheetColumnName, Dictionary<double, CacheEntry>>();
|
||||
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<double> to_clean = new List<double>();
|
||||
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<double, CacheEntry> val_to_string;
|
||||
if (!_cached_data.TryGetValue(value_type, out val_to_string))
|
||||
{
|
||||
val_to_string = new Dictionary<double, CacheEntry>();
|
||||
_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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<NMSheetSymbol> 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
|
||||
}
|
||||
}
|
||||
@@ -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<NMSheetExpiration> {
|
||||
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; }
|
||||
}
|
||||
}
|
||||
@@ -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<NMSheetShellWindow>())
|
||||
// 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<SecurityTuple> securities = _launch_menu_vm.get_selected_securities();
|
||||
// List<SymbolExchange> converted = new List<SymbolExchange>();
|
||||
// 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<NMSheetSymbol> _convert_to_o2(IEnumerable<SymbolExchange> symbol_exchanges) {
|
||||
// List<NMSheetSymbol> rv = new List<NMSheetSymbol>();
|
||||
// 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<int> _quoter_ids_awaiting_symbols_for_launch = new List<int>();
|
||||
|
||||
// #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<SecurityTuple> 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<NMSheetSymbol> sheet_syms = new List<NMSheetSymbol>();
|
||||
// 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<IShellWindow> create(Stream load_stream) {
|
||||
// NMSheetSettings nmsheet_settings = CommonGUIUtilities.deserialize_from_stream<NMSheetSettings>(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
|
||||
// }
|
||||
// }
|
||||
@@ -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<NMSheetSettings>(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() { }
|
||||
}
|
||||
}
|
||||
@@ -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<NMSheetSymbol> {
|
||||
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; }
|
||||
|
||||
}
|
||||
}
|
||||
@@ -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<string>(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<string>(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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
using System;
|
||||
using BCG;
|
||||
using BCG.Utilities;
|
||||
|
||||
namespace BCG
|
||||
{
|
||||
public class BlackboardException : Exception
|
||||
{
|
||||
public BlackboardException(string msg)
|
||||
:
|
||||
base(msg)
|
||||
{}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
using mbts.bb;
|
||||
|
||||
namespace BCG {
|
||||
class ClickTradeSettingsTag : EqualsHelper { }
|
||||
}
|
||||
@@ -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<string, object> _get_static_property_bag(Type t)
|
||||
{
|
||||
const BindingFlags flags = BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic;
|
||||
var map = new Dictionary<string, object>();
|
||||
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<Pair<Color, string>> all_colors;
|
||||
|
||||
public static List<Pair<Color, string>> get_all_colors()
|
||||
{
|
||||
if (all_colors == null)
|
||||
{
|
||||
all_colors = new List<Pair<Color, string>>();
|
||||
var colors = _get_static_property_bag(typeof(Colors));
|
||||
|
||||
foreach (KeyValuePair<string, object> colorPair in colors)
|
||||
{
|
||||
Color color = (Color)colorPair.Value;
|
||||
all_colors.Add(new Pair<Color, string>(color, colorPair.Key));
|
||||
}
|
||||
}
|
||||
return all_colors;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -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<string>(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<bts.o2.msgs.Exchange.type>(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<string>(row, sym_col, string.Empty);
|
||||
// bts.o2.msgs.SecurityType.type type = BlueDataUtility.get_row_enum_value<bts.o2.msgs.SecurityType.type>(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<string>(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<T>(byte[] byte_arr)
|
||||
// {
|
||||
// MemoryStream str = new MemoryStream(byte_arr);
|
||||
// str.Position = 0;
|
||||
// return deserialize_from_stream<T>(str);
|
||||
// }
|
||||
|
||||
// public static T deserialize_from_file<T>(string full_file_name) {
|
||||
// return deserialize_from_stream<T>(new FileStream(full_file_name, FileMode.Open, FileAccess.Read));
|
||||
// }
|
||||
|
||||
// public static T deserialize_from_stream<T>(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<T>(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<T> get_selection<T>(MultiSelectDropDown dropdown_box, out bool all_selected, Func<object,T> convert = null)
|
||||
// {
|
||||
// all_selected = dropdown_box.IsAllSelected;
|
||||
// List<T> rv = new List<T>();
|
||||
// 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<T>(MultiSelectDropDown dropdown_box, out bool all_selected)
|
||||
// {
|
||||
// return get_selection<T>(dropdown_box, out all_selected, null).ToArray();
|
||||
// }
|
||||
|
||||
// public static T[] get_selection<T>(MultiSelectDropDown dropdown_box)
|
||||
// {
|
||||
// bool all_selected;
|
||||
// return get_selection<T>(dropdown_box, out all_selected);
|
||||
// }
|
||||
|
||||
// public static IEnumerable<T> get_empty_selection_if_all_selected<T>(MultiSelectDropDown dropdown_box, Func<object, T> convert = null)
|
||||
// {
|
||||
// bool all_selected = false;
|
||||
// IEnumerable<T> selected_multiselect_items = get_selection<T>(dropdown_box, out all_selected, convert);
|
||||
// return all_selected ? new List<T>() { } : selected_multiselect_items;
|
||||
// }
|
||||
|
||||
// public static List<mbts.SecurityExpiration> get_selected_security_expirations_from_display_expiration(MultiSelectDropDown dropdown_box, IDictionary<string, mbts.SecurityExpiration> display_to_real_exp_map)
|
||||
// {
|
||||
// List<mbts.SecurityExpiration> rv = new List<mbts.SecurityExpiration>();
|
||||
// foreach (string display_exp in get_selection<string>(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<string, mbts.SecurityExpiration> 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>(T obj) {
|
||||
try {
|
||||
string json_txt = JsonSerializer.Serialize(obj);
|
||||
var rv = JsonSerializer.Deserialize<T>(json_txt);
|
||||
return rv;
|
||||
} catch {
|
||||
return default(T);
|
||||
}
|
||||
}
|
||||
|
||||
public static T clone_protobuf<T>(T protobuf_obj) {
|
||||
try {
|
||||
MemoryStream ms = new MemoryStream();
|
||||
ProtoBuf.Serializer.SerializeWithLengthPrefix<T>(ms, protobuf_obj, ProtoBuf.PrefixStyle.Fixed32);
|
||||
ms.Position = 0;
|
||||
T rv = ProtoBuf.Serializer.DeserializeWithLengthPrefix<T>(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<T>(MultiSelectDropDown multi_selection_dropdown, IEnumerable<T> all_item_list, IEnumerable<T> selected_item_list, bool sort_items = true)
|
||||
// {
|
||||
// multi_selection_dropdown.IsAllSelected = false;
|
||||
// List<T> all_item_sorted_list = all_item_list == null ? new List<T>() : new List<T>(all_item_list);
|
||||
// if (sort_items)
|
||||
// all_item_sorted_list.Sort();
|
||||
// HashSet<T> selected_item_map = new HashSet<T>(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<T>(MultiSelectDropDown multi_selection_dropdown, IEnumerable<T> items)
|
||||
// {
|
||||
// System.Collections.Generic.HashSet<object> curr_item_map = new HashSet<object>();
|
||||
// foreach (object o in multi_selection_dropdown.Items)
|
||||
// curr_item_map.Add(o);
|
||||
// System.Collections.Generic.HashSet<object> new_item_map = new HashSet<object>(items.Select(t => (object)t));
|
||||
// if (!CollectionHelpers.hashset_equals(curr_item_map, new_item_map))
|
||||
// {
|
||||
// /// finds out the unselected items
|
||||
// Dictionary<object, bool> unselected_items_map = new Dictionary<object, bool>();
|
||||
// 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<T> items_list = new List<T>(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<T>(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<ToolStripItem, bool> remove_func)
|
||||
// {
|
||||
// List<ToolStripItem> to_be_rem = new List<ToolStripItem> ();
|
||||
// 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<DateTime, DateTime> display_to_real_exp_map)
|
||||
// {
|
||||
// bool all_selected;
|
||||
// DateTime[] selected_display_exps = CommonGUIUtilities.get_selection<DateTime>(dropdown_control, out all_selected);
|
||||
// selected_display_exps = all_selected ? new DateTime[] { } : selected_display_exps;
|
||||
// List<DateTime> rv = new List<DateTime>();
|
||||
// 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<InstrumentType>(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));
|
||||
// }
|
||||
}
|
||||
}
|
||||
@@ -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 { }
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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(); }
|
||||
}
|
||||
}
|
||||
@@ -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 {
|
||||
/// <summary>
|
||||
/// 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
|
||||
/// </summary>
|
||||
// TODO: SystemSecurityData will replace this
|
||||
public class ExchangeSecurityMap/* : mbts.bb.IExchangeSecurityMap */{
|
||||
public const uint error_key = 0;
|
||||
private readonly IDictionary<uint, Security> _key_sec_map;
|
||||
private readonly IDictionary<mbts.SecurityStrike, Security[]> _option_map;
|
||||
private readonly IDictionary<mbts.SecurityExpiration, Security> _fut_map;
|
||||
private readonly IDictionary<Venue, IDictionary<string, Security>> _spread_map;
|
||||
|
||||
public ExchangeSecurityMap(IDictionary<uint, Security> key_sec_map,
|
||||
IDictionary<mbts.SecurityStrike, Security[]> option_map,
|
||||
IDictionary<mbts.SecurityExpiration, Security> fut_map,
|
||||
IDictionary<Venue, IDictionary<string, Security>> 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<string, Security> 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<Tuple<Venue, string, DateTime, uint>> get_future_expirations() {
|
||||
// return _fut_map.Select(e => Tuple.Create(e.Key.exchange, e.Key.symbol, e.Key.expiration, e.Key));
|
||||
// }
|
||||
|
||||
public IEnumerable<Tuple<Venue, string, uint>> get_stocks() { return new List<Tuple<Venue, string, uint>>(); }
|
||||
|
||||
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<Triplet<T, uint, uint>> attach_sec_keys<T>(ExpStrikeKeyedData<T> data, string option_name, Venue exchange) {
|
||||
ExpStrikeKeyedData<Triplet<T, uint, uint>> rv = new ExpStrikeKeyedData<Triplet<T, uint, uint>>();
|
||||
uint[] uninit_keys = new uint[] { 0, 0 };
|
||||
foreach (Triplet<DateTime, double, T> 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, uint, uint>(t.third, c_key, p_key));
|
||||
}
|
||||
return rv;
|
||||
}
|
||||
|
||||
// private static DateTime _exp<T>(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<Security> get_matching_option_securities(string symbol, Venue exchange) {
|
||||
List<Security> rv = new List<Security>();
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,186 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
namespace BCG
|
||||
{
|
||||
/// <summary>
|
||||
/// just a conveniant way to store exp,K based data
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
public class ExpStrikeKeyedData <T>
|
||||
{
|
||||
public delegate T CreateT(DateTime exp, double strike);
|
||||
|
||||
private IDictionary<DateTime, IDictionary<double, T>> _map = new Dictionary<DateTime, IDictionary<double, T>>();
|
||||
|
||||
public ExpStrikeKeyedData() { }
|
||||
|
||||
public ExpStrikeKeyedData(ExpStrikeKeyedData<T> data)
|
||||
{
|
||||
foreach (KeyValuePair<DateTime, IDictionary<double, T>> p in data._map)
|
||||
_map[p.Key] = new Dictionary<double, T>(p.Value);
|
||||
}
|
||||
|
||||
public ExpStrikeKeyedData(ICollection<Pair<DateTime, double>> exp_strikes, CreateT del)
|
||||
{
|
||||
foreach (Pair<DateTime, double> 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<double, T> strike_vs_t_map = null;
|
||||
if (!_map.TryGetValue(exp, out strike_vs_t_map))
|
||||
{
|
||||
strike_vs_t_map = new Dictionary<double, T>();
|
||||
_map.Add(exp, strike_vs_t_map);
|
||||
}
|
||||
strike_vs_t_map[strike] = t;
|
||||
}
|
||||
|
||||
public void set_data_for_expiration(DateTime expiration, IDictionary<double, T> strike_data)
|
||||
{
|
||||
_map[expiration] = strike_data;
|
||||
}
|
||||
|
||||
public void clear() { _map.Clear(); }
|
||||
|
||||
public bool delete_data(DateTime exp, double strike)
|
||||
{
|
||||
IDictionary<double, T> 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<double, T> 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<double, T> strike_vs_t_map = null;
|
||||
return _map.TryGetValue(exp, out strike_vs_t_map) && strike_vs_t_map.ContainsKey(strike);
|
||||
}
|
||||
|
||||
public List<double> get_strike_list_for_expiration(DateTime expiration)
|
||||
{
|
||||
List<double> rv = new List<double>();
|
||||
IDictionary<double, T> exp_map = null;
|
||||
if (_map.TryGetValue(expiration, out exp_map))
|
||||
rv = new List<double>(exp_map.Keys);
|
||||
return rv;
|
||||
}
|
||||
|
||||
public T get_random_data_for_exp(DateTime option_expiration)
|
||||
{
|
||||
IDictionary<double, T> 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<DateTime>(_map.Keys).ToArray();
|
||||
}
|
||||
|
||||
public double[] get_strikes()
|
||||
{
|
||||
Dictionary<double, bool> strikes = new Dictionary<double, bool>();
|
||||
foreach (Pair<DateTime, double> 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<Pair<DateTime, double>> get_expstrike_pairs()
|
||||
{
|
||||
List<Pair<DateTime, double>> rv = new List<Pair<DateTime, double>>();
|
||||
foreach (KeyValuePair<DateTime, IDictionary<double, T>> kv1 in _map)
|
||||
{
|
||||
DateTime exp = kv1.Key;
|
||||
foreach (KeyValuePair<double, T> kv2 in kv1.Value)
|
||||
rv.Add(new Pair<DateTime, double>(exp, kv2.Key));
|
||||
}
|
||||
return rv;
|
||||
}
|
||||
|
||||
public ICollection<Triplet<DateTime, double, T>> get_data_linearly ()
|
||||
{
|
||||
List<Triplet<DateTime, double, T>> rv = new List<Triplet<DateTime, double, T>>();
|
||||
foreach (KeyValuePair<DateTime, IDictionary<double, T>> kv1 in _map)
|
||||
{
|
||||
DateTime exp = kv1.Key;
|
||||
foreach (KeyValuePair<double, T> kv2 in kv1.Value)
|
||||
rv.Add(new Triplet<DateTime, double, T>(exp, kv2.Key, kv2.Value));
|
||||
}
|
||||
return rv;
|
||||
}
|
||||
|
||||
public ExpStrikeKeyedData<T> clone_filtered_set(HashSet<DateTime> filtered_expirations, bool is_exp_inclusive,
|
||||
HashSet<double> filtered_strikes, bool is_strike_inclusive)
|
||||
{
|
||||
ExpStrikeKeyedData<T> rv = new ExpStrikeKeyedData<T>();
|
||||
foreach (KeyValuePair<DateTime, IDictionary<double, T>> ep in _map)
|
||||
if ((is_exp_inclusive && filtered_expirations.Contains(ep.Key)) || (!is_exp_inclusive && !filtered_expirations.Contains(ep.Key)))
|
||||
foreach (KeyValuePair<double, T> 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<double, T> get_data_for_single_exp(DateTime exp)
|
||||
{
|
||||
IDictionary<double, T> rv = null;
|
||||
_map.TryGetValue(exp, out rv);
|
||||
return rv;
|
||||
}
|
||||
|
||||
public IReadOnlyDictionary<DateTime, IReadOnlyDictionary<double, T>> get_full_data()
|
||||
{
|
||||
IDictionary<DateTime, IReadOnlyDictionary<double, T>> rv = _map.ToDictionary(kv => kv.Key, kv => (IReadOnlyDictionary<double, T>)kv.Value);
|
||||
return (IReadOnlyDictionary<DateTime, IReadOnlyDictionary<double, T>>)rv;
|
||||
}
|
||||
|
||||
public int count
|
||||
{
|
||||
get
|
||||
{
|
||||
int count = 0;
|
||||
foreach (Dictionary<double, T> exp_map in _map.Values)
|
||||
count += exp_map.Count;
|
||||
return count;
|
||||
}
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region Cloning
|
||||
|
||||
public ExpStrikeKeyedData<S> clone_conversion<S>(Func<DateTime, double, T, S> convert)
|
||||
{
|
||||
ExpStrikeKeyedData<S> rv = new ExpStrikeKeyedData<S>();
|
||||
foreach (var t in get_data_linearly())
|
||||
rv.set_data(t.first, t.second, convert(t.first, t.second, t.third));
|
||||
return rv;
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
@@ -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<SecurityType, IDictionary<string, bts.config.ExpirationDisplayOffsetEntry>> _offset_map;
|
||||
|
||||
static ExpirationFormatter() {
|
||||
// try {
|
||||
// _offset_map = new Dictionary<SecurityType, IDictionary<string, bts.config.ExpirationDisplayOffsetEntry>>();
|
||||
// _offset_map[SecurityType.OPTION] = new Dictionary<string, bts.config.ExpirationDisplayOffsetEntry>();
|
||||
// _offset_map[SecurityType.FUTURE] = new Dictionary<string, bts.config.ExpirationDisplayOffsetEntry>();
|
||||
|
||||
// bts.config.ExpirationDisplayOffset offset_list = mbts.config.Configuration.get<bts.config.ExpirationDisplayOffset>();
|
||||
// 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<bts.o2.msgs.SecurityType>(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<string, bts.config.ExpirationDisplayOffsetEntry> 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); }
|
||||
}
|
||||
}
|
||||
@@ -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<security_key> securities;
|
||||
[ProtoMember(30)]
|
||||
public readonly List<string> security_descriptions;
|
||||
|
||||
public ExplicitTask(IEnumerable<security_key> secs, IEnumerable<string> 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<security_key> securities = null, IEnumerable<string> security_descriptions = null) {
|
||||
return new ExplicitTask(securities ?? this.securities, security_descriptions ?? this.security_descriptions);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
using System;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace BCG.Utilities.General
|
||||
{
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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;
|
||||
/// <summary>
|
||||
/// This a static instance that can be shared across a running process.
|
||||
/// The only member function that is thread-safe right now
|
||||
/// is 'runningMilliseconds'
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
/// <summary>
|
||||
/// starts measuring the time
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// stops recording time
|
||||
/// </summary>
|
||||
public void stop()
|
||||
{
|
||||
QueryPerformanceCounter (ref myEndCount);
|
||||
myTotalCount += myEndCount - myStartCount;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// total milliseconds, ie aggregated time of all intervals
|
||||
/// </summary>
|
||||
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;}}
|
||||
|
||||
/// <summary>
|
||||
/// time between the last start-stop
|
||||
/// </summary>
|
||||
public double lastIntervalTime {get{return (myEndCount - myStartCount) * 1000.0 / myFreq ; }}
|
||||
|
||||
/// <summary>
|
||||
/// Resets the running time
|
||||
/// </summary>
|
||||
public void reset ()
|
||||
{
|
||||
QueryPerformanceCounter(ref myZeroTime);
|
||||
myTotalCount = 0;
|
||||
}
|
||||
|
||||
public long freq
|
||||
{
|
||||
get { return myFreq; }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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<IAgent> _agent_map = new HashSet<IAgent>(), _agents_awaiting_join = new HashSet<IAgent>(), _agents_awaiting_leave = new HashSet<IAgent>();
|
||||
|
||||
// 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<Tuple<object, object>> _safe_write_queue = new List<Tuple<object, object>>();
|
||||
|
||||
// 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<Tuple<object, object>> 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<object> callback) {
|
||||
// this.tag = tag;
|
||||
// this.callback = callback;
|
||||
// }
|
||||
// public object tag { get; private set; }
|
||||
// public Action<object> callback { get; private set; }
|
||||
// }
|
||||
|
||||
// public static class IBlackboardExtensions {
|
||||
// public static T read<T>(this IBlackboard b, object tag) {
|
||||
// var result = b.read(tag);
|
||||
// return result != null ? (T)result : default(T);
|
||||
// }
|
||||
|
||||
// public static T read<T>(this bts.api.IBus b, bts.api.ITag tag) {
|
||||
// var sub = b.subscribe<T>(tag);
|
||||
// var subprime = sub as bts.api.Subscription<T>;
|
||||
// if (subprime != null && subprime.has_value) {
|
||||
// return subprime.value;
|
||||
// }
|
||||
// return default(T);
|
||||
// }
|
||||
|
||||
// private class BlackboardAwaiter<T> : IAgent {
|
||||
// private readonly object _tag;
|
||||
// private readonly IBlackboard _bb;
|
||||
// private readonly TaskCompletionSource<T> _completion_source;
|
||||
|
||||
// public BlackboardAwaiter(IBlackboard bb, object tag) {
|
||||
// _completion_source = new TaskCompletionSource<T>();
|
||||
// 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<T> task { get { return _completion_source.Task; } }
|
||||
// }
|
||||
|
||||
// public static Task<T> read_next<T>(this IBlackboard bb, object tag) {
|
||||
// var temp = new BlackboardAwaiter<T>(bb, tag);
|
||||
// return temp.task;
|
||||
// }
|
||||
|
||||
// private class BlackboardProxyAgent : IAgent, IDisposable {
|
||||
// private readonly IBlackboard _bb;
|
||||
// private readonly IDictionary<object, Action<object>> _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<object> cb;
|
||||
// if (_callback.TryGetValue(tag, out cb))
|
||||
// cb(_bb.read(tag));
|
||||
// }
|
||||
// }
|
||||
|
||||
// private class BlackboardProxyAgent<TData> : IAgent, IDisposable {
|
||||
// public BlackboardProxyAgent(IBlackboard bb, object tag, Action<TData> callback) {
|
||||
// _tag = tag;
|
||||
// _callback = callback;
|
||||
// _bb = bb;
|
||||
// change(tag);
|
||||
// _bb.join(this);
|
||||
// }
|
||||
|
||||
// private readonly IBlackboard _bb;
|
||||
// private readonly object _tag;
|
||||
// private readonly Action<TData> _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<TTag, TData> : IAgent, IDisposable {
|
||||
// public BlackbaordProxyAgent(IBlackboard bb, Action<TTag, TData> callback) {
|
||||
// _callback = callback;
|
||||
// _bb = bb;
|
||||
// _bb.join(this);
|
||||
// }
|
||||
|
||||
// private readonly IBlackboard _bb;
|
||||
// private readonly Action<TTag, TData> _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<TData>(this IBlackboard bb, object tag, Action<TData> callback) {
|
||||
// return new BlackboardProxyAgent<TData>(bb, tag, callback);
|
||||
// }
|
||||
|
||||
// [Obsolete]
|
||||
// public static IDisposable subscribe<TTag, TData>(this IBlackboard bb, Action<TTag, TData> callback) {
|
||||
// return new BlackbaordProxyAgent<TTag, TData>(bb, callback);
|
||||
// }
|
||||
|
||||
// [Obsolete]
|
||||
// public static IDisposable subscribe<TTag, TData>(this IBlackboard bb, Action<TData> callback) {
|
||||
// return bb.subscribe(new Action<TTag, TData>((t, d) => callback(d)));
|
||||
// }
|
||||
|
||||
// public static IDisposable subscribe(this IBlackboard bb, params BBSub[] subscriptions) {
|
||||
// return new BlackboardProxyAgent(bb, subscriptions);
|
||||
// }
|
||||
// }
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
using System;
|
||||
using BCG;
|
||||
using BCG.Utilities;
|
||||
|
||||
namespace BCG
|
||||
{
|
||||
public interface IVirtualTag
|
||||
{
|
||||
object getRealTag(object changedTagHint, object oldValue, Blackboard bb);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
using System;
|
||||
|
||||
namespace BCG.Utilities.General
|
||||
{
|
||||
public interface IWorker
|
||||
{
|
||||
void doWork();
|
||||
}
|
||||
}
|
||||
@@ -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<string> selected_symbols,
|
||||
IEnumerable<DateTime> selected_expirations,
|
||||
IEnumerable<SavedTaskFilter> 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<string> selected_symbols = null,
|
||||
IEnumerable<DateTime> selected_expirations = null,
|
||||
IEnumerable<SavedTaskFilter> 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<string> selected_symbols;
|
||||
public readonly List<DateTime> selected_expirations;
|
||||
public readonly List<SavedTaskFilter> 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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 { }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<string> { public OptionDriverBBOTag(string option_name) : base(option_name) { } }
|
||||
|
||||
public class OptionDriverDetailedBBOTag : KeyedTag<string> { public OptionDriverDetailedBBOTag(string option_name) : base(option_name) { } }
|
||||
|
||||
public class OptionDriverSymbolBBOTag : KeyedTag<string> { public OptionDriverSymbolBBOTag(string option_name) : base(option_name) { } }
|
||||
|
||||
public class DriverDailySettlementPriceTag : mbts.bb.EqualsHelper { public DriverDailySettlementPriceTag() { } }
|
||||
}
|
||||
}
|
||||
@@ -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<IWorker, Pair<TimeSpan, DateTime>> myWorkers = new Dictionary<IWorker, Pair<TimeSpan, DateTime>>(),
|
||||
myJustAdded = new Dictionary<IWorker, Pair<TimeSpan, DateTime>>(),
|
||||
myJustRemoved = new Dictionary<IWorker, Pair<TimeSpan, DateTime>>();
|
||||
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<TimeSpan, DateTime>(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<IWorker, Pair<TimeSpan, DateTime>> p in myJustAdded) {
|
||||
myWorkers.Add(p.Key, p.Value);
|
||||
}
|
||||
foreach (KeyValuePair<IWorker, Pair<TimeSpan, DateTime>> p in myJustRemoved) {
|
||||
myWorkers.Remove(p.Key);
|
||||
}
|
||||
myJustAdded.Clear();
|
||||
myJustRemoved.Clear();
|
||||
if (DateTime.UtcNow - myLastDoWorkTime >= myPeriod) {
|
||||
myTimer.start();
|
||||
//myLogEntries();
|
||||
myLastDoWorkTime = DateTime.UtcNow;
|
||||
foreach (KeyValuePair<IWorker, Pair<TimeSpan, DateTime>> 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<TimeSpan, DateTime>(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<IWorker, Pair<TimeSpan, DateTime>> 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();
|
||||
// }
|
||||
|
||||
//}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
using System;
|
||||
|
||||
using BCG;
|
||||
using BCG.Utilities;
|
||||
|
||||
using bts.api;
|
||||
|
||||
namespace BCG {
|
||||
/// <summary>
|
||||
/// Serves as the contract information (ie no calculated data, theos, deltas etc) for one leg of
|
||||
/// the spread
|
||||
/// </summary>
|
||||
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");
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
|
||||
namespace BCG
|
||||
{
|
||||
public class CallPutValue<T>
|
||||
{
|
||||
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<T> shallow_copy ()
|
||||
{
|
||||
return new CallPutValue<T>() { call_value = call_value, put_value = put_value };
|
||||
}
|
||||
}
|
||||
|
||||
public class OptionContractKeyedData <T>
|
||||
{
|
||||
private Dictionary<DateTime, Dictionary<double, CallPutValue<T>>> _map = new Dictionary<DateTime, Dictionary<double, CallPutValue<T>>>();
|
||||
public OptionContractKeyedData() {}
|
||||
|
||||
public IReadOnlyDictionary<DateTime, IReadOnlyDictionary<double, CallPutValue<T>>> get_data()
|
||||
{
|
||||
Dictionary<DateTime, IReadOnlyDictionary<double, CallPutValue<T>>> rv = new Dictionary<DateTime, IReadOnlyDictionary<double, CallPutValue<T>>>();
|
||||
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<double, CallPutValue<T>> k_map = null;
|
||||
if (!_map.TryGetValue(e, out k_map))
|
||||
_map.Add(e, k_map = new Dictionary<double, CallPutValue<T>>());
|
||||
CallPutValue<T> k_val = null;
|
||||
if (!k_map.TryGetValue(k, out k_val))
|
||||
k_map.Add(k, k_val = new CallPutValue<T>());
|
||||
k_val.set_value(is_call, data);
|
||||
}
|
||||
|
||||
public T getValue(DateTime e, double k, bool is_call)
|
||||
{
|
||||
Dictionary<double, CallPutValue<T>> k_map = null;
|
||||
CallPutValue<T> 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<double, CallPutValue<T>> k_map = null;
|
||||
CallPutValue<T> 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<double, CallPutValue<T>> k_map = null;
|
||||
CallPutValue<T> 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<double, CallPutValue<T>> k_map = null;
|
||||
CallPutValue<T> 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<double, CallPutValue<T>> k_map;
|
||||
return _map.TryGetValue(e, out k_map) && k_map != null && k_map.Count > 0;
|
||||
}
|
||||
|
||||
public List<Triplet<DateTime, double, CallPutValue<T>>> get_linear_data ()
|
||||
{
|
||||
List<Triplet<DateTime, double, CallPutValue<T>>> rv = new List<Triplet<DateTime, double, CallPutValue<T>>>();
|
||||
foreach (KeyValuePair<DateTime, Dictionary<double, CallPutValue<T>>> kv1 in _map)
|
||||
{
|
||||
DateTime e = kv1.Key;
|
||||
foreach (KeyValuePair<double, CallPutValue<T>> kv2 in kv1.Value)
|
||||
rv.Add(new Triplet<DateTime, double, CallPutValue<T>>(e, kv2.Key, kv2.Value));
|
||||
}
|
||||
return rv;
|
||||
}
|
||||
|
||||
public IReadOnlyDictionary<double, CallPutValue<T>> get_exp_data(DateTime exp)
|
||||
{
|
||||
Dictionary<double, CallPutValue<T>> exp_map = null;
|
||||
return _map.TryGetValue(exp, out exp_map) ? exp_map : new Dictionary<double, CallPutValue<T>>();
|
||||
}
|
||||
|
||||
public OptionContractKeyedData<T> shallow_copy ()
|
||||
{
|
||||
Dictionary<DateTime, Dictionary<double, CallPutValue<T>>> rv = new Dictionary<DateTime,Dictionary<double,CallPutValue<T>>> ();
|
||||
foreach (KeyValuePair<DateTime, Dictionary<double, CallPutValue<T>>> kv1 in _map)
|
||||
{
|
||||
Dictionary<double, CallPutValue<T>> k_map = new Dictionary<double, CallPutValue<T>>();
|
||||
foreach (KeyValuePair<double, CallPutValue<T>> kv2 in kv1.Value)
|
||||
k_map.Add(kv2.Key, kv2.Value.shallow_copy());
|
||||
rv.Add(kv1.Key, k_map);
|
||||
}
|
||||
return new OptionContractKeyedData<T>() { _map = rv };
|
||||
}
|
||||
|
||||
public void mutate_data(Action<T> mutate_func)
|
||||
{
|
||||
foreach (Dictionary<double, CallPutValue<T>> k_map in _map.Values)
|
||||
foreach (CallPutValue<T> kp_val in k_map.Values)
|
||||
{
|
||||
mutate_func(kp_val.call_value);
|
||||
mutate_func(kp_val.put_value);
|
||||
}
|
||||
}
|
||||
|
||||
public IDictionary<DateTime, IEnumerable<double>> get_contracts()
|
||||
{
|
||||
Dictionary<DateTime, IEnumerable<double>> rv = new Dictionary<DateTime, IEnumerable<double>>();
|
||||
foreach (KeyValuePair<DateTime, Dictionary<double, CallPutValue<T>>> k in _map)
|
||||
rv.Add(k.Key, k.Value.Keys);
|
||||
return rv;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
|
||||
namespace BCG
|
||||
{
|
||||
/// <summary>
|
||||
/// Just like the C++ pair template
|
||||
/// </summary>
|
||||
/// <typeparam name="F"></typeparam>
|
||||
/// <typeparam name="S"></typeparam>
|
||||
[Serializable]
|
||||
public class Pair<F, S>
|
||||
{
|
||||
public F first;
|
||||
public S second;
|
||||
|
||||
public Pair() { }
|
||||
public Pair(F f, S s)
|
||||
{
|
||||
first = f;
|
||||
second = s;
|
||||
}
|
||||
|
||||
public Pair(KeyValuePair<F, S> 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<F, S> && ToString() == obj.ToString();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public static class Pair
|
||||
{
|
||||
public static Pair<F, S> Create<F,S>(F a, S b) {
|
||||
return new Pair<F, S>(a, b);
|
||||
}
|
||||
}
|
||||
|
||||
[Serializable]
|
||||
public class Triplet<F, S, T>
|
||||
{
|
||||
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<F, S, T> from_tuple(Tuple<F, S, T> t) { return new Triplet<F, S, T>(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<F, S, T> && ToString() == obj.ToString();
|
||||
}
|
||||
|
||||
public override int GetHashCode()
|
||||
{
|
||||
return ToString().GetHashCode();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
using System.Collections;
|
||||
using BCG.Utilities;
|
||||
using BCG.Utilities.General;
|
||||
|
||||
namespace BCG
|
||||
{
|
||||
/// <summary>
|
||||
/// Proprietary Rounding Algorithm by Pedro Pinto, Blue Capital Group, LLC.
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
using mbts.bb;
|
||||
|
||||
namespace BCG
|
||||
{
|
||||
public class PriceSettingsTag : EqualsHelper
|
||||
{
|
||||
}
|
||||
}
|
||||
@@ -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<object>
|
||||
{
|
||||
public AquireTag(object req_id) : base(req_id) { }
|
||||
}
|
||||
|
||||
public class DisposeTag : KeyedTag<object>
|
||||
{
|
||||
public DisposeTag(object req_id) : base(req_id) { }
|
||||
}
|
||||
|
||||
public class ActiveOptionsTag : mbts.bb.EqualsHelper
|
||||
{
|
||||
public ActiveOptionsTag() { }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
using mbts.bb;
|
||||
|
||||
namespace BCG
|
||||
{
|
||||
class SpreadWindowSettingsTag : EqualsHelper
|
||||
{
|
||||
}
|
||||
}
|
||||
@@ -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<mbts.SecurityTuple> sectups;
|
||||
public readonly object user_id;
|
||||
public readonly bool is_activate;
|
||||
|
||||
public SymbolResourceAllocationUnit(IEnumerable<mbts.SecurityTuple> this_sectups,
|
||||
object this_user_id,
|
||||
bool this_is_activate)
|
||||
{
|
||||
sectups = this_sectups;
|
||||
user_id = this_user_id;
|
||||
is_activate = this_is_activate;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<Tuple<int, double>> overridden_edges;
|
||||
[ProtoMember(210)]
|
||||
public readonly List<Tuple<int, uint>> 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<Tuple<int, double>> overridden_edges,
|
||||
List<Tuple<int, uint>> 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<Tuple<int, double>>(),
|
||||
overridden_sizes: new List<Tuple<int, uint>>());
|
||||
}
|
||||
}
|
||||
|
||||
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<Tuple<int, double>> overridden_edges = null,
|
||||
List<Tuple<int, uint>> 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);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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<bts.config.Engines>();
|
||||
// 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<bts.config.toggles.Enable_Tasking_For_GLBX>().enabled;
|
||||
// enable_tasking_for_CBOE = mbts.config.Configuration.get<bts.config.toggles.Enable_Tasking_For_CBOE>().enabled;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -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<TaskLiveData>
|
||||
{
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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; }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<bts.config.toggles.
|
||||
// Assume_tied_spreads_hedged_gamma_price>().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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<string> { public LiveOptionTheoTag(string option_name) : base(option_name) { } }
|
||||
|
||||
public class PrecomputedOptionTheoTag : KeyedTag<string> { public PrecomputedOptionTheoTag(string option_name) : base(option_name) { } }
|
||||
|
||||
public class LiveFutureTheoTag : KeyedTag<string> { public LiveFutureTheoTag(string future_name) : base(future_name) { } }
|
||||
|
||||
public class TheoreticalEdgesTag : mbts.bb.EqualsHelper { }
|
||||
|
||||
public class OptionRollsTag : KeyedTag<string> { public OptionRollsTag(string option_name) : base(option_name) { } }
|
||||
|
||||
public class PNLRollOverDataTag : KeyedTag<string> { 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) { }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
|
||||
namespace BCG {
|
||||
/// <summary>
|
||||
/// 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
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
public class ThreadSafeQueue<T> {
|
||||
private readonly int _max_size = Int32.MaxValue;
|
||||
private Queue<T> _main_queue = new Queue<T>();
|
||||
|
||||
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<T> 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<T> 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<T> dequeueAll() {
|
||||
List<T> rv = new List<T>();
|
||||
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<T> comp) {
|
||||
bool rv;
|
||||
lock (this) {
|
||||
Dictionary<int, bool> marked_for_deletion = new Dictionary<int, bool>();
|
||||
List<T> 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<T> comp) {
|
||||
if (comp != null)
|
||||
return comp(t1, t2) == 0;
|
||||
else
|
||||
return t1 != null && t1.Equals(t2);
|
||||
}
|
||||
|
||||
public virtual List<T> dequeueLimited(int max) {
|
||||
List<T> rv = new List<T>();
|
||||
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));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,203 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
namespace BCG {
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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<object, bool> _subsribed_tags = new Dictionary<object, bool>();
|
||||
private List<Func<object, bool>> _subsribed_tags_funcs = new List<Func<object, bool>>();
|
||||
private Dictionary<object, object> _cached_data = new Dictionary<object, object>();
|
||||
/// thread transfer data
|
||||
private ThreadSafeQueue<Pair<object, object>> _main_to_sec_callback_waiting_data_queue, _sec_to_main_write_request_queue;
|
||||
private ThreadSafeQueue<object> _sec_to_main_subscription_request_queue;
|
||||
private ThreadSafeQueue<Func<object, bool>> _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<Pair<object, object>>(Int32.MaxValue, String.Format("MainToSecondaryWrite_{0}", _bb_name), true, 250, TimeSpan.FromSeconds(30));
|
||||
_sec_to_main_write_request_queue = new ThreadSafeQueue<Pair<object, object>>(Int32.MaxValue, String.Format("SecondaryToMainWrite_{0}", _bb_name), true, 250, TimeSpan.FromSeconds(30));
|
||||
_sec_to_main_subscription_request_queue = new ThreadSafeQueue<object>(Int32.MaxValue, String.Format("SecondaryToMainSubscription_{0}", _bb_name), true, 50, TimeSpan.FromSeconds(30));
|
||||
_sec_to_main_subscription_func_request_queue = new ThreadSafeQueue<Func<object, bool>>(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<object, bool> 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; }
|
||||
|
||||
/// <summary>
|
||||
/// this can be a blocking or non blocking call
|
||||
/// depending on the last arg
|
||||
/// </summary>
|
||||
/// <param name="tag"></param>
|
||||
/// <param name="value"></param>
|
||||
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<object, object>(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<Pair<object, object>> bb_data = _main_to_sec_callback_waiting_data_queue.dequeueAll();
|
||||
_store_in_cache(bb_data);
|
||||
if (data_callback != null)
|
||||
foreach (Pair<object, object> 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<Pair<object, object>> bb_data) {
|
||||
foreach (Pair<object, object> 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<object> 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<object, object>(tag, v));
|
||||
}
|
||||
List<Func<object, bool>> 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<object, bool> f in funcs_waiting_to_be_subscribed)
|
||||
if (f(tag))
|
||||
_main_to_sec_callback_waiting_data_queue.enqueue(new Pair<object, object>(tag, _bb.read(tag)));
|
||||
}
|
||||
/// waiting write requests
|
||||
List<Pair<object, object>> data_to_be_written = _sec_to_main_write_request_queue.dequeueAll();
|
||||
foreach (Pair<object, object> 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<object, object>(tag, _bb.read(tag)));
|
||||
else {
|
||||
foreach (Func<object, bool> f in _subsribed_tags_funcs)
|
||||
if (f(tag))
|
||||
_main_to_sec_callback_waiting_data_queue.enqueue(new Pair<object, object>(tag, _bb.read(tag)));
|
||||
}
|
||||
}
|
||||
|
||||
public void commit(System.Collections.IDictionary changedTags) { }
|
||||
|
||||
#endregion
|
||||
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -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 {
|
||||
/// <summary>
|
||||
/// Tag for the complete position for one symbol,
|
||||
/// for the account the logged in trader is supposed
|
||||
/// to trade in
|
||||
/// </summary>
|
||||
public class OptionSymbolPositionTag : KeyedTag<string> { 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<string> { 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() { } }
|
||||
}
|
||||
}
|
||||
@@ -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<UInt32> _default_order_size = 10;
|
||||
public Nullable<UInt32> 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<bool> _use_trade_price_for_ticker_orders = false;
|
||||
public Nullable<bool> UseTradePriceForTickerOrders
|
||||
{
|
||||
get { return _use_trade_price_for_ticker_orders; }
|
||||
set { _use_trade_price_for_ticker_orders = (value == null ? false : value); }
|
||||
}
|
||||
|
||||
private Nullable<UInt32> _direct_io_order_size = 0;
|
||||
public Nullable<UInt32> 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
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
using System;
|
||||
|
||||
namespace BCG
|
||||
{
|
||||
/// <summary>
|
||||
/// Maps to BidAskConfig. Denotes the grid
|
||||
/// settings that should be used in the display of bid and asks
|
||||
/// for a given product
|
||||
/// </summary>
|
||||
[Serializable]
|
||||
public class BidAskConfigTag : ProductTag, IConfigTag
|
||||
{
|
||||
public BidAskConfigTag (string product)
|
||||
: base (product)
|
||||
{}
|
||||
}
|
||||
}
|
||||
@@ -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<Blackboard> _bb;
|
||||
|
||||
// [ImportingConstructor]
|
||||
// public BlackboardBusProvider(Lazy<Blackboard> 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<T>(bts.api.ITag tag) {
|
||||
// return tag is IBlackboardTag;
|
||||
// }
|
||||
|
||||
// public override IObservable<T> create_subscription<T>(bts.api.ITag tag) {
|
||||
// var bbtag = (IBlackboardTag)tag;
|
||||
// return Observable.Create<T>(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<Blackboard> _bb;
|
||||
// private readonly IBus _bus;
|
||||
|
||||
// [ImportingConstructor]
|
||||
// public BlackboardIBus(IBus bus, Lazy<Blackboard> 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<T>(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<object> subscribe(bts.api.ITag tag, Type data_type) {
|
||||
// return _bus.subscribe(tag, data_type);
|
||||
// }
|
||||
|
||||
// public ISubscription<T> subscribe<T>(bts.api.ITag tag) {
|
||||
// return _bus.subscribe<T>(tag);
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
@@ -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<SecuritySideKey> {
|
||||
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<bts.config.AnalyticsOptions>().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<bts.utils.HostInfo>();
|
||||
// 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);
|
||||
// };
|
||||
// }
|
||||
// }
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
using System;
|
||||
using BCG;
|
||||
using BCG.Utilities;
|
||||
|
||||
namespace BCG
|
||||
{
|
||||
/// <summary>
|
||||
/// Marker interface for all config items
|
||||
/// </summary>
|
||||
public interface IConfigTag
|
||||
{}
|
||||
}
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
using System;
|
||||
using System.Runtime.Serialization;
|
||||
using BCG;
|
||||
using BCG.Utilities;
|
||||
|
||||
namespace BCG
|
||||
{
|
||||
/// <summary>
|
||||
/// Maps to an object of type GridConfig. Denotes the grid
|
||||
/// settings that should be used in the display of theos
|
||||
/// for a given product
|
||||
/// </summary>
|
||||
[Serializable]
|
||||
public class TheoGridConfigTag : ProductTag, IConfigTag
|
||||
{
|
||||
public TheoGridConfigTag (string product) :base(product)
|
||||
{}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
using System;
|
||||
|
||||
namespace BCG
|
||||
{
|
||||
public interface ITag{}
|
||||
}
|
||||
@@ -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) { }
|
||||
}
|
||||
}
|
||||
@@ -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));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
namespace BCG
|
||||
{
|
||||
/// <summary>
|
||||
/// Encapsultes the ATM greeks, for a single option_expiration.
|
||||
/// Also includes the roll and fwd for that exp
|
||||
/// </summary>
|
||||
public class ATMData
|
||||
{
|
||||
public double roll_offset = Double.NaN, fwd = Double.NaN;
|
||||
public Dictionary<double, mbts.TheoPoint> strike_vs_data = new Dictionary<double, mbts.TheoPoint>();
|
||||
public Dictionary<double, Pair<double, double>> strike_vs_callput_bbo_mid = new Dictionary<double, Pair<double, double>>();
|
||||
|
||||
public double get_md_midpoint_straddle(double strike)
|
||||
{
|
||||
Pair<double, double> 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<double> get_sorted_strikes()
|
||||
{
|
||||
List<double> rv = new List<double>(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<DateTime, ATMData> atmData)
|
||||
{
|
||||
foreach (ATMData d in atmData.Values)
|
||||
d.reduce_to_nearest_expiration();
|
||||
}
|
||||
|
||||
public static Dictionary<DateTime, ICollection<double>> get_exp_strike_map(Dictionary<DateTime, ATMData> atm_data_map)
|
||||
{
|
||||
Dictionary<DateTime, ICollection<double>> rv = new Dictionary<DateTime, ICollection<double>>();
|
||||
if (atm_data_map != null)
|
||||
foreach (KeyValuePair<DateTime, ATMData> p in atm_data_map)
|
||||
rv.Add(p.Key, new List<double>(p.Value.strike_vs_data.Keys));
|
||||
return rv;
|
||||
}
|
||||
}
|
||||
}
|
||||
+102
@@ -0,0 +1,102 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
using BCG.Utilities;
|
||||
|
||||
namespace BCG {
|
||||
/// <summary>
|
||||
/// Bunch of static funtions to deal with ATM
|
||||
/// </summary>
|
||||
public class OptionATMDataSource {
|
||||
#region stateless helpers
|
||||
internal static void fill_in_bbo(ref Dictionary<DateTime, ATMData> atm_data_map,
|
||||
ExpStrikeKeyedData<Triplet<mbts.TheoPoint, uint, uint>> theo_data,
|
||||
IDictionary<uint, BBOPacket> bbo_data) {
|
||||
foreach (KeyValuePair<DateTime, ATMData> 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<double, Pair<double, double>>();
|
||||
foreach (double k in exp_atm_data.strike_vs_data.Keys) {
|
||||
Triplet<mbts.TheoPoint, uint, uint> tp = theo_data.get_data(exp, k) ?? new Triplet<mbts.TheoPoint, uint, uint>(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<double, double>((call_bid_price + call_ask_price) / 2, (put_bid_price + put_ask_price) / 2);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal static IDictionary<DateTime, ATMData> compute_atm_data(string option_symbol, double one_five, ExpStrikeKeyedData<mbts.TheoPoint> theo_data, IDictionary<DateTime, double> opt_exp_rolls) {
|
||||
IDictionary<DateTime, double> exp_vs_drivers = _get_computed_drivers(theo_data);
|
||||
IDictionary<DateTime, ATMData> rv = new Dictionary<DateTime, ATMData>();
|
||||
if (one_five != 0)
|
||||
foreach (DateTime exp in new List<DateTime>(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<DateTime, double> _get_computed_drivers(ExpStrikeKeyedData<mbts.TheoPoint> expStrikeTheos) {
|
||||
Dictionary<DateTime, double> rv = new Dictionary<DateTime, double>();
|
||||
foreach (Triplet<DateTime, double, mbts.TheoPoint> 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<mbts.TheoPoint> theo_data, IDictionary<DateTime, double> opt_exp_rolls) {
|
||||
ATMData rv = new ATMData();
|
||||
IDictionary<double, mbts.TheoPoint> 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<double, mbts.TheoPoint> 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
|
||||
}
|
||||
}
|
||||
+14
@@ -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)
|
||||
{ }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
|
||||
namespace BCG
|
||||
{
|
||||
public enum SheetsAlertMode
|
||||
{
|
||||
SimpleCross,
|
||||
Proximity
|
||||
}
|
||||
}
|
||||
@@ -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() { }
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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<BidAskConfig.OrderType> preset_order_hint = null;
|
||||
public double preset_price = Double.NaN;
|
||||
public UInt32 preset_size = 0;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
namespace BCG
|
||||
{
|
||||
/// <summary>
|
||||
/// Corresponding data is a dictionary of exps vs
|
||||
/// their shifts. An absent expiration denotes a 0 vol shift
|
||||
/// </summary>
|
||||
public class VolShiftTag : ProductTag
|
||||
{
|
||||
public VolShiftTag(string product)
|
||||
: base(product)
|
||||
{ }
|
||||
}
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 2.4 KiB |
@@ -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;
|
||||
}
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 894 B |
@@ -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; }
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
|
||||
}
|
||||
}
|
||||
@@ -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>
|
||||
/// Summary description for GDIPlusWrapper.
|
||||
/// </summary>
|
||||
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
|
||||
}
|
||||
}
|
||||
@@ -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<bool> _show_marketdata_size = null;
|
||||
public Nullable<bool> 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<bool> _show_theo = true;
|
||||
public Nullable<bool> ShowTheo
|
||||
{
|
||||
get { return _show_theo; }
|
||||
set
|
||||
{
|
||||
_show_theo = value == null ? false : value;
|
||||
}
|
||||
}
|
||||
|
||||
private Nullable<bool> _show_delta = true;
|
||||
public Nullable<bool> 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<bool> _show_presave_theos = false;
|
||||
public Nullable<bool> ShowPreSaveTheos
|
||||
{
|
||||
get { return _show_presave_theos == null ? false : _show_presave_theos.Value; }
|
||||
set { _show_presave_theos = value == null ? false : value.Value; }
|
||||
}
|
||||
|
||||
private Nullable<bool> _show_presave_theos_diff = false;
|
||||
public Nullable<bool> 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<bool> _show_standard_strike = false;
|
||||
public Nullable<bool> 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<int> _grid_paint_throttle_ms = 333;
|
||||
public Nullable<int> GridPaintThrottleMs
|
||||
{
|
||||
get { return _grid_paint_throttle_ms; }
|
||||
set { _grid_paint_throttle_ms = (value == null ? 0 : value); }
|
||||
}
|
||||
|
||||
private Nullable<double> _driver_mult = 1.0;
|
||||
public Nullable<double> 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<StraddleDisplayEnum> _straddle_display = StraddleDisplayEnum.StraddleTheo;
|
||||
public Nullable<StraddleDisplayEnum> StraddleDisplay
|
||||
{
|
||||
get { return _straddle_display.HasValue ? _straddle_display.Value : StraddleDisplayEnum.StraddleTheo; }
|
||||
set { _straddle_display = (value.HasValue ? value.Value : StraddleDisplayEnum.StraddleTheo); }
|
||||
}
|
||||
|
||||
private Nullable<Color> _straddle_theo_vs_market_negative_back_color = Color.Pink;
|
||||
public Nullable<Color> 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<Color> _straddle_theo_vs_market_negative_font_color = Color.Black;
|
||||
public Nullable<Color> 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<Color> _straddle_theo_vs_market_positive_back_color = Color.LightGreen;
|
||||
public Nullable<Color> 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<Color> _straddle_theo_vs_market_positive_font_color = Color.Black;
|
||||
public Nullable<Color> 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<bool> _show_vol_shift_control_in_expiration_header = true;
|
||||
public Nullable<bool> 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
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
using System;
|
||||
using BCG;
|
||||
|
||||
namespace BCG
|
||||
{
|
||||
/// <summary>
|
||||
/// 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
|
||||
/// </summary>
|
||||
public interface ITheoFormatter
|
||||
{
|
||||
string formatTheo (string theoType, object value);
|
||||
string formatExpiration (DateTime expiration);
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
/// <summary>
|
||||
/// Clean up any resources being used.
|
||||
/// </summary>
|
||||
protected override void Dispose(bool disposing) {
|
||||
if (disposing) {
|
||||
if (components != null) {
|
||||
components.Dispose();
|
||||
}
|
||||
}
|
||||
base.Dispose(disposing);
|
||||
}
|
||||
|
||||
#region Component Designer generated code
|
||||
/// <summary>
|
||||
/// Required method for Designer support - do not modify
|
||||
/// the contents of this method with the code editor.
|
||||
/// </summary>
|
||||
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
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<root>
|
||||
<!--
|
||||
Microsoft ResX Schema
|
||||
|
||||
Version 2.0
|
||||
|
||||
The primary goals of this format is to allow a simple XML format
|
||||
that is mostly human readable. The generation and parsing of the
|
||||
various data types are done through the TypeConverter classes
|
||||
associated with the data types.
|
||||
|
||||
Example:
|
||||
|
||||
... ado.net/XML headers & schema ...
|
||||
<resheader name="resmimetype">text/microsoft-resx</resheader>
|
||||
<resheader name="version">2.0</resheader>
|
||||
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
|
||||
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
|
||||
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
|
||||
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
|
||||
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
|
||||
<value>[base64 mime encoded serialized .NET Framework object]</value>
|
||||
</data>
|
||||
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
|
||||
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
|
||||
<comment>This is a comment</comment>
|
||||
</data>
|
||||
|
||||
There are any number of "resheader" rows that contain simple
|
||||
name/value pairs.
|
||||
|
||||
Each data row contains a name, and value. The row also contains a
|
||||
type or mimetype. Type corresponds to a .NET class that support
|
||||
text/value conversion through the TypeConverter architecture.
|
||||
Classes that don't support this are serialized and stored with the
|
||||
mimetype set.
|
||||
|
||||
The mimetype is used for serialized objects, and tells the
|
||||
ResXResourceReader how to depersist the object. This is currently not
|
||||
extensible. For a given mimetype the value must be set accordingly:
|
||||
|
||||
Note - application/x-microsoft.net.object.binary.base64 is the format
|
||||
that the ResXResourceWriter will generate, however the reader can
|
||||
read any of the formats listed below.
|
||||
|
||||
mimetype: application/x-microsoft.net.object.binary.base64
|
||||
value : The object must be serialized with
|
||||
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
|
||||
: and then encoded with base64 encoding.
|
||||
|
||||
mimetype: application/x-microsoft.net.object.soap.base64
|
||||
value : The object must be serialized with
|
||||
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
|
||||
: and then encoded with base64 encoding.
|
||||
|
||||
mimetype: application/x-microsoft.net.object.bytearray.base64
|
||||
value : The object must be serialized into a byte array
|
||||
: using a System.ComponentModel.TypeConverter
|
||||
: and then encoded with base64 encoding.
|
||||
-->
|
||||
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
|
||||
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
|
||||
<xsd:element name="root" msdata:IsDataSet="true">
|
||||
<xsd:complexType>
|
||||
<xsd:choice maxOccurs="unbounded">
|
||||
<xsd:element name="metadata">
|
||||
<xsd:complexType>
|
||||
<xsd:sequence>
|
||||
<xsd:element name="value" type="xsd:string" minOccurs="0" />
|
||||
</xsd:sequence>
|
||||
<xsd:attribute name="name" use="required" type="xsd:string" />
|
||||
<xsd:attribute name="type" type="xsd:string" />
|
||||
<xsd:attribute name="mimetype" type="xsd:string" />
|
||||
<xsd:attribute ref="xml:space" />
|
||||
</xsd:complexType>
|
||||
</xsd:element>
|
||||
<xsd:element name="assembly">
|
||||
<xsd:complexType>
|
||||
<xsd:attribute name="alias" type="xsd:string" />
|
||||
<xsd:attribute name="name" type="xsd:string" />
|
||||
</xsd:complexType>
|
||||
</xsd:element>
|
||||
<xsd:element name="data">
|
||||
<xsd:complexType>
|
||||
<xsd:sequence>
|
||||
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
|
||||
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
|
||||
</xsd:sequence>
|
||||
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
|
||||
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
|
||||
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
|
||||
<xsd:attribute ref="xml:space" />
|
||||
</xsd:complexType>
|
||||
</xsd:element>
|
||||
<xsd:element name="resheader">
|
||||
<xsd:complexType>
|
||||
<xsd:sequence>
|
||||
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
|
||||
</xsd:sequence>
|
||||
<xsd:attribute name="name" type="xsd:string" use="required" />
|
||||
</xsd:complexType>
|
||||
</xsd:element>
|
||||
</xsd:choice>
|
||||
</xsd:complexType>
|
||||
</xsd:element>
|
||||
</xsd:schema>
|
||||
<resheader name="resmimetype">
|
||||
<value>text/microsoft-resx</value>
|
||||
</resheader>
|
||||
<resheader name="version">
|
||||
<value>2.0</value>
|
||||
</resheader>
|
||||
<resheader name="reader">
|
||||
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
|
||||
</resheader>
|
||||
<resheader name="writer">
|
||||
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
|
||||
</resheader>
|
||||
</root>
|
||||
@@ -0,0 +1,188 @@
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.ComponentModel;
|
||||
using System.Drawing;
|
||||
using System.Data;
|
||||
using System.Windows.Forms;
|
||||
|
||||
namespace BCG
|
||||
{
|
||||
/// <summary>
|
||||
/// 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)
|
||||
/// </summary>
|
||||
public class SpreadPositionGUI : System.Windows.Forms.UserControl
|
||||
{
|
||||
private BCG.ValueEntryGUI myValueEntryGUI;
|
||||
/// <summary>
|
||||
/// Required designer variable.
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Clean up any resources being used.
|
||||
/// </summary>
|
||||
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
|
||||
/// <summary>
|
||||
/// Required method for Designer support - do not modify
|
||||
/// the contents of this method with the code editor.
|
||||
/// </summary>
|
||||
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
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<root>
|
||||
<!--
|
||||
Microsoft ResX Schema
|
||||
|
||||
Version 1.3
|
||||
|
||||
The primary goals of this format is to allow a simple XML format
|
||||
that is mostly human readable. The generation and parsing of the
|
||||
various data types are done through the TypeConverter classes
|
||||
associated with the data types.
|
||||
|
||||
Example:
|
||||
|
||||
... ado.net/XML headers & schema ...
|
||||
<resheader name="resmimetype">text/microsoft-resx</resheader>
|
||||
<resheader name="version">1.3</resheader>
|
||||
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
|
||||
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
|
||||
<data name="Name1">this is my long string</data>
|
||||
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
|
||||
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
|
||||
[base64 mime encoded serialized .NET Framework object]
|
||||
</data>
|
||||
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
|
||||
[base64 mime encoded string representing a byte array form of the .NET Framework object]
|
||||
</data>
|
||||
|
||||
There are any number of "resheader" rows that contain simple
|
||||
name/value pairs.
|
||||
|
||||
Each data row contains a name, and value. The row also contains a
|
||||
type or mimetype. Type corresponds to a .NET class that support
|
||||
text/value conversion through the TypeConverter architecture.
|
||||
Classes that don't support this are serialized and stored with the
|
||||
mimetype set.
|
||||
|
||||
The mimetype is used forserialized objects, and tells the
|
||||
ResXResourceReader how to depersist the object. This is currently not
|
||||
extensible. For a given mimetype the value must be set accordingly:
|
||||
|
||||
Note - application/x-microsoft.net.object.binary.base64 is the format
|
||||
that the ResXResourceWriter will generate, however the reader can
|
||||
read any of the formats listed below.
|
||||
|
||||
mimetype: application/x-microsoft.net.object.binary.base64
|
||||
value : The object must be serialized with
|
||||
: System.Serialization.Formatters.Binary.BinaryFormatter
|
||||
: and then encoded with base64 encoding.
|
||||
|
||||
mimetype: application/x-microsoft.net.object.soap.base64
|
||||
value : The object must be serialized with
|
||||
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
|
||||
: and then encoded with base64 encoding.
|
||||
|
||||
mimetype: application/x-microsoft.net.object.bytearray.base64
|
||||
value : The object must be serialized into a byte array
|
||||
: using a System.ComponentModel.TypeConverter
|
||||
: and then encoded with base64 encoding.
|
||||
-->
|
||||
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
|
||||
<xsd:element name="root" msdata:IsDataSet="true">
|
||||
<xsd:complexType>
|
||||
<xsd:choice maxOccurs="unbounded">
|
||||
<xsd:element name="data">
|
||||
<xsd:complexType>
|
||||
<xsd:sequence>
|
||||
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
|
||||
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
|
||||
</xsd:sequence>
|
||||
<xsd:attribute name="name" type="xsd:string" msdata:Ordinal="1" />
|
||||
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
|
||||
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
|
||||
</xsd:complexType>
|
||||
</xsd:element>
|
||||
<xsd:element name="resheader">
|
||||
<xsd:complexType>
|
||||
<xsd:sequence>
|
||||
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
|
||||
</xsd:sequence>
|
||||
<xsd:attribute name="name" type="xsd:string" use="required" />
|
||||
</xsd:complexType>
|
||||
</xsd:element>
|
||||
</xsd:choice>
|
||||
</xsd:complexType>
|
||||
</xsd:element>
|
||||
</xsd:schema>
|
||||
<resheader name="resmimetype">
|
||||
<value>text/microsoft-resx</value>
|
||||
</resheader>
|
||||
<resheader name="version">
|
||||
<value>1.3</value>
|
||||
</resheader>
|
||||
<resheader name="reader">
|
||||
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
|
||||
</resheader>
|
||||
<resheader name="writer">
|
||||
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
|
||||
</resheader>
|
||||
<data name="myValueEntryGUI.Locked" type="System.Boolean, mscorlib, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
|
||||
<value>False</value>
|
||||
</data>
|
||||
<data name="myValueEntryGUI.DefaultModifiers" type="System.CodeDom.MemberAttributes, System, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
|
||||
<value>Private</value>
|
||||
</data>
|
||||
<data name="myValueEntryGUI.Modifiers" type="System.CodeDom.MemberAttributes, System, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
|
||||
<value>Private</value>
|
||||
</data>
|
||||
<data name="$this.TrayLargeIcon" type="System.Boolean, mscorlib, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
|
||||
<value>False</value>
|
||||
</data>
|
||||
<data name="$this.Locked" type="System.Boolean, mscorlib, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
|
||||
<value>False</value>
|
||||
</data>
|
||||
<data name="$this.SnapToGrid" type="System.Boolean, mscorlib, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
|
||||
<value>True</value>
|
||||
</data>
|
||||
<data name="$this.DrawGrid" type="System.Boolean, mscorlib, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
|
||||
<value>True</value>
|
||||
</data>
|
||||
<data name="$this.TrayHeight" type="System.Int32, mscorlib, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
|
||||
<value>80</value>
|
||||
</data>
|
||||
<data name="$this.Language" type="System.Globalization.CultureInfo, mscorlib, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
|
||||
<value>(Default)</value>
|
||||
</data>
|
||||
<data name="$this.Localizable" type="System.Boolean, mscorlib, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
|
||||
<value>False</value>
|
||||
</data>
|
||||
<data name="$this.DefaultModifiers" type="System.CodeDom.MemberAttributes, System, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
|
||||
<value>Private</value>
|
||||
</data>
|
||||
<data name="$this.Name">
|
||||
<value>SpreadPositionGUI</value>
|
||||
</data>
|
||||
<data name="$this.GridSize" type="System.Drawing.Size, System.Drawing, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
|
||||
<value>8, 8</value>
|
||||
</data>
|
||||
</root>
|
||||
@@ -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<string, Dictionary<double, CacheEntry>> _cached_data = new Dictionary<string, Dictionary<double, CacheEntry>>();
|
||||
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<double> to_clean = new List<double>();
|
||||
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<double, CacheEntry> val_to_string;
|
||||
if (!_cached_data.TryGetValue(theo_type, out val_to_string)) {
|
||||
val_to_string = new Dictionary<double, CacheEntry>();
|
||||
_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
|
||||
}
|
||||
}
|
||||
Loaded 100 of 195 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user