Local/Direct bbo subscription

This commit is contained in:
Taha committed 2025-03-02 02:23:17 -05:00
1 parent 74b376ce56
commit 7b5f034ed2
7 files changed
+310 -56

No files matched your search

+226
View File
@@ -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<LocalMDDaemon.BBO> 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<double, bool> 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}");
}
}
}
}
}
+58 -49
View File
@@ -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<uint, SecurityMD> _server_sec_map = new Dictionary<uint, SecurityMD>();
Dictionary<uint, SecurityMD> _fake_sec_map = new Dictionary<uint, SecurityMD>();
private Dictionary<uint, SecurityMD> _exchange_id_map = new Dictionary<SecurityKey, SecurityMD>();
private readonly IList<IDisposable> _subs = new List<IDisposable>();
private SyncQueue<LocalMDDaemon.BBO> _waiting_bbo = new SyncQueue<LocalMDDaemon.BBO>();
[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<uint, SecurityMD> 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<LocalMDDaemon.BBO> unprocessed_bbo_list = new List<LocalMDDaemon.BBO>();
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<uint, SecurityMD> 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<uint, SecurityMD> sec_map)
{
private UInt32 _get_exchange_sec_id(SecurityImmutable sec) {
// TODO:
return Convert.ToUInt32(sec.Cboe.ExchangeId);
}
private void _on_server_sec_map(IReadOnlyDictionary<uint, SecurityMD> 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<uint, SecurityMD>(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<uint, SecurityMD> sec_map)
{
private void _on_fake_sec_map(IReadOnlyDictionary<uint, SecurityMD> sec_map) {
bts.Log.Gen.info(String.Format("MergedMDDaemon._on_fake_sec_map sz: {0}", sec_map.Count()));
_fake_sec_map = new Dictionary<uint, SecurityMD>(sec_map);
_merge_and_post();
}
private void _merge_and_post()
{
Func<SecurityMD, bool> is_active = (sec_md) =>
{
private void _merge_and_post() {
Func<SecurityMD, bool> 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()));
@@ -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,
@@ -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; }
+7 -3
View File
@@ -4,13 +4,17 @@ using System.Runtime.InteropServices;
namespace mbts.co2 {
[StructLayout(LayoutKind.Explicit)]
public readonly struct IntPrice : IEquatable<IntPrice> {
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();
}
}
@@ -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;
+11 -4
View File
@@ -13,9 +13,9 @@ namespace mbts {
using System.Linq;
using System.Threading;
public readonly struct SecurityMD : IEquatable<SecurityMD> {
public /*readonly*/ struct SecurityMD : IEquatable<SecurityMD> {
public static readonly Func<SecurityMD, uint> 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<TickDisplayRuleImmutable>? 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<TickDisplayRuleImmutable> price_display_rules { get; }