#nullable enable namespace Spark.Core.Data { using bts; using bts.api; using bts.api.domain; using bts.collections; using mbts; using mbts.config; using mbts.spark; using System; using System.Collections.Generic; using System.Linq; public class SecurityMetadataStore { [ThreadStatic] static ISecurityMetadataStore? _configured_store_backing; static ISecurityMetadataStore _configured_store => _configured_store_backing ??= new Impl(Configuration.get()); public static ISecurityMetadataStore instance { get; } = new ConfiguredInstanceWrapper(); class ConfiguredInstanceWrapper : ISecurityMetadataStore { public SecurityMetadataImmutable? get(SecurityImmutable security) => _configured_store.get(security); } class Impl : ISecurityMetadataStore { readonly SecurityMetadataCollection _security_metadata; readonly Dictionary _cache = new(); readonly bool _get_price_ticks_from_sec; public Impl( SecurityMetadataCollection security_metadata, bool get_price_ticks_from_sec = true) { _security_metadata = security_metadata; _get_price_ticks_from_sec = get_price_ticks_from_sec; } public SecurityMetadataImmutable? get(SecurityImmutable sec) { return _cache.GetOrAdd(sec.Id, _ => { /// Since doesn't distinguish opt/fut spreads, it /// isn't possible to configure different metadata for them. As a workaround, use /// metadata associated with the first leg's security to achieve desired behavior /// (e.g., apply Deribit BTC Option qty tick settings to Deribit BTC Option Spreads). var normalized_legs = new ContractLegEnumerable(sec); if (!normalized_legs.Select(l => l.Security).TryGetFirst(out var outright)) { return null; } if (!_security_metadata.Items.TryGetFirst(item => item is not null && item.Scope.to_criteria().includes(outright), out var raw_meta)) { return null; } // Can't possibly be null (the delegate above already checked for this) raw_meta = Log.notnull(raw_meta); var meta = convert_raw_metadata(raw_meta); if (sec.ContractCase == Security.ContractOneofCase.Spread && meta.HasValue && meta.Value.PriceRules.AtLeast(2)) { // This is a hack to force Deribit Combos to have uniform ticks var rules = meta.Value.PriceRules .Where(r => r.HasTickDisplay && r.TickDisplay.HasTickFactors); if (rules.TryGetMinElement( r => r.TickDisplay.TickFactors.tick_unit_frac(), out var min_tick_rule)) { var mutable_meta = meta.Value.CloneToMutable(); mutable_meta.PriceRules.SetItems(new[] { min_tick_rule.CloneToMutable() }); meta = mutable_meta.immutable(); } } return meta; }); SecurityMetadataImmutable? convert_raw_metadata(SecurityMetadataItem raw_meta) { if (!_get_price_ticks_from_sec) { return new(raw_meta.Value); } /// Don't mutate the actual object stored in var meta = raw_meta.Value.Clone(); meta.PriceDisplay ??= Security.Defaults.price_display_settings; // meta.PriceDisplay.TickFactors = sec.spec_or_default() // .tick_factors().to_api_tick_factorsi().CloneToMutable(); return new(meta); } } } } }