#nullable enable namespace bts.md { using bts.api.core; using mbts; using mbts.co2; using mbts.spark; using Spark.Api.MarketData; using System; using System.Collections.Generic; using System.Linq; using System.Reactive.Linq; public class MarketDataClient { readonly MDSource _source; readonly TimeSpan _poll_interval; readonly uint _num_depth_levels; public MarketDataClient(MDSource source) : this(source, 5, TimeSpan.FromSeconds(0.1)) { } public MarketDataClient(MDSource source, uint num_depth_levels, TimeSpan poll_interval) { _source = source; _poll_interval = poll_interval; _num_depth_levels = num_depth_levels; } public IObservable> market_data(SecurityCriteria? criteria = null) { // 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. return criteria.subscribe_md(_source.subscribe_securities()) .Select(fixed_sec_market_data) .FlattenTableSeries(); IObservable> fixed_sec_market_data( IEnumerable security_mds) { // Convert 'security_mds' to a list of PollableBooks. var cached_books = security_mds .Select(s => new PollableBook(s, _num_depth_levels)) .ToList(); return Observable.Interval(_poll_interval).Scan( TableUpdate.mk_empty(get_sec_id), poll_books); uint get_sec_id(BookTuple book) => book.security.Id; TableUpdate poll_books(TableUpdate 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(); } } } class PollableBook { readonly SecurityMD _security_md; readonly uint _num_depth_levels; ulong _last_update_time = 0; // Reuse the same arrays as an optimization to avoid reallocating memory on each poll. // Note: this will break if the code isn't called in a thread-safe manner. NativePriceSize[] _bids; NativePriceSize[] _asks; public PollableBook(SecurityMD security_md, uint num_depth_levels) { _security_md = security_md; _num_depth_levels = num_depth_levels; _bids = new NativePriceSize[_num_depth_levels]; _asks = new NativePriceSize[_num_depth_levels]; } public BookTuple to_book_tuple() { var book = new Book( _security_md.security.Id, _to_book_side(_bids), _to_book_side(_asks)); return new(_security_md.security, book); } public bool poll_changes() => _security_md.md.get_depth( ref _last_update_time, ref _bids, ref _asks, _num_depth_levels); static List _to_book_side(NativePriceSize[] native_book_side) => native_book_side .Select(nps => new PriceSize(nps.size, nps.direct_size, nps.implied_size, nps.price)) .ToList(); } } }