diff --git a/src/DataStreamSuite/SharedStreams/Services/SharedStreamsServices.cs b/src/DataStreamSuite/SharedStreams/Services/SharedStreamsServices.cs index 340b7a9bd..74acc595e 100644 --- a/src/DataStreamSuite/SharedStreams/Services/SharedStreamsServices.cs +++ b/src/DataStreamSuite/SharedStreams/Services/SharedStreamsServices.cs @@ -11,6 +11,7 @@ using Microsoft.Extensions.DependencyInjection; public static class SharedStreamsServices { public static IServiceCollection AddMarketDataStreams(this IServiceCollection services) => services.addStreamFactory() + .addStreamFactory() .addStreamFactory(); public static IServiceCollection AddNaturalLanguageStreams(this IServiceCollection services, IConfigurationSection configurationSection) { diff --git a/src/DataStreamSuite/SharedStreams/StreamFactories/SpreadBookRow.cs b/src/DataStreamSuite/SharedStreams/StreamFactories/SpreadBookRow.cs new file mode 100644 index 000000000..f240c781c --- /dev/null +++ b/src/DataStreamSuite/SharedStreams/StreamFactories/SpreadBookRow.cs @@ -0,0 +1,17 @@ +namespace Bts.SharedStreams.StreamFactories; + +using bts.api; + +public readonly struct SpreadBookRow { + public SpreadBookRow(SyntheticBook book, IReadOnlyList legs) { + Book = book; + Legs = legs; + } + + public uint SecurityId => Book.SecurityId; + public string? SecurityName => string.Join(" • ", Legs.Select(l => $"{l.Quantity}{l.Name}")); + public SyntheticBook Book { get; } + public IReadOnlyList Legs { get; } + + public record Leg(Venue Venue, SecurityType Type, string Name, uint Id, double CashPerPoint, double Quantity); +} diff --git a/src/DataStreamSuite/SharedStreams/StreamFactories/SpreadBookSchemaBuilder.cs b/src/DataStreamSuite/SharedStreams/StreamFactories/SpreadBookSchemaBuilder.cs new file mode 100644 index 000000000..177e7c4ae --- /dev/null +++ b/src/DataStreamSuite/SharedStreams/StreamFactories/SpreadBookSchemaBuilder.cs @@ -0,0 +1,78 @@ +namespace Bts.SharedStreams.StreamFactories; + +using bts.api; +using bts.collections; + +using Bts.DataStreamCore; + +public class SpreadBookSchemaBuilder { + public int NumLegs { get; set; } = 2; + public int NumLevels { get; set; } = 3; + public bool ShowPrice { get; set; } = true; + public bool ShowQuantity { get; set; } = true; + public bool ShowNotional { get; set; } + public bool ShowVenue { get; set; } + public bool ShowAsset { get; set; } + public bool ShowSecurityName { get; set; } = true; + public bool ShowLegVenue { get; set; } + public bool ShowLegAsset { get; set; } + public bool ShowLegSecurityType { get; set; } + public bool ShowLegSecurityName { get; set; } = true; + public bool ShowLegSecurityId { get; set; } = true; + public bool ShowLegCashPerPoint { get; set; } + public bool ShowTimestamp { get; set; } = false; + public string TableName { get; set; } = "SpreadBook"; + + public BlueTableSchemaAdapter SpreadBookRowAdapter() { + var adapter = new BlueTableSchemaAdapter(TableName, r => (int)r.SecurityId); + if (ShowSecurityName) { + adapter.AddColumn(WellKnownColumns.SecurityName.Name, r => r.SecurityName); + } + if (ShowTimestamp) { + adapter.AddColumn(WellKnownColumns.Timestamp.Name, r => DateTime.MinValue); + } + for (int i = 0; i < NumLegs; i++) { + if (ShowLegVenue) { + adapter.AddColumn(WellKnownColumns.LegVenue(i).Name, r => (GetLeg(r)?.Venue)?.ToString() ?? string.Empty); + } + if (ShowLegSecurityType) { + adapter.AddColumn(WellKnownColumns.LegSecurityType(i).Name, r => (GetLeg(r)?.Type)?.ToString() ?? string.Empty); + } + if (ShowLegSecurityName) { + adapter.AddColumn(WellKnownColumns.LegSecurityName(i).Name, r => GetLeg(r)?.Name ?? string.Empty); + } + if (ShowLegSecurityId) { + adapter.AddColumn(WellKnownColumns.LegSecurityId(i).Name, r => GetLeg(r)?.Id ?? 0); + } + if (ShowLegCashPerPoint) { + adapter.AddColumn(WellKnownColumns.LegCashPerPoint(i).Name, r => GetLeg(r)?.CashPerPoint ?? 1); + } + + SpreadBookRow.Leg? GetLeg(SpreadBookRow r) => + r.Legs.as_mutable().TryGetAt(i, out var l) ? l : null; + } + foreach (var side in new[] { Side.Buy, Side.Sell }) { + for (int i = 0; i < NumLevels; i++) { + if (ShowPrice) { + adapter.AddColumn(WellKnownColumns.DepthPrice(side, i).Name, priceGetter(side, i)); + } + if (ShowQuantity) { + adapter.AddColumn(WellKnownColumns.DepthQuantity(side, i).Name, quantityGetter(side, i)); + } + if (ShowNotional) { + adapter.AddColumn(WellKnownColumns.DepthNotional(side, i).Name, notionalGetter(side, i)); + } + } + } + return adapter; + + static Func priceGetter(Side side, int level) => + b => b.Book[side, level].Price; + + static Func quantityGetter(Side side, int level) => + b => b.Book[side, level].Quantity; + + static Func notionalGetter(Side side, int level) => + b => b.Book[side, level].NotionalValue; + } +} diff --git a/src/DataStreamSuite/SharedStreams/StreamFactories/SpreadBookStreamFactory.cs b/src/DataStreamSuite/SharedStreams/StreamFactories/SpreadBookStreamFactory.cs new file mode 100644 index 000000000..74efec747 --- /dev/null +++ b/src/DataStreamSuite/SharedStreams/StreamFactories/SpreadBookStreamFactory.cs @@ -0,0 +1,117 @@ +namespace Bts.SharedStreams.StreamFactories; + +using BCG; + +using bts.api; +using bts.api.core; +using bts.md; +using bts.utils; + +using Bts.DataStream; +using Bts.DataStreamCore; + +using mbts.spark; + +using Microsoft.Extensions.Logging; +using Microsoft.Scripting.Utils; + +using Spark.Api.MarketData; +using Spark.Core.Reactive; + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reactive.Linq; + +public class SpreadBookStreamFactory : IDataStreamFactory { + readonly ILogger logger; + readonly MarketDataClient? mdClient; + + public SpreadBookStreamFactory(ILogger logger) + : this(null, logger) { } + + public SpreadBookStreamFactory(MarketDataClient? mdClient, ILogger logger) { + this.logger = logger; + this.mdClient = mdClient; + } + + public IObservable>? CreateLiveSpreadBookTables(SpreadBookStreamParams args) { + if (mdClient is null) { + throw new InvalidOperationException("Live md not available"); + } + var secDefs = args.Legs.ToList(); + var calcDataSource = mdClient.securities_incremental(IncludeSec).Select(upd => { + var legs = new List<(SecurityImmutable Sec, double Qty)>(); + foreach (var sd in secDefs) { + if (upd.state.Values.TryGetFirst(IsMatch, out var sec)) { + legs.Add((sec, sd.Quantity)); + } + + bool IsMatch(SecurityImmutable sec) => + sd.Name == sec.ToString() && (!sd.Type.HasValue || sd.Type == SecurityType.Unset || sd.Type.Value == sec.security_type()) && sd.Venue == sec.Exchange; + } + return legs; + }); + return calcDataSource.SelectSeries(legs => createSpreadBook(legs, mdClient.books(IncludeSec))) + .Scan( + TableUpdate.mk_empty(r => (int)r.SecurityId), + (lastOut, bk) => lastOut.state.Count == 0 + ? lastOut.with_added(new[] { bk }) + : lastOut.with_changed(new[] { bk })); + + bool IncludeSec(SecurityImmutable s) => + secDefs.Any(leg => + leg.Venue == s.Exchange + && (!leg.Type.HasValue || leg.Type == SecurityType.Unset || leg.Type.Value == s.security_type()) + && leg.Name == s.ToString()); + } + + public IObservable? CreateSpreadBookStream(SpreadBookStreamParams streamParams) => + CreateLiveSpreadBookTables(streamParams)?.AsDataPackets(streamParams.GetSchemaBuilder().SpreadBookRowAdapter()); + + public ViewStream? Create(string streamId, IEnumerable<(string? Name, int? Index, object? Value)> args) { + if (SupportedStreams.SpreadBook.IsMatch(streamId)) { + return createSpreadBook(args); + } + return null; + } + + public IEnumerable GetSupportedStreams() { + yield return SupportedStreams.SpreadBook; + } + + static IObservable createSpreadBook( + List<(SecurityImmutable Sec, double Qty)> legs, IObservable> books) { + var synthLegs = legs.Select(l => new SpreadBookRow.Leg( + l.Sec.Exchange, l.Sec.security_type(), l.Sec.ToString() ?? string.Empty, l.Sec.Id, l.Sec.ContractSpec.CashPerPoint, l.Qty)) + .ToList(); + return Observable.Create(o => { + return books.Subscribe(OnBooks); + + void OnBooks(TableUpdate upd) { + var synthBook = SyntheticBookCalculator.GetSyntheticNotionalBook( + 0, legs.Select(l => (l.Qty, l.Sec.ContractSpec.ticksize(0), l.Sec.ContractSpec.CashPerPoint, GetLegBook(l.Sec.Id)))); + var row = new SpreadBookRow(new(0, synthBook.Bids, synthBook.Asks), synthLegs); + o.OnNext(row); + + Book GetLegBook(uint secId) => + upd.state.TryGetValue(secId, out var bk) ? bk.book : Book.empty(secId); + } + }); + } + + ViewStream? createSpreadBook(IEnumerable<(string? Name, int? Index, object? Value)> args) { + if (!StreamFactoryArgStore.TryGetParams(args, out SpreadBookStreamParams? streamParams, out var err)) { + logger.LogInvalidParams("spreadBook", err); + return null; + } + return CreateSpreadBookStream(streamParams)?.AsViewStream(); + } + + static class SupportedStreams { + public static readonly DataStreamMetadata SpreadBook = new() { + Name = "spreadBook", + AlternateNames = new() { "synthBook" }, + }; + } +} diff --git a/src/DataStreamSuite/SharedStreams/StreamFactories/SpreadBookStreamParams.cs b/src/DataStreamSuite/SharedStreams/StreamFactories/SpreadBookStreamParams.cs new file mode 100644 index 000000000..9e1fbd3c7 --- /dev/null +++ b/src/DataStreamSuite/SharedStreams/StreamFactories/SpreadBookStreamParams.cs @@ -0,0 +1,93 @@ +namespace Bts.SharedStreams.StreamFactories; + +using bts.api; + +using Bts.DataStreamCore; + +using System.Diagnostics.CodeAnalysis; + +public class SpreadBookStreamParams { + [StreamArgument("venue1", "exchange1", "exch1", "ex1", "e1", IsRequired = true)] + public Venue? Venue1 { get; set; } + + [StreamArgument("type1", "typ1", IsRequired = false)] + public SecurityType? SecurityType1 { get; set; } + + [StreamArgument("sec1", "name1", IsRequired = true)] + public string? SecurityName1 { get; set; } + + [StreamArgument("qty1", "quantity1", "q1", "size1", "sz1", IsRequired = true)] + public double? Quantity1 { get; set; } + + [StreamArgument("venue2", "exchange2", "exch2", "ex2", "e2", IsRequired = true)] + public Venue? Venue2 { get; set; } + + [StreamArgument("type2", "typ2", IsRequired = false)] + public SecurityType? SecurityType2 { get; set; } + + [StreamArgument("sec2", "name2", IsRequired = true)] + public string? SecurityName2 { get; set; } + + [StreamArgument("qty2", "quantity2", "q2", "size2", "sz2", IsRequired = true)] + public double? Quantity2 { get; set; } + + [StreamArgument("price", "px", "p", "showPrice", "showPx", "showP")] + public bool ShowPrice { get; set; } = true; + + [StreamArgument("quantity", "qty", "q", "showQuantity", "showQty", "showQ")] + public bool ShowQuantity { get; set; } = true; + + [StreamArgument("notional", "notl", "showNotl", "showNotional")] + public bool ShowNotional { get; set; } + + [StreamArgument("cpp", "cashPerPoint", "showCpp", "showCashPerPoint")] + public bool ShowCashPerPoint { get; set; } = true; + + [StreamArgument("numLevels", "n", "count", "levels")] + public int NumLevels { get; set; } = 3; + + public IEnumerable<(Venue Venue, SecurityType? Type, string Name, double Quantity)> Legs { + get { + yield return (Venue1 ?? Venue.Unset, SecurityType1 ?? SecurityType.Unset, SecurityName1 ?? string.Empty, Quantity1 ?? double.NaN); + yield return (Venue2 ?? Venue.Unset, SecurityType2 ?? SecurityType.Unset, SecurityName2 ?? string.Empty, Quantity2 ?? double.NaN); + } + } + + public SpreadBookSchemaBuilder GetSchemaBuilder() => + new() { + NumLevels = NumLevels, + ShowLegVenue = true, + ShowLegSecurityType = true, + ShowAsset = false, + ShowLegSecurityName = false, + ShowSecurityName = true, + ShowLegSecurityId = false, + ShowPrice = ShowPrice, + ShowQuantity = ShowQuantity, + ShowNotional = ShowNotional, + ShowLegCashPerPoint = ShowCashPerPoint, + }; + + [MemberNotNull(nameof(Venue1), nameof(SecurityName1), nameof(Quantity1), nameof(Venue2), nameof(SecurityName2), nameof(Quantity2))] + public SpreadBookStreamParams Validate() { + if (!Venue1.HasValue) { + throw new InvalidOperationException("Venue1 is null"); + } + if (SecurityName1 is null) { + throw new InvalidOperationException("Name1 is null"); + } + if (!Quantity1.HasValue) { + throw new InvalidOperationException("Quantity1 is null"); + } + if (!Venue2.HasValue) { + throw new InvalidOperationException("Venue2 is null"); + } + if (SecurityName2 is null) { + throw new InvalidOperationException("Name2 is null"); + } + if (!Quantity2.HasValue) { + throw new InvalidOperationException("Quantity2 is null"); + } + return this; + } +}