From 7b5f034ed280b86325ad9e28f27ac8617fa034e6 Mon Sep 17 00:00:00 2001 From: Taha Date: Fri, 28 Feb 2025 10:00:34 -0500 Subject: [PATCH] Local/Direct bbo subscription --- src/client/spark/Daemons/LocalMDDaemon.cs | 226 ++++++++++++++++++ src/client/spark/Daemons/MergedMDDaemon.cs | 107 +++++---- .../MarketData/FakeMDConsumerHandle.cs | 4 + .../spark_api/MarketData/IMDConsumerHandle.cs | 1 + src/client/spark_api/MarketData/IntPrice.cs | 10 +- .../spark_api/MarketData/MDConsumerHandle.cs | 3 + src/client/spark_api/MarketData/SecurityMD.cs | 15 +- 7 files changed, 310 insertions(+), 56 deletions(-) create mode 100644 src/client/spark/Daemons/LocalMDDaemon.cs diff --git a/src/client/spark/Daemons/LocalMDDaemon.cs b/src/client/spark/Daemons/LocalMDDaemon.cs new file mode 100644 index 000000000..4f9f42539 --- /dev/null +++ b/src/client/spark/Daemons/LocalMDDaemon.cs @@ -0,0 +1,226 @@ +using bts.api; + +using mbts.co2; + +using System; +using System.Diagnostics; +using System.IO; +using System.IO.Pipes; +using System.Text; +using System.Threading; + +namespace bts { + public class LocalMDConsumerHandle : mbts.co2.IMDConsumerHandle { + private readonly SecurityImmutable _sec; + private readonly LocalMDDaemon.BBO _bbo; + public LocalMDConsumerHandle(SecurityImmutable sec, LocalMDDaemon.BBO bbo) { + _sec = sec; + _bbo = bbo; + } + + public UInt32 key => _sec.Id; + // The exchange key can change at CBOE. This numeric_id will always be correct + public ulong numeric_id => Convert.ToUInt64(_sec.Cboe.ExchangeId); + + public void set_bbo(double bid_price, UInt32 bid_qty, double ask_price, UInt32 ask_qty) { + _bbo.bid_price = bid_price; + _bbo.bid_qty = bid_qty; + _bbo.ask_price = ask_price; + _bbo.ask_qty = ask_qty; + } + + public bool is_heart_beating => true; + public bool has_depth => true; + + // This property exists for specific performance optimization purposes + // Most callers should just use get_bbo/get_depth + public ulong market_timestamp => 0; + public ulong misc_timestamp => 0; + + public ulong total_volume => 0; + + public double settlement_price => 100.0; + public DateTime settlement_date => DateTime.Now; + public double previous_settlement_price => 200.0; + public DateTime previous_settlement_date => DateTime.Now; + + public double open_price => 300; + public DateTime open_date => DateTime.Now; + + public double close_price => 300; + public DateTime close_date => DateTime.Now; + public double session_high => 1000; + public double session_low => 500; + public double fixing_price => 20; + + + public bool get_bbo(ref ulong time, out NativePriceSize bid, out NativePriceSize ask) { + bid = new NativePriceSize(new IntPrice(_bbo.bid_price), Convert.ToSingle(_bbo.bid_qty)); + ask = new NativePriceSize(new IntPrice(_bbo.ask_price), Convert.ToSingle(_bbo.ask_qty)); + return true; + } + + public bool get_depth( + ref ulong time, ref NativePriceSize[] bids, ref NativePriceSize[] asks, uint depth) { + return true; + } + + public bool get_last_trade( + ref ulong time, out NativePriceSize ps, out DateTime timestamp, out ulong total_volume) { + ps = new NativePriceSize(); + timestamp = DateTime.MinValue; + total_volume = 0; + return false; + } + + public bool get_last_trade( + ref ulong time, + out NativePriceSize ps, + out DateTime timestamp, + out ulong total_volume, + out bool from_spread + ) { + ps = new NativePriceSize(); + timestamp = DateTime.MinValue; + total_volume = 0; + from_spread = false; + return false; + } + + public class PriceLevel { + public double price; + public uint qty; + + public PriceLevel(double price_arg, uint qty_arg) { + price = price_arg; + qty = qty_arg; + } + + public static PriceLevel empty => new(double.NaN, 0); + + public static IntPrice intprice_from_double(double d) => + double.IsNaN(d) ? IntPrice.NaN : new IntPrice((long)d, 0); + + public NativePriceSize get_native_ps() => + new(intprice_from_double(price), qty); + } + } + + public class LocalMDDaemon { + + public class BBO { + public double bid_price = Double.NaN; + public UInt32 bid_qty = 0; + public double ask_price = Double.NaN; + public UInt32 ask_qty = 0; + public UInt32 exchange_id = 0; + public BBO(double bid_price_, uint bid_qty_, double ask_price_, uint ask_qty_, uint exchange_id_) { + bid_price = bid_price_; + bid_qty = bid_qty_; + ask_price = ask_price_; + ask_qty = ask_qty_; + exchange_id = exchange_id_; + } + + public override string ToString() { + return $"bid_price: {bid_price} bid_qty: {bid_qty} ask_price: {ask_price} ask_qty: {ask_qty} exchange_id: {exchange_id}"; + } + } + static Process producer_process = null; + static void start_or_restart_producer_process(string exePath) { + foreach (var process in Process.GetProcessesByName(Path.GetFileNameWithoutExtension(exePath))) { + try { + bts.Log.Gen.info($"Stopping existing producer process (PID: {process.Id})..."); + process.Kill(); + process.WaitForExit(); + } catch (Exception ex) { + bts.Log.Gen.error($"Stopping existing producer process (PID: {process.Id})...ex: {ex.Message}"); + } + } + if (producer_process != null && !producer_process.HasExited) { + bts.Log.Gen.info("Stopping existing producer process..."); + producer_process.Kill(); + producer_process.WaitForExit(); + producer_process.Dispose(); + } + + bts.Log.Gen.info("Starting new producer process..."); + + producer_process = new Process(); + producer_process.StartInfo.FileName = exePath; // Path to the EXE + producer_process.StartInfo.UseShellExecute = false; + producer_process.StartInfo.RedirectStandardOutput = true; + producer_process.StartInfo.RedirectStandardError = true; + producer_process.Start(); + + bts.Log.Gen.info("Producer process started."); + } + public Action on_bbo = (bbo) => { }; + + public LocalMDDaemon() { + System.Threading.Thread pipe_read_thr = new Thread(_start_reading); + pipe_read_thr.IsBackground = true; + pipe_read_thr.Start(); + + } + + private void _start_reading() { + // TODO, fix this + string exe_path = //@".\dist\producer_delayed\producer_delayed.exe"; //UNCOMMENT FOR DELAYED + @"C:\Users\m_tah\Downloads\HelloWorld\HelloWorld\dist\producer_delayed\producer_delayed.exe"; + + // delete pipe if already exists + using NamedPipeClientStream old_pipe_client = new NamedPipeClientStream(".", "MyPipe", PipeDirection.In); + try { + old_pipe_client.Close(); + old_pipe_client.Dispose(); + } catch { + + } + start_or_restart_producer_process(exe_path); + + // Connect to the named pipe + using NamedPipeClientStream pipe_client = new NamedPipeClientStream(".", "MyPipe", PipeDirection.In); + + pipe_client.Connect(); + + bts.Log.Gen.info("Connected to pipe. Waiting for messages..."); + + byte[] buffer = new byte[1024]; + + while (true) { + try { + int bytes_read = pipe_client.Read(buffer, 0, buffer.Length); + + if (bytes_read == 0)// this means there was an error + { + break; + } + Func qty_ok = (d) => { + if (d < 0 || d > Convert.ToDouble(UInt32.MaxValue)) + return false; + return true; + }; + double double1 = BitConverter.ToDouble(buffer, 0); + double double2 = BitConverter.ToDouble(buffer, 8); + double double3 = BitConverter.ToDouble(buffer, 16); + double double4 = BitConverter.ToDouble(buffer, 24); + uint int5 = BitConverter.ToUInt32(buffer, 32); + //Log.Gen.info($"Read from pipe {double1} , {double2} , {double3} , {double4} , {int5}"); + if (!qty_ok(double2) || !qty_ok(double4)) + continue; + LocalMDDaemon.BBO bbo = new BBO(double1, Convert.ToUInt32(double2), + double3, Convert.ToUInt32(double4), int5); + on_bbo(bbo); + } catch (IOException) { + bts.Log.Gen.error("Pipe disconnected. Attempting to reconnect..."); + pipe_client.Dispose(); + System.Threading.Thread.Sleep(1000); + pipe_client.Connect(); // Try reconnecting + } catch (Exception ex) { + bts.Log.Gen.error($"Exception: {ex.Message}"); + } + } + } + } +} \ No newline at end of file diff --git a/src/client/spark/Daemons/MergedMDDaemon.cs b/src/client/spark/Daemons/MergedMDDaemon.cs index 72d9c0cf9..e3edbae44 100644 --- a/src/client/spark/Daemons/MergedMDDaemon.cs +++ b/src/client/spark/Daemons/MergedMDDaemon.cs @@ -23,20 +23,21 @@ using System.Threading.Tasks; using SecurityKey = System.UInt32; -namespace bts -{ +namespace bts { + [Export(typeof(IShellDaemon))] - internal class MergedMDDaemon : IShellDaemon, IDisposable - { + internal class MergedMDDaemon : IShellDaemon, IDisposable { private readonly IBus _bus; + private LocalMDDaemon _local_md_daemon = new LocalMDDaemon(); IDisposable _dispose; Dictionary _server_sec_map = new Dictionary(); Dictionary _fake_sec_map = new Dictionary(); + private Dictionary _exchange_id_map = new Dictionary(); private readonly IList _subs = new List(); + private SyncQueue _waiting_bbo = new SyncQueue(); [ImportingConstructor] - public MergedMDDaemon(IBus bus) - { + public MergedMDDaemon(IBus bus) { //TempTester.test_analytics(); bts.Log.Gen.info("MergedMDDaemon started"); _bus = bus; @@ -44,48 +45,52 @@ namespace bts d => _on_server_sec_map(d))); _subs.Add(_bus.subscribe(SparkTags.FakeSecuritiesTag).OnDispatcher().Subscribe( d => _on_fake_sec_map(d))); - // This is done periodically to remove expired contracts - // (disabling it right now because we are not sure if deleting securities - // works with the various UI windows) - // _subs.Add(_bus.subscribe(SparkTags.SparkTimer).BufferLatest(TimeSpan.FromMinutes(1)) - // .Subscribe(t => _merge_and_post())); - //_test_md_stream(); - } - // BCG.MDStream _md_stream = null; - // private void _test_md_stream() - // { - // _bus.subscribe(SparkTags.SparkTimer).Subscribe(t => - // { - // if (_md_stream == null) - // { - // _md_stream = new BCG.MDStream(); - // _md_stream.onChange += _on_md; - // } - // else - // { - // BCG.ViewStreamDatabase.instance.doWork(); - // } - // }); - // } + _subs.Add(_bus.subscribe(SparkTags.SparkTimer).OnDispatcher().Subscribe( + ts => _on_timer())); - private void _on_md(object obj) - { - BCG.DataPacket dp = obj as DataPacket; - bts.Log.Gen.info($"MDStream callback dp: {dp}"); + _local_md_daemon.on_bbo += (bbo_pack) => { + //bts.Log.Gen.info($"MergedMDDaemon on_bbo, local bbo callback, bbo: {bbo_pack}"); + _waiting_bbo.enqueue(bbo_pack); + }; } - private void _log_options(IReadOnlyDictionary sec_map) - { + private void _on_timer() { + _process_local_bbo_updates(); + } + + private void _process_local_bbo_updates() { + if (_waiting_bbo.getCount() == 0) + return; + var bbo_list = _waiting_bbo.dequeue_all(); + List unprocessed_bbo_list = new List(); + foreach (var bbo in bbo_list) { + //bts.Log.Gen.info($"MergedMDDaemon._process_local_bbo_updates read from queue bbo: {bbo}"); + UInt32 exchange_id = bbo.exchange_id; + SecurityMD sec_md; + if (_exchange_id_map.TryGetValue(exchange_id, out sec_md)) { + if (!(sec_md.md is LocalMDConsumerHandle)) { + LocalMDConsumerHandle md_handle = new LocalMDConsumerHandle(sec_md.security, bbo); + sec_md.md = md_handle; + } else { + sec_md.md.set_bbo(bbo.bid_price, bbo.bid_qty, bbo.ask_price, bbo.ask_qty); + } + } else { + //unprocessed_bbo_list.Add(bbo); + } + } + // foreach (var unpbbo in unprocessed_bbo_list) + // _waiting_bbo.enqueue(unpbbo); + } + + private void _log_options(IReadOnlyDictionary sec_map) { string rv = "MergedMDDaemon Options:\n"; - foreach (var kv in sec_map) - { + foreach (var kv in sec_map) { var sec = kv.Value.security; var md = kv.Value.md; ulong time = 0; NativePriceSize bid, ask; var has_md = md.get_bbo(ref time, out bid, out ask); - if (sec.HasOption) - { + if (sec.HasOption) { rv += $"id: {kv.Key} desc: {sec.security_desc()} sym: {sec.Symbol} " + $"exp: {sec.security_expiration()} " + $"k: {sec.Option.Strike} cp: {sec.Option.CallPut} " + @@ -96,31 +101,35 @@ namespace bts Log.Gen.info(rv); } - private void _on_server_sec_map(IReadOnlyDictionary sec_map) - { + private UInt32 _get_exchange_sec_id(SecurityImmutable sec) { + // TODO: + return Convert.ToUInt32(sec.Cboe.ExchangeId); + } + + private void _on_server_sec_map(IReadOnlyDictionary sec_map) { //_log_options(sec_map); bts.Log.Gen.info(String.Format("MergedMDDaemon._on_server_sec_map sz: {0}", sec_map.Count())); _server_sec_map = new Dictionary(sec_map); + foreach (var kv in _server_sec_map) { + UInt32 exchange_sec_id = _get_exchange_sec_id(kv.Value.security); + _exchange_id_map.Add(exchange_sec_id, kv.Value); + } _merge_and_post(); } - private void _on_fake_sec_map(IReadOnlyDictionary sec_map) - { + private void _on_fake_sec_map(IReadOnlyDictionary sec_map) { bts.Log.Gen.info(String.Format("MergedMDDaemon._on_fake_sec_map sz: {0}", sec_map.Count())); _fake_sec_map = new Dictionary(sec_map); _merge_and_post(); } - private void _merge_and_post() - { - Func is_active = (sec_md) => - { + private void _merge_and_post() { + Func is_active = (sec_md) => { var sec = sec_md.security; return SecurityExpirationHelper.is_unexpired(sec); }; var to_pub = _server_sec_map.Where(kv => is_active(kv.Value)).ToDictionary(kv => kv.Key, kv => kv.Value); - foreach (var kv in _fake_sec_map) - { + foreach (var kv in _fake_sec_map) { to_pub[kv.Key] = kv.Value; } bts.Log.Gen.info(String.Format("MergedMDDaemon._merge_and_post sz: {0}", to_pub.Count())); diff --git a/src/client/spark_api/MarketData/FakeMDConsumerHandle.cs b/src/client/spark_api/MarketData/FakeMDConsumerHandle.cs index 95b95e49e..e2ea9a26b 100644 --- a/src/client/spark_api/MarketData/FakeMDConsumerHandle.cs +++ b/src/client/spark_api/MarketData/FakeMDConsumerHandle.cs @@ -12,6 +12,10 @@ namespace mbts.co2 { readonly ulong _numeric_key; + public void set_bbo(double bid_price, UInt32 bid_qty, double ask_price, UInt32 ask_qty) { + + } + public FakeMDConsumerHandle( security_key key, ulong numeric_key, diff --git a/src/client/spark_api/MarketData/IMDConsumerHandle.cs b/src/client/spark_api/MarketData/IMDConsumerHandle.cs index c6ae5a5a6..746c9cd5c 100644 --- a/src/client/spark_api/MarketData/IMDConsumerHandle.cs +++ b/src/client/spark_api/MarketData/IMDConsumerHandle.cs @@ -7,6 +7,7 @@ namespace mbts.co2 { bool is_heart_beating { get; } bool has_depth { get; } security_key key { get; } + public void set_bbo(double bid_price, UInt32 bid_qty, double ask_price, UInt32 ask_qty); // The exchange key can change at CBOE. This numeric_id will always be correct ulong numeric_id { get; } diff --git a/src/client/spark_api/MarketData/IntPrice.cs b/src/client/spark_api/MarketData/IntPrice.cs index 27cec9411..55aecb9ae 100644 --- a/src/client/spark_api/MarketData/IntPrice.cs +++ b/src/client/spark_api/MarketData/IntPrice.cs @@ -4,13 +4,17 @@ using System.Runtime.InteropServices; namespace mbts.co2 { [StructLayout(LayoutKind.Explicit)] public readonly struct IntPrice : IEquatable { - public static readonly IntPrice NaN = new(0,127); + public static readonly IntPrice NaN = new(0, 127); [FieldOffset(0)] readonly long _mantissa; [FieldOffset(7)] readonly sbyte _exponent; + public IntPrice(double v) : + this(Convert.ToInt64(v * Math.Pow(10, 7)), 7) { + } + public IntPrice(long mantissa, sbyte exponent) { _mantissa = mantissa; _exponent = exponent; @@ -38,10 +42,10 @@ namespace mbts.co2 { public static bool operator ==(IntPrice a, IntPrice b) => a.Equals(b); public static bool operator !=(IntPrice a, IntPrice b) => !a.Equals(b); - public static bool operator < (IntPrice a, IntPrice b) => + public static bool operator <(IntPrice a, IntPrice b) => a.exponent == b.exponent ? a.mantissa < b.mantissa : a.price() < b.price(); - public static bool operator > (IntPrice a, IntPrice b) => + public static bool operator >(IntPrice a, IntPrice b) => a.exponent == b.exponent ? a.mantissa > b.mantissa : a.price() > b.price(); } } diff --git a/src/client/spark_api/MarketData/MDConsumerHandle.cs b/src/client/spark_api/MarketData/MDConsumerHandle.cs index 4a9ccd404..821340a8c 100644 --- a/src/client/spark_api/MarketData/MDConsumerHandle.cs +++ b/src/client/spark_api/MarketData/MDConsumerHandle.cs @@ -11,6 +11,9 @@ using security_key = System.UInt32; public unsafe class MDConsumerHandle : IMDConsumerHandle { + public void set_bbo(double bid_price, UInt32 bid_qty, double ask_price, UInt32 ask_qty) { + throw new NotImplementedException(); + } readonly HotEntry* _hot; readonly HotDepthEntry* _hot_depth; readonly ColdEntry* _cold; diff --git a/src/client/spark_api/MarketData/SecurityMD.cs b/src/client/spark_api/MarketData/SecurityMD.cs index 60e113189..04dabe119 100644 --- a/src/client/spark_api/MarketData/SecurityMD.cs +++ b/src/client/spark_api/MarketData/SecurityMD.cs @@ -13,9 +13,9 @@ namespace mbts { using System.Linq; using System.Threading; - public readonly struct SecurityMD : IEquatable { + public /*readonly*/ struct SecurityMD : IEquatable { public static readonly Func key_fn = smd => smd.security.Id; - + private IMDConsumerHandle _md; public SecurityMD( SecurityImmutable security, IMDConsumerHandle md, @@ -23,7 +23,7 @@ namespace mbts { TickDisplaySettingsImmutable? quantity_display = null, IEnumerable? price_display_rules = null) { this.security = security; - this.md = md; + _md = md; this.price_display = price_display ?? Security.Defaults.price_display_settingsi; this.quantity_display = quantity_display ?? Security.Defaults.quantity_display_settingsi; @@ -38,7 +38,14 @@ namespace mbts { public SecurityImmutable security { get; } public uint id => security.Id; - public IMDConsumerHandle md { get; } + public IMDConsumerHandle md { + get { + return _md; + } + set { + _md = value; + } + } public TickDisplaySettingsImmutable price_display { get; } public TickDisplaySettingsImmutable quantity_display { get; } public ImmutableList price_display_rules { get; }