static void ListenToMarketData() { var cfg = new Config() { Endpoint = Instance.Prod, Products = new List <string>() { "BTC-USD" }, }; using (var restClient = new ExchangeApi.Coinbase.REST.RestClient(cfg.Endpoint.REST, null)) using (var client = new Client(cfg)) { var book = new OrderBook(); var expectedBook = new OrderBook(); Action poll = () => { if (book.Sequence < 0) { _log.Info("Haven't received any messages yet"); return; } // Sleep on the scheduler thread in order to fall behind on the order book. Thread.Sleep(20000); ExchangeApi.Coinbase.REST.OrderBookResponse full = restClient.SendRequest(new ExchangeApi.Coinbase.REST.OrderBookRequest() { Product = "BTC-USD" }).Result; if (full.Sequence <= book.Sequence) { _log.Info("Order book isn't behind"); return; } _log.Info("Expecting sequence {0} in the near future", full.Sequence); Convert(full, expectedBook); }; client.OnOrderBook += (string product, TimestampedMsg <OrderBookDelta> msg) => { if (msg.Value.Bids.Count + msg.Value.Asks.Count > 10) { _log.Info("OnOrderBook({0}, IsLast={1}): {2} bid(s), {3} ask(s)", product, !client.Scheduler.HasReady(), msg.Value.Bids.Count, msg.Value.Asks.Count); } else { _log.Info("OnOrderBook({0}, IsLast={1}): {2}", product, !client.Scheduler.HasReady(), msg.Value); } ApplyDelta(book, msg.Value); Compare(expectedBook, book); }; client.Connect(); using (var timer = new PeriodicAction(cfg.Scheduler, TimeSpan.FromSeconds(30), TimeSpan.FromSeconds(30), poll)) while (true) { Thread.Sleep(1000); } } }
static void Convert(ExchangeApi.Coinbase.REST.OrderBookResponse src, OrderBook dst) { Action <List <ExchangeApi.Coinbase.REST.Order>, SortedDictionary <decimal, decimal> > Cvt = (from, to) => { to.Clear(); foreach (var order in from) { if (to.ContainsKey(order.Price)) { to[order.Price] += order.Quantity; } else { to[order.Price] = order.Quantity; } } }; dst.Sequence = src.Sequence; Cvt(src.Bids, dst.Bids); Cvt(src.Asks, dst.Asks); }