namespace Bts.SharedStreams.StreamFactories; using BCG; using bts.api; using Microsoft.Extensions.Logging; using Spark.Core; using System.Diagnostics.CodeAnalysis; using System.Reflection; using System.Text; using System.Text.RegularExpressions; class StreamFactoryArgStore { readonly IEnumerable<(string? Name, int? Index, object? Value)> args; readonly ILogger? logger; readonly string streamType; public StreamFactoryArgStore(IEnumerable<(string? Name, int? Index, object? Value)> args, string? streamType = null, ILogger? logger = null) { this.args = args; this.streamType = streamType ?? "anonStream"; this.logger = logger; } public static bool TryGetParams( IEnumerable<(string? Name, int? Index, object? Value)> args, [MaybeNull][NotNullWhen(true)] out T result, [NotNullWhen(false)] out string? errorMessage ) => new StreamFactoryArgStore(args).TryGetParams(out result, out errorMessage); public bool TryGetParams([MaybeNull][NotNullWhen(true)] out T result, [NotNullWhen(false)] out string? errorMessage) { var props = typeof(T).GetProperties(); var res = Activator.CreateInstance(); if (res is null) { errorMessage = $"Failed to instantiate {typeof(T)}"; result = default; return false; } foreach (var p in props) { var att = p.GetCustomAttribute(); IEnumerable names = att?.Names ?? new[] { p.Name }; if (att?.AllowCommaSeparatedAliases ?? false) { names = names.SelectMany(n => n.Split(',')); } IEnumerable regexNames = att?.RegexNames ?? Enumerable.Empty(); if (TryGet(names, out var val) || TryGetRegex(regexNames, out val)) { SetValue(val); } else if (att is not null && att.Position >= 0 && args.Skip(att.Position).TryGetFirst(out var arg)) { SetValue(arg.Value); } else if (att?.IsRequired ?? false) { errorMessage = $"Missing required param '{p.Name}'"; result = default; return false; } void SetValue(object? val) { var pType = p.PropertyType; bool isNullable = pType.IsNullable(); if (isNullable) { pType = pType.GetGenericArguments().Single(); } if (pType == typeof(DateTime)) { SetValueType(BlueDataUtility.GetDateTime(val)); } else if (pType == typeof(TimeSpan)) { SetValueType(BlueDataUtility.GetTimeSpan(val)); } else if (pType == typeof(string)) { p.SetValue(res, val as string ?? val?.ToString()); } else if (pType.IsEnum) { p.SetValue(res, BlueDataUtility.GetEnum(pType, val)); } else if (val?.GetType() == pType || (val is null && (!pType.IsValueType || isNullable))) { p.SetValue(res, val); } else { p.SetValue(res, Convert.ChangeType(val, pType)); } void SetValueType(TProp? pVal) where TProp : struct { if (isNullable) { p.SetValue(res, pVal); } else { p.SetValue(res, pVal.assert_value()); } } } } errorMessage = null; result = res; return true; } public Venue GetVenue(bool required = true) { var rv = GetVenue(new[] { "venue", "exchange", "exch" }); if (required && logger is not null && rv == Venue.Unset) { logger.LogMissingParam(streamType, "venue"); } return rv; } public Venue GetVenue(string[] preferredNames) { return preferredNames .Select(n => Get(n)) .Concat(args.Select(a => a.Value)) .Select(ConvertObj) .SelectWhereValues() .FirstOrDefault(Venue.Unset); static Venue? ConvertObj(object? obj) { if (obj is Venue res) { return res; } var str = obj as string ?? obj?.ToString(); if (tryParseVenue(str, out res)) { return res; } return null; } } public string? GetVenueString(bool required = true) => GetVenueString(required, "venue", "exchange", "exch"); public bool GetVenueString([NotNullWhen(true)] out string? venue, bool required = true) { venue = GetVenueString(required, "venue", "exchange", "exch"); return venue is not null; } public string? GetVenueString(bool required, params string[] preferredNames) { var obj = Get(preferredNames); var str = obj as string ?? obj?.ToString(); str = str?.ToUpper()?.Replace("VENUE_", ""); if (required && logger is not null && string.IsNullOrEmpty(str)) { logger.LogMissingParam(streamType, "venue"); } return str; } public SecurityType GetSecurityType() => GetSecurityType(new[] { "secType", "securityType", "type" }); public SecurityType GetSecurityType(params string[] preferredNames) { return preferredNames .Select(n => Get(n)) .Concat(args.Select(a => a.Value)) .Select(ConvertObj) .SelectWhereValues() .FirstOrDefault(SecurityType.Unset); static SecurityType? ConvertObj(object? obj) { if (obj is SecurityType res) { return res; } var str = obj as string ?? obj?.ToString(); if (tryParseSecurityType(str, out res)) { return res; } return null; } } public bool GetSymbol([NotNullWhen(true)] out string? symbol, bool required = true) { symbol = GetSymbol(required); return symbol is not null; } public string? GetSymbol(bool required = true) { var rv = Get("symbol", "product", "productCode", "asset")?.ToString(); if (required && logger is not null && string.IsNullOrEmpty(rv)) { logger.LogMissingParam(streamType, "symbol"); } return rv; } public bool GetInt32(string name, [NotNullWhen(true)] out int? result) => GetInt32(out result, true, name); public bool GetInt32([NotNullWhen(true)] out int? result, bool required, params string[] names) { result = GetInt32(names); return result.HasValue; } public int? GetInt32(params string[] names) => GetInt32(true, names); public int? GetInt32(bool required, params string[] names) { if (names.Length == 0) { return null; } var obj = Get(names); if (obj is int i) { return i; } var s = obj as string ?? obj?.ToString(); if (int.TryParse(s, out i)) { return i; } if (required && logger is not null) { logger.LogMissingParam(streamType, names[0]); } return null; } public bool GetTimeSpan(string name, out TimeSpan? result) { result = GetTimeSpan(true, new[] { name }); return result.HasValue; } public TimeSpan? GetTimeSpan(string name) => GetTimeSpan(true, new[] { name }); public TimeSpan? GetTimeSpan(bool required, string[] preferredNames) => preferredNames .Select(n => BlueDataUtility.GetTimeSpan(Get(n))) .Where(ts => ts.HasValue) .FirstOrDefault(); public IEnumerable GetStrings() => args.Select(a => a.Value).OfType(); // First, parses the args associated with preferredNames and returns the first successful // parse result. If none were successful, tries to parse every arg. public T? GetEnum(params string[] preferredNames) where T : struct { var candidateObjs = preferredNames.Select(n => Get(n)).Concat(args.Select(a => a.Value)); foreach (var obj in candidateObjs) { if (obj is T res) { return res; } if (obj is string s && Enum.TryParse(s, true, out res)) { return res; } } return null; } public IEnumerable GetDateTimes() => args.Select(a => convertToDateTime(a.Value)).SelectWhereValues(); public bool GetDateTime(string name, [NotNullWhen(true)] out DateTime? result) { result = GetDateTime(true, name); return result.HasValue; } public bool GetDateTime([NotNullWhen(true)] out DateTime? result, params string[] names) { result = GetDateTime(names); return result.HasValue; } public DateTime? GetDateTime(params string[] names) => GetDateTime(true, names); public DateTime? GetDateTime(bool required, params string[] names) => names.Select(n => Get(n)).Select(convertToDateTime).Where(dt => dt.HasValue).FirstOrDefault(); public object? Get(params string[] names) => Get(true, names); public object? Get(bool required, params string[] names) { if (names.Length == 0) { return null; } if (!TryGet(names, out var result) && required && logger is not null) { logger.LogMissingParam(streamType, names[0]); } return result; } public bool TryGet(string name, out object? result) => TryGet(new[] { name }, out result); public bool TryGetRegex(string name, out object? result) => TryGet(new[] { name }, out result, checkDefaultMatch: false, checkRegexMatch: true); public bool TryGetRegex(IEnumerable names, out object? result) => TryGet(names, out result, checkDefaultMatch: false, checkRegexMatch: true); public bool TryGet(IEnumerable names, out object? result, bool checkDefaultMatch = true, bool checkRegexMatch = false) { if (checkDefaultMatch) { foreach (var name in names.SelectMany(Variants)) { if (args.TryGetFirst(a => a.Name == name, out var a)) { result = a.Value; return true; } } } if (checkRegexMatch) { foreach (var name in names) { if (args.TryGetFirst(a => Regex.IsMatch(a.Name ?? string.Empty, name), out var a)) { result = a.Value; return true; } } } result = null; return false; IEnumerable Variants(string s) { if (string.IsNullOrEmpty(s)) { yield break; } yield return s; // Convert to snake_case var bd = new StringBuilder(char.ToLower(s[0])); for (int i = 1; i < s.Length; i++) { if (i > 1 && char.IsUpper(s[i]) && char.IsLower(s[i - 1])) { bd.Append('_'); } bd.Append(char.ToLower(s[i])); } yield return bd.ToString(); // Convert to camelCase bd.Clear(); for (int i = 0; i < s.Length; i++) { int numUnderscores = 0; while (s[i + numUnderscores] == '_' & (i + numUnderscores < s.Length)) { numUnderscores++; } if (numUnderscores > 0) { i += numUnderscores; if (i >= s.Length) { break; } bd.Append(char.ToUpper(s[i])); } else { bd.Append(s[i]); } } yield return bd.ToString(); } } static bool tryParseVenue(string? str, out Venue v) { if (str is null) { v = Venue.Unset; return false; } if (Enum.TryParse(str, true, out v) || Enum.TryParse("VENUE_" + str, true, out v)) { return true; } v = str.ToUpper() switch { "CME" or "XCME" or "CEC" or "XCEC" => Venue.Glbx, "CBOT" or "CBT" or "XCBT" => Venue.Cboe, _ => Venue.Unset, }; return v != Venue.Unset; } static bool tryParseSecurityType(string? str, out SecurityType t) { if (str is null) { // bbo(symbol: "ZN", venue: "GLBX", begin: "2024-10-03T18:00:00-00:05", end: "2024-10-03T19:00:00-00:05", interval: "PT1S") t = SecurityType.Unset; return false; } return Enum.TryParse(str, true, out t) || Enum.TryParse("SECURITYTYPE_" + str, true, out t); } static DateTime? convertToDateTime(object? obj) => tryConvert(obj, out DateTime dt) ? dt : null; static bool tryConvert(object? obj, out DateTime res) { if (obj is DateTime dt) { res = dt; return true; } if (obj is string s) { // if (OffsetDateTimePattern) if (DateTimeOffset.TryParseExact(s, "yyyy-MM-ddTHH:mm:ssK", null, System.Globalization.DateTimeStyles.None, out var dto)) { res = dto.ToUniversalTime().DateTime; return true; } if (DateTimeOffset.TryParseExact(s, "yyyy-MM-ddTHH:mm:ss.fffffffffK", null, System.Globalization.DateTimeStyles.None, out dto)) { res = dto.ToUniversalTime().DateTime; return true; } if (DateTime.TryParse(s, null, System.Globalization.DateTimeStyles.RoundtripKind, out res)) { return true; } if (DateTimeOffset.TryParse(s, out var resOff)) { res = resOff.ToUniversalTime().DateTime; return true; } return DateTime.TryParse(s, out res); } res = default; return false; } }