Files
spark/src/client/spark_api/MarketData/MarketDataClient.cs
T

212 lines
8.8 KiB
C#

#nullable enable
namespace Spark.Api.Services;
using bts;
using bts.api;
using bts.api.core;
using bts.co2;
using bts.collections;
using mbts;
using mbts.co2;
using mbts.spark;
using Microsoft.Extensions.Options;
using Spark.Api.MarketData;
using Spark.Core.Disposables;
using Spark.Core.Reactive;
using Spark.Core.Services;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Reactive.Linq;
using System.Reactive.Subjects;
using System.Threading;
using System.Threading.Tasks;
public class MarketDataClient : IMarketDataClient {
readonly ISubject<MDConsumer> mdConsumerSrc = new ReplaySubject<MDConsumer>(1);
readonly IObservable<ConcurrentDictionary<uint, SecurityMD>> securitiesSrc;
readonly List<IDisposable> _resources = new();
readonly MarketDataConfig config;
// The Co2RelayControl manages the grpc subscription to md under the hood (in c++).
// Even though it's not directly used by this class, we store it in a member var to
// keep the subscription alive.
Co2RelayControl? relay;
volatile bool isDisposed;
public MarketDataClient(ISparkConfigLoader configLoader, ISparkdLoginService loginService, IUserDataPermissions userDataPermissions, IOptions<MarketDataConfig> config)
: this(configLoader, loginService, userDataPermissions, config.Value) { }
public MarketDataClient(ISparkConfigLoader configLoader, ISparkdLoginService loginService, IUserDataPermissions userDataPermissions, MarketDataConfig config) {
this.config = config;
_resources.Add(mdConsumerSrc
.CombineLatest(Observable.FromAsync(() => loginService.LoginAsync().AsTask()))
.Subscribe(tup => {
var (consumer, loginRes) = tup;
Log.notnull(loginRes.Token);
var relay = new Co2RelayControl(consumer, config.RelayThrottle);
relay.preload_securities((MDRequest.Types.Flags)0xff).ignore();
relay.set_token(loginRes.Token.Value);
this.relay = relay;
}));
securitiesSrc = mdConsumerSrc
.SelectSeries(consumer => Log.notnull(consumer.on_security)
.Buffer(config.SecurityPollInterval)
.Select(buffer => buffer.SelectMany(_ => _).Where(SecFilter))
.Where(buffer => buffer.Any())
.Scan(
new ConcurrentDictionary<uint, SecurityMD>(),
(cache, new_secs) => {
foreach (var sec in new_secs) {
var sec_md = new SecurityMD(new(sec.security), sec.handle);
cache.AddOrUpdate(sec.security.Id, sec_md, (_, _) => sec_md);
}
return cache;
}))
.Replay(1)
.ToObservable();
// Log md errors
_resources.Add(securitiesSrc.Subscribe(_ => { }, e => Log.Md.error(e.ToString())));
// Init the consumer in background. Once it's ready, md will start flowing.
Task.Run(InitConsumer).ignore();
bool SecFilter(SecurityAndHandle sec) =>
sec.security.ContractCase != Security.ContractOneofCase.Synthetic ||
userDataPermissions.Allow(sec.security.Synthetic.UserId);
void InitConsumer() {
// Wait until config has been loaded before creating the MDConsumer (otherwise it
// loads the default symbols, instead of those from the config server).
var configTask = configLoader.InitializeAsync(CancellationToken.None);
var lastLogTime = DateTime.MinValue;
var logInterval = TimeSpan.FromSeconds(1);
var stopwatch = Stopwatch.StartNew();
for (var sw = Stopwatch.StartNew(); !configTask.IsCompleted; Thread.Sleep(100)) {
if (isDisposed) {
mdConsumerSrc.OnCompleted();
return;
}
if (stopwatch.Elapsed > logInterval) {
Log.Api.warn($"MarketDataService waiting for config");
stopwatch.Restart();
}
}
mdConsumerSrc.OnNext(new());
}
}
public IObservable<TableUpdate<SecurityImmutable, uint>> Securities(Func<SecurityImmutable, bool>? includeSecurity) {
var src = securitiesSrc.ToSelector(secMds => MappedDictionary.create(secMds, s => s.security));
if (includeSecurity is not null) {
src = src.extend(secs => new FilteredDictionary<uint, SecurityImmutable>(secs, includeSecurity));
}
return src.Table(s => s.Id);
}
public IObservable<TableUpdate<BookTuple, uint>> Books(Func<SecurityImmutable, bool>? includeSecurity) {
// This MDSource's IObservable provides callbacks when a security is added or removed, but
// doesn't detect book changes. To avoid maintaining complicated state, create a brand new
// IObservable of book updates whenever the securities change.
var filteredSecs = includeSecurity is null ?
securitiesSrc.Select(mds => mds.Values) :
securitiesSrc.Select(mds => mds.Values.Where(md => includeSecurity(md.security)));
return filteredSecs.Select(fixed_sec_market_data).FlattenTableSeries();
IObservable<TableUpdate<BookTuple, uint>> fixed_sec_market_data(
IEnumerable<SecurityMD> security_mds) {
// Convert 'security_mds' to a list of PollableBooks.
var cached_books = security_mds
.Select(s => new PollableBook(s, config.NumDepthLevels))
.ToList();
return Observable.Interval(config.HotPollInterval).Scan(
TableUpdate<BookTuple, uint>.mk_empty(GetSecId),
PollBooks);
uint GetSecId(BookTuple book) =>
book.security.Id;
TableUpdate<BookTuple, uint> PollBooks(TableUpdate<BookTuple, uint> table, long _) {
var bd = table.to_builder();
foreach (var cbook in cached_books) {
if (cbook.poll_changes()) {
bd.add_or_update(cbook.to_book_tuple());
}
}
return bd.to_table();
}
}
}
public IObservable<IList<TradeInfo>> Trades(Func<SecurityImmutable, bool>? includeSecurity) {
IObservable<IReadOnlyDictionary<uint, SecurityMD>> filteredSecs = includeSecurity is null ?
securitiesSrc :
securitiesSrc.Select(mds => new FilteredDictionary<uint, SecurityMD>(mds, md => includeSecurity(md.security)));
return mdConsumerSrc.SelectSeries(consumer => securitiesSrc.Scan(
(channels: ImmutableDictionary<ProductImmutable, ChannelConsumer>.Empty, active: new List<ChannelConsumer>(0)),
(channel_data, map) => {
var (channels, active) = channel_data;
var products = map.Values.Select(s => s.security.product()).Distinct();
active = new List<ChannelConsumer>();
foreach (var p in products) {
if (!channels.TryGetValue(p, out var c)) {
c = new ChannelConsumer(
consumer.get_channel(p.Symbol, p.Type, p.Exchange),
map.Values.Where(s => s.security.product().Equals(p)));
channels = channels.Add(p, c);
}
active.Add(c);
}
return (channels, active);
})
.SelectSeries(channel_data => {
var (channels, active) = channel_data;
return Observable.Interval(config.TradePollInterval)
.Select(_ => active.SelectMany(c => c.read_trades()).ToList())
.Where(trades => trades.Count > 0);
}));
}
public IObservable<TableUpdate<PriceStats, uint>> PriceStats(Func<SecurityImmutable, bool>? includeSecurity) {
throw new NotImplementedException();
}
public IObservable<TableUpdate<PriceTicker, uint>> PriceTicker(Func<SecurityImmutable, bool>? includeSecurity) {
throw new NotImplementedException();
}
public void Dispose() {
GC.SuppressFinalize(this);
isDisposed = true;
_resources.DisposeAll(true);
}
class ChannelConsumer {
readonly MDConsumerChannel _channel;
readonly Dictionary<uint, SecurityMD> _security_mds = new(0);
long _cursor = 0;
public ChannelConsumer(MDConsumerChannel channel) =>
_channel = channel;
public ChannelConsumer(MDConsumerChannel channel, IEnumerable<SecurityMD> security_mds) {
_channel = channel;
_security_mds = security_mds.ToDictionaryCrushed(s => s.id);
}
public IEnumerable<TradeInfo> read_trades() {
foreach (var tm in _channel.read_trades(ref _cursor)) {
if (tm != null && _security_mds.TryGetValue(tm.Key, out var smd))
yield return new TradeInfo(
smd, new TradeMessageImmutable(tm));
}
}
}
}