diff --git a/src/client/sparkcmd/Cmd/Historical/Analyzers/OrderBook.cs b/src/client/sparkcmd/Cmd/Historical/Analyzers/OrderBook.cs new file mode 100644 index 000000000..dd0dcbb0f --- /dev/null +++ b/src/client/sparkcmd/Cmd/Historical/Analyzers/OrderBook.cs @@ -0,0 +1,297 @@ +using System; +using System.Collections.Generic; +using System.Reflection; +using bts.api.core; +using bts.md; +using System.Linq; +using System.IO; +using System.Threading.Tasks; +using bts.api; +using Google.Protobuf.WellKnownTypes; +using bts.co2; +using mbts.co2; + +using QueueType = System.Collections.Generic.SortedDictionary; + +namespace bts.history +{ + class OrderEntry + { + public Timestamp transact_time; + public ulong order_id; + public ulong order_priority; + public double price; + public ulong size; + public uint reference_id; + public bool deleted; + } + + + class OrderBook + { + public const string quote_event_done = "10000100"; + + //price, priority + readonly Dictionary< double, QueueType > _mbo = new Dictionary(); + //orderid to { price, priority } + readonly Dictionary< ulong, Tuple > _mbokey = new Dictionary>(); + readonly SortedList _myorders = new SortedList(); + + readonly BookMessage _mbp; + public BookMessage current_book => _mbp; + readonly Queue _tradelog = new Queue(); + public Queue tradelog => _tradelog; + + public OrderBook() + { + _mbp = new BookMessage(); + init_book(_mbp); + } + + bool fill(OrderEntry myorder, OrderIDEntry trade) + { + if(myorder.size < trade.LastQty) //full fill of my order, keep going + { + _tradelog.Append(new OrderEntry { price = myorder.price, size = myorder.size }); + trade.LastQty -= (uint) myorder.size; + return true; + } + else + { + _tradelog.Append(new OrderEntry { price = myorder.price, size = trade.LastQty }); + trade.LastQty = 0; + return false; + } + } + + void process_trades(MarketDataIncrementalRefresh md) + { + foreach (var trade in md.OrderIdEntries) + { + Log.assert(_mbokey.TryGetValue(trade.OrderId, out Tuple tup)); + var priority = tup.Item2; + foreach(var myorder in _myorders.Values) + { + if(priority > myorder.order_priority) //fill me first; the real order still gets decremented which isn't quite right + { + if(!fill(myorder, trade)) + continue; + } + } + } + } + + //once you're in, they can't get in front of you + public ulong insert_my_order(Google.Protobuf.WellKnownTypes.Timestamp reference_time, uint latency_us, double price, uint size) + { + Log.assert(_mbo.TryGetValue(price, out QueueType queue)); + OrderEntry order = new OrderEntry() { price = price, size = size, order_id = 0 }; + order.transact_time = Timestamp.FromDateTime( reference_time.ToDateTime().AddTicks(latency_us * TimeSpan.TicksPerMillisecond * 1000) ); + var key = queue.Keys.Last(); + order.order_priority = key + 1; + queue.Add(order.order_priority, order); + return order.order_priority; //we key on this for our orders, odds of collision are low + } + + readonly Dictionary _reference = new Dictionary(); + public void process_md(MarketDataIncrementalRefresh md, string debug_fix = null) + { + _reference.Clear(); + bool bidoffer = false, trade = false; + foreach (var entry in md.MdEntries) + { + if (entry.MdEntryType == MDEntryType.Bid || entry.MdEntryType == MDEntryType.Offer) + { + keep_book(_mbp, entry); + if (md.MatchEventIndicator == quote_event_done) + validate_book(_mbp, debug_fix); + _reference[entry.ReferenceId] = entry; + bidoffer = true; + } + else if(entry.MdEntryType == MDEntryType.Trade) + { + trade = true; + } + } + Log.assert( !(bidoffer && trade), "Saw trade and bids / offers in same md packet"); + if(bidoffer) + process_orders(md); + else if(trade) + process_trades(md); + } + + + void process_orders(MarketDataIncrementalRefresh md) + { + foreach (var order in md.OrderIdEntries) + { + if (_reference.TryGetValue(order.ReferenceId, out MDEntry mdval)) + { + if (order.OrderUpdateAction == MDUpdateAction.New) + { + var q = _mbo.GetOrAdd(mdval.MdEntryPx, x => new QueueType()); + var neworder = new OrderEntry + { + transact_time = md.TransactTime, + order_id = order.OrderId, + order_priority = order.MdOrderPriority, + price = mdval.MdEntryPx, + size = order.MdDisplayQty, + reference_id = order.ReferenceId + }; + q.Add(order.MdOrderPriority, neworder); + _mbokey[order.OrderId] = Tuple.Create(mdval.MdEntryPx, order.MdOrderPriority); + } + else if (order.OrderUpdateAction == MDUpdateAction.Change) + { + Log.assert(_mbokey.TryGetValue(order.OrderId, out Tuple tup)); + + var currq = _mbo.GetOrAdd(tup.Item1, x => { Log.assert(false); return null; } ); + Log.assert(currq.Remove(tup.Item2)); + var newq = _mbo.GetOrAdd(mdval.MdEntryPx, x => new QueueType()); + newq.AddOrUpdate(order.MdOrderPriority, + x => + { + var neworder = new OrderEntry + { + transact_time = md.TransactTime, + order_id = order.OrderId, + order_priority = order.MdOrderPriority, + price = mdval.MdEntryPx, + size = order.MdDisplayQty, + reference_id = order.ReferenceId + }; + Log.assert(neworder.order_priority == order.MdOrderPriority, "bad priority"); + return neworder; + }, + (id, x) => + { + Log.assert(x.order_id == order.OrderId, "orderid invariant"); + x.transact_time = md.TransactTime; + x.order_priority = order.MdOrderPriority; + x.price = mdval.MdEntryPx; + x.reference_id = order.ReferenceId; + x.size = order.MdDisplayQty; + return x; + }); + } + else if (order.OrderUpdateAction == MDUpdateAction.Delete) + { + Log.assert(_mbokey.TryGetValue(order.OrderId, out Tuple tup)); + var currq = _mbo.GetOrAdd(tup.Item1, x => { Log.assert(false); return null; }); + + currq.AddOrUpdate(order.MdOrderPriority, + x => { Log.assert(false, "shouldn't add"); return null; }, + (id, x) => + { + Log.assert(x.order_id == order.OrderId, "orderid invariant"); + x.deleted = true; + return x; + }); + } + } + } + } + + + private double get_price_and_correct_ticks(Security sec, MDEntry md) + { + var d = md.MdEntryPx - Math.IEEERemainder(md.MdEntryPx, sec.ContractSpec.LowTick); + return d; + } + + public static void init_book(BookMessage book) + { + for (int i = 0; i < NativePriceHelpers.COCONUT_MAX_DEPTH; i++) + { + book.Bids.Add(new PriceSizeMessage() { Exponent = 0, Mantissa = 0, Size = 0 }); + book.Asks.Add(new PriceSizeMessage() { Exponent = 0, Mantissa = 0, Size = 0 }); + } + } + + public static void keep_book(BookMessage book, MDEntry md) + { + if (md.MdPriceLevel <= 0) + return; + var fixedp = md.MdEntryPx; //get_price_and_correct_ticks(upd, md); + var dv = IntPrice.from_double(fixedp); + var ps = new PriceSizeMessage() + { + Size = md.MdEntrySize, + Exponent = dv.exponent, + Mantissa = dv.mantissa, + }; + if (md.MdEntryType == MDEntryType.Bid) + { + switch (md.MdUpdateAction) + { + case MDUpdateAction.Change: + { + book.Bids[(int)md.MdPriceLevel - 1] = ps; + } + break; + case MDUpdateAction.New: + { + for (int index = (int)NativePriceHelpers.COCONUT_MAX_DEPTH - 1; md.MdPriceLevel <= index; index--) + book.Bids[index] = book.Bids[index - 1]; + book.Bids[(int)md.MdPriceLevel - 1] = ps; + } + break; + case MDUpdateAction.Delete: + { + int index = (int)md.MdPriceLevel - 1; + for (; index < NativePriceHelpers.COCONUT_MAX_DEPTH - 1; index++) + book.Bids[index] = book.Bids[index + 1]; + book.Bids[index] = new PriceSizeMessage() { Size = 0, Exponent = 0, Mantissa = 0 }; + } + break; + } + } + else if (md.MdEntryType == MDEntryType.Offer) + { + switch (md.MdUpdateAction) + { + case MDUpdateAction.Change: + { + book.Asks[(int)md.MdPriceLevel - 1] = ps; + } + break; + case MDUpdateAction.New: + { + for (int index = (int)NativePriceHelpers.COCONUT_MAX_DEPTH - 1; md.MdPriceLevel <= index; index--) + book.Asks[index] = book.Asks[index - 1]; + book.Asks[(int)md.MdPriceLevel - 1] = ps; + } + break; + case MDUpdateAction.Delete: + { + int index = (int)md.MdPriceLevel - 1; + for (; index < NativePriceHelpers.COCONUT_MAX_DEPTH - 1; index++) + book.Asks[index] = book.Asks[index + 1]; + book.Asks[index] = new PriceSizeMessage() { Size = 0, Exponent = 0, Mantissa = 0 }; + } + break; + } + } + } + + public static bool validate_book(BookMessage book, string debug_fix = null) + { + bool desc = true; + for (int i = 0; i < book.Bids.Count - 1; i++) + { + double curr = NativePriceHelpers.to_double(book.Bids[i].Mantissa, (sbyte)book.Bids[i].Exponent); + double next = NativePriceHelpers.to_double(book.Bids[i + 1].Mantissa, (sbyte)book.Bids[i + 1].Exponent); + if (curr == 0.0) + continue; + desc = desc && curr > next; + } + if (!desc) + { + bts.Log.Testing.info("bad bid book " + debug_fix ?? ""); + return false; + } + return desc; + } + } +} \ No newline at end of file diff --git a/src/client/sparkcmd/Cmd/Historical/Analyzers/OrderQueue.cs b/src/client/sparkcmd/Cmd/Historical/Analyzers/OrderQueue.cs new file mode 100644 index 000000000..58c347f7e --- /dev/null +++ b/src/client/sparkcmd/Cmd/Historical/Analyzers/OrderQueue.cs @@ -0,0 +1,30 @@ +using System; +using System.Collections.Generic; +using System.Reflection; +using bts.api.core; +using bts.md; +using System.Linq; +using System.IO; +using System.Threading.Tasks; +using bts.api; +using Google.Protobuf.WellKnownTypes; +using bts.co2; +using mbts.co2; + +namespace bts.history +{ + + + class OrderQueue + { + readonly Dictionary> _orders = new Dictionary>(); + public OrderQueue() + { + } + + public void process_orders(MarketDataIncrementalRefresh md) + { + + } + } +} \ No newline at end of file diff --git a/src/client/sparkcmd/Cmd/Historical/HistoricalDataReplayer.cs b/src/client/sparkcmd/Cmd/Historical/HistoricalDataReplayer.cs index fb9603fad..6cc7e4238 100644 --- a/src/client/sparkcmd/Cmd/Historical/HistoricalDataReplayer.cs +++ b/src/client/sparkcmd/Cmd/Historical/HistoricalDataReplayer.cs @@ -20,7 +20,6 @@ namespace bts.history Google.Protobuf.WellKnownTypes.Timestamp _time; Dictionary _channels = new Dictionary(); - const string _quote_event_done = "10000100"; public HistoricalDataReplayer(ServiceContext context) { @@ -105,6 +104,7 @@ namespace bts.history _channels.Add(prod, chan); } int count = 0; + foreach (var md in mdr.MdEntries) { var upd = chan.Updates.FirstOrDefault(x => x.Key == md.SecurityId); @@ -112,117 +112,16 @@ namespace bts.history { upd = create(prod, md); upd.Direct = new BookMessage(); - for (int i = 0; i < NativePriceHelpers.COCONUT_MAX_DEPTH; i++) - { - upd.Direct.Bids.Add(new PriceSizeMessage() { Exponent = 0, Mantissa = 0, Size = 0 }); - upd.Direct.Asks.Add(new PriceSizeMessage() { Exponent = 0, Mantissa = 0, Size = 0 }); - } + OrderBook.init_book(upd.Direct); chan.Updates.Add(upd); } - var prev = upd.Clone(); - keep_book(upd, md); + OrderBook.keep_book(upd.Direct, md); count++; - if (mdr.MatchEventIndicator == _quote_event_done) - validate_book(upd, md, fix, prev); - + if (mdr.MatchEventIndicator == OrderBook.quote_event_done) + OrderBook.validate_book(upd.Direct, fix); } } - private bool validate_book(ChannelUpdate upd, MDEntry md, string fix, ChannelUpdate prev) - { - if (md.MdEntryType == MDEntryType.Bid) - { - bool desc = true; - for (int i = 0; i < upd.Direct.Bids.Count - 1; i++) - { - double curr = NativePriceHelpers.to_double(upd.Direct.Bids[i].Mantissa, (sbyte)upd.Direct.Bids[i].Exponent); - double next = NativePriceHelpers.to_double(upd.Direct.Bids[i + 1].Mantissa, (sbyte)upd.Direct.Bids[i + 1].Exponent); - if (curr == 0.0) - continue; - desc = desc && curr > next; - } - if (!desc) - { - bts.Log.Testing.diag("bad bid book"); - return false; - } - } - return true; - } - - private double get_price_and_correct_ticks(ChannelUpdate upd, MDEntry md) - { - var d = md.MdEntryPx - Math.IEEERemainder(md.MdEntryPx, upd.Security.ContractSpec.LowTick); - return d; - } - - private void keep_book(ChannelUpdate upd, MDEntry md) - { - if (md.MdPriceLevel <= 0) - return; - var fixedp = get_price_and_correct_ticks(upd, md); - var dv = IntPrice.from_double(fixedp); - var ps = new PriceSizeMessage() - { - Size = md.MdEntrySize, - Exponent = dv.exponent, - Mantissa = dv.mantissa, - }; - if (md.MdEntryType == MDEntryType.Bid) - { - switch (md.MdUpdateAction) - { - case MDUpdateAction.Change: - { - upd.Direct.Bids[(int)md.MdPriceLevel - 1] = ps; - } - break; - case MDUpdateAction.New: - { - for (int index = (int)NativePriceHelpers.COCONUT_MAX_DEPTH - 1; md.MdPriceLevel <= index; index--) - upd.Direct.Bids[index] = upd.Direct.Bids[index - 1]; - upd.Direct.Bids[(int)md.MdPriceLevel - 1] = ps; - } - break; - case MDUpdateAction.Delete: - { - int index = (int)md.MdPriceLevel - 1; - for (; index < NativePriceHelpers.COCONUT_MAX_DEPTH - 1; index++) - upd.Direct.Bids[index] = upd.Direct.Bids[index + 1]; - upd.Direct.Bids[index] = new PriceSizeMessage() { Size = 0, Exponent = 0, Mantissa = 0 }; - } - break; - } - } - else if (md.MdEntryType == MDEntryType.Offer) - { - switch (md.MdUpdateAction) - { - case MDUpdateAction.Change: - { - upd.Direct.Asks[(int)md.MdPriceLevel - 1] = ps; - } - break; - case MDUpdateAction.New: - { - for (int index = (int)NativePriceHelpers.COCONUT_MAX_DEPTH - 1; md.MdPriceLevel <= index; index--) - upd.Direct.Asks[index] = upd.Direct.Asks[index - 1]; - upd.Direct.Asks[(int)md.MdPriceLevel - 1] = ps; - } - break; - case MDUpdateAction.Delete: - { - int index = (int)md.MdPriceLevel - 1; - for (; index < NativePriceHelpers.COCONUT_MAX_DEPTH - 1; index++) - upd.Direct.Asks[index] = upd.Direct.Asks[index + 1]; - upd.Direct.Asks[index] = new PriceSizeMessage() { Size = 0, Exponent = 0, Mantissa = 0 }; - } - break; - } - } - - } - async public Task replay(DateTime start, DateTime end, string symbol, SecurityType st, string analyzer_security = null, bool should_send = false, int us = 20) @@ -259,7 +158,7 @@ namespace bts.history { if (_time == null) { - if (md.MatchEventIndicator == _quote_event_done) + if (md.MatchEventIndicator == OrderBook.quote_event_done) { if (should_send) send(); //send the initial books @@ -271,7 +170,7 @@ namespace bts.history process(prod, md, line); var ts = (md.TransactTime - _time).ToTimeSpan(); var diff = ts.Ticks / (TimeSpan.TicksPerMillisecond / 1000); - if (diff > us && md.MatchEventIndicator == _quote_event_done) + if (diff > us && md.MatchEventIndicator == OrderBook.quote_event_done) { if (should_send) send(); //send the next book diff --git a/src/lib/api/services/HistoricalDataService.proto b/src/lib/api/services/HistoricalDataService.proto index 13c76fbbe..e68656d62 100644 --- a/src/lib/api/services/HistoricalDataService.proto +++ b/src/lib/api/services/HistoricalDataService.proto @@ -11,14 +11,14 @@ import "lib/domain_model/Security.proto"; enum MDUpdateAction { MDUpdateAction_UNSET = 0; - NEW = 48; + NEW = 48; // '0' CHANGE = 49; DELETE = 50; } enum MDEntryType { MDEntryType_UNSET = 0; - BID = 48; + BID = 48; // '0' OFFER = 49; TRADE = 50; OPENING_PRICE = 52; @@ -26,7 +26,7 @@ enum MDEntryType } message MDEntry { - MDUpdateAction md_update_action = 279; + MDUpdateAction md_update_action = 279; //delimiter MDEntryType md_entry_type = 269; uint32 security_id = 48; string symbol = 55; @@ -48,11 +48,12 @@ message MDEntry } message OrderIDEntry { - uint64 order_id = 37; + uint64 order_id = 37; //delimiter uint64 md_display_qty = 37706; uint64 md_order_priority = 37707; MDUpdateAction order_update_action = 37708; uint32 reference_id = 9633; + uint32 last_qty = 32; } //https://www.cmegroup.com/confluence/display/EPICSANDBOX/MDP+3.0+-+Market+by+Order+-+Book+Management