using mbts; using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using FutureLeg = System.Tuple; namespace bts.api { static class SecurityFormatter { static readonly ConcurrentDictionary _formatted_name_cache = new ConcurrentDictionary(); public static IEnumerable Parse(string str) { return str.Split('/').Select(a => { var part_args = a.Split(new[] { ':' }, StringSplitOptions.RemoveEmptyEntries); if (part_args[0].Length != 1) throw new ArgumentException($"Invalid formatting string '{str}'.", "str"); return new PartFormattingTuple(_get_part(part_args[0][0]), part_args.Length == 2 ? part_args[1] : null); }).ToList(); } public static string Format(SecurityImmutable s, IEnumerable parts) { var key = new SecurityFormattingKey(s.Id, parts); string formatted_security_name = string.Empty; if (_formatted_name_cache.TryGetValue(key, out formatted_security_name)) return formatted_security_name; else { var part_formatters = parts.Select(p => PartFormatterFactory.get_formatter(p)).ToList(); switch (s.ContractCase) { case Security.ContractOneofCase.Future: formatted_security_name = _format_future(s, part_formatters); break; case Security.ContractOneofCase.Spread: if (s.Glbx != null && s.Glbx.SecurityDesc.Contains(":")) { try { formatted_security_name = GlbxSecurityFormatter.FormatSpread(s); break; } catch (Exception) { goto default; } } else { goto default; } default: if (part_formatters.Count > 0 && part_formatters[0].separator == "!") { if (part_formatters[0].add_part(s, out formatted_security_name)) { break; } } formatted_security_name = string.Join("", SecurityHelper.get_flat_future_legs(s).Select(flt => _format_future_leg(flt, part_formatters))); break; } _formatted_name_cache.TryAdd(key, formatted_security_name); return formatted_security_name; } } public enum ContractParts { Name, Exchange, Symbol, Quantity, MappedExp, RawExp } class SecurityFormattingKey : IEquatable { readonly uint _security; readonly PartFormattingTuple[] _parts; public SecurityFormattingKey(uint security, IEnumerable parts) { _security = security; _parts = parts.ToList().ToArray(); } public bool Equals(SecurityFormattingKey other) => other != null && other._security == _security && other._parts.SequenceEqual(_parts); public override bool Equals(object obj) => Equals(obj as SecurityFormattingKey); public override int GetHashCode() => _security.GetHashCode() ^ _parts.GetHashCode(); } public class PartFormattingTuple : IEquatable { public readonly ContractParts Part; public readonly string Argument; public PartFormattingTuple(ContractParts part, string argument = null) { Part = part; Argument = argument; } public bool Equals(PartFormattingTuple other) => other != null && other.Part == Part && other.Argument == Argument; public override bool Equals(object obj) => Equals(obj as PartFormattingTuple); public override int GetHashCode() => Argument == null ? Part.GetHashCode() : Part.GetHashCode() ^ Argument.GetHashCode(); } #region Private Members private static ContractParts _get_part(char c) { switch(c) { case 'n': return ContractParts.Name; case 'e': return ContractParts.Exchange; case 's': return ContractParts.Symbol; case 'r': return ContractParts.RawExp; case 'm': return ContractParts.MappedExp; case 'q': return ContractParts.Quantity; default: throw new ArgumentException($"Unable to determine ContractPart from char '{c}'.", "c"); } } private static string _format_future(SecurityImmutable s, IEnumerable part_formatters) { return _format(s, part_formatters, _add_future); } private static string _format_future_leg(FutureLeg l, IEnumerable part_formatters) { return _format(l, part_formatters, _add_future_leg); } private delegate bool AddPart(T t, IPartFormatter part_formatter, out string result); private static bool _add_future(SecurityImmutable s, IPartFormatter part_formatter, out string result) { return part_formatter.add_part(s, out result); } private static bool _add_future_leg(FutureLeg l, IPartFormatter part_formatter, out string result) { return part_formatter.add_part(l, out result); } private static string _format(T t, IEnumerable part_formatters, AddPart add_part) { var adds = new List>(); foreach (var pf in part_formatters) { string p; if(add_part(t, pf, out p)) adds.Add(Tuple.Create(p, pf)); } string result = string.Empty; if (adds.Count > 0) { result = adds[0].Item1; for (int i = 1; i < adds.Count; i++) result += $"{adds[i-1].Item2.separator}{adds[i].Item1}"; } return result; } private interface IPartFormatter { string separator { get; } bool add_part(FutureLeg fl, out string result); bool add_part(SecurityImmutable s, out string result); } private static class PartFormatterFactory { public static IPartFormatter get_formatter(PartFormattingTuple pft) { switch (pft.Part) { case ContractParts.Name: return new NameFormatter(pft.Argument); case ContractParts.Exchange: return new Formatter(s => s.Exchange, fl => fl.Item1, pft.Argument); case ContractParts.Symbol: return new SymbolFormatter(pft.Argument); case ContractParts.MappedExp: { _parse_exp_formatting_arg(pft.Argument, out DateFormat df, out string separator); return new Formatter(s => s.Future.MappedExpDate(), fl => fl.Item3.MappedExpDate(), date => DateFormatter.Format(date, df), separator); } case ContractParts.RawExp: { _parse_exp_formatting_arg(pft.Argument, out DateFormat df, out string separator); return new Formatter(s => s.Future.RawExpDate(), fl => fl.Item3.RawExpDate(), date => DateFormatter.Format(date, df), separator); } case ContractParts.Quantity: return new QuantityFormatter(pft.Argument); default: throw new NotImplementedException(); } } private static void _parse_exp_formatting_arg(string arg, out DateFormat df, out string separator) { if (string.IsNullOrEmpty(arg)) { df = DateFormat.MonthAbvDiff2000; separator = null; } else { if (DateFormatter.TryParse(arg[0], out DateFormat result)) { df = result; separator = arg.Substring(1); } else { df = DateFormat.MonthAbvDiff2000; separator = arg; } } } private class NameFormatter : IPartFormatter { public NameFormatter(string separator) { this.separator = separator; } public string separator { get; } public bool add_part(FutureLeg fl, out string result) { result = null; return false; } public bool add_part(SecurityImmutable s, out string result) { if (s.ContractCase == Security.ContractOneofCase.Synthetic) { result = s.Synthetic.Name; return true; } else { result = null; return false; } } } private class QuantityFormatter : IPartFormatter { public QuantityFormatter(string separator) { this.separator = separator; } private bool _first_leg = true; public string separator { get; } public bool add_part(FutureLeg fl, out string result) { if (_first_leg) { if (fl.Item4 > 0) result = fl.Item4 == 1 ? string.Empty : fl.Item4.ToString(); else result = fl.Item4 == -1 ? "-" : fl.Item4.ToString("-0"); _first_leg = false; } else { if (fl.Item4 == 1) result = "+"; else if (fl.Item4 == -1) result = "-"; else result = fl.Item4.ToString("+0;-0"); } return true; } public bool add_part(SecurityImmutable s, out string result) { result = null; return false; } } private class SymbolFormatter : IPartFormatter { public SymbolFormatter(string separator) { this.separator = separator; } public string separator { get; } public bool add_part(FutureLeg fl, out string result) { result = fl.Item2; return true; } public bool add_part(SecurityImmutable s, out string result) { result = s.Symbol; return true; } } private class Formatter : IPartFormatter { public Formatter(Func get_sec_value, Func get_leg_value, string separator) : this(get_sec_value, get_leg_value, t => t.ToString(), separator) { } public Formatter(Func get_sec_value, Func get_leg_value, Func format, string separator) { _get_sec_value = get_sec_value; _get_leg_value = get_leg_value; _format = format; _separator = separator; } private readonly Func _get_sec_value; private readonly Func _get_leg_value; private readonly Func _format; private readonly string _separator; private T _last_val; public string separator => _separator ?? string.Empty; public bool add_part(SecurityImmutable s, out string result) { T val = _get_sec_value(s); if (!val.Equals(_last_val)) { result = _format(_last_val = val); return true; } else { result = null; return false; } } public bool add_part(FutureLeg fl, out string result) { T val = _get_leg_value(fl); if (!val.Equals(_last_val)) { result = _format(_last_val = val); return true; } else { result = null; return false; } } } } #endregion } }