Beispiel #1
0
        private static void Display(DepthUpdateEventArgs args)
        {
            var orderBookTop = OrderBookTop.Create(args.Symbol, args.Bids.First(), args.Asks.First());

            lock (_sync)
            {
                _orderBookTops[orderBookTop.Symbol] = orderBookTop;

                if (_displayTask.IsCompleted)
                {
                    // Delay to allow multiple data updates between display updates.
                    _displayTask = Task.Delay(250)
                                   .ContinueWith(_ =>
                    {
                        OrderBookTop[] latestTops;
                        lock (_sync)
                        {
                            latestTops = _orderBookTops.Values.ToArray();
                        }

                        Console.SetCursorPosition(0, 0);

                        foreach (var t in latestTops)
                        {
                            Console.WriteLine($" {t.Symbol.PadLeft(8)}  -  Bid: {t.Bid.Price.ToString("0.00000000").PadLeft(13)} (qty: {t.Bid.Quantity})   |   Ask: {t.Ask.Price.ToString("0.00000000").PadLeft(13)} (qty: {t.Ask.Quantity})".PadRight(119));
                            Console.WriteLine();
                        }

                        Console.WriteLine(_message.PadRight(119));
                    });
                }
            }
        }
Beispiel #2
0
 private static OrderBookTop DeserializeOrderBookTop(JToken jToken)
 {
     return(OrderBookTop.Create(
                jToken[KeySymbol].Value <string>(),
                jToken[KeyBidPrice].Value <decimal>(),
                jToken[KeyBidQuantity].Value <decimal>(),
                jToken[KeyAskPrice].Value <decimal>(),
                jToken[KeyAskQuantity].Value <decimal>()));
 }
Beispiel #3
0
        public void Throws()
        {
            var           symbol      = Symbol.BTC_USDT;
            const decimal bidPrice    = 0.123456789m;
            const decimal bidQuantity = 0.987654321m;
            const decimal askQuantity = 1.987654321m;

            Assert.Throws <ArgumentException>("Price", () => OrderBookTop.Create(symbol, bidPrice, bidQuantity, bidPrice - 0.1m, askQuantity));
        }
Beispiel #4
0
        private static void Display(DepthUpdateEventArgs e)
        {
            var top = OrderBookTop.Create(e.Symbol, e.Bids.First(), e.Asks.First());

            lock (Program.ConsoleSync)
            {
                Console.WriteLine($"  {top.Symbol}  -  Bid: {top.Bid.Price:.00000000}  |  {top.MidMarketPrice():.00000000}  |  Ask: {top.Ask.Price:.00000000}  -  Spread: {top.Spread():.00000000}");
            }
        }
Beispiel #5
0
        public void Properties()
        {
            var           symbol      = Symbol.BTC_USDT;
            const decimal bidPrice    = 0.123456789m;
            const decimal bidQuantity = 0.987654321m;
            const decimal askPrice    = 1.123456789m;
            const decimal askQuantity = 1.987654321m;

            var top = OrderBookTop.Create(symbol, bidPrice, bidQuantity, askPrice, askQuantity);

            Assert.Equal(bidPrice, top.Bid.Price);
            Assert.Equal(bidQuantity, top.Bid.Quantity);

            Assert.Equal(askPrice, top.Ask.Price);
            Assert.Equal(askQuantity, top.Ask.Quantity);
        }
        public void Equality()
        {
            var           symbol      = Symbol.BTC_USDT;
            const decimal bidPrice    = 0.123456789m;
            const decimal bidQuantity = 0.987654321m;
            const decimal askPrice    = 1.123456789m;
            const decimal askQuantity = 1.987654321m;

            var top = OrderBookTop.Create(symbol, bidPrice, bidQuantity, askPrice, askQuantity);

            var serializer = new OrderBookTopSerializer();

            var json = serializer.Serialize(top);

            var other = serializer.Deserialize(json);

            Assert.True(top.Equals(other));
        }
Beispiel #7
0
        public void Serialization()
        {
            var           symbol      = Symbol.BTC_USDT;
            const decimal bidPrice    = 0.123456789m;
            const decimal bidQuantity = 0.987654321m;
            const decimal askPrice    = 1.123456789m;
            const decimal askQuantity = 1.987654321m;

            var top = OrderBookTop.Create(symbol, bidPrice, bidQuantity, askPrice, askQuantity);

            var json = JsonConvert.SerializeObject(top);

            top = JsonConvert.DeserializeObject <OrderBookTop>(json);

            Assert.Equal(bidPrice, top.Bid.Price);
            Assert.Equal(bidQuantity, top.Bid.Quantity);

            Assert.Equal(askPrice, top.Ask.Price);
            Assert.Equal(askQuantity, top.Ask.Quantity);
        }
Beispiel #8
0
        private async void OrderBookTimerCallback(object state)
        {
            //lock (_threadLock)
            {
                try
                {
                    var orderBook = await Program.KucoinApi.GetOrderBookAsync(_kucoinOrderBookSymbol);

                    var top = OrderBookTop.Create(orderBook.Symbol, (orderBook.Bids.First().Price, orderBook.Bids.First().Quantity), (orderBook.Asks.First().Price, orderBook.Asks.First().Quantity));

                    using (var conn = new SQLiteConnection(_pathToDatabase, false))
                    {
                        conn.Insert(new OrderBookSqlite
                        {
                            Timestamp = DateTime.UtcNow,
                            Market    = "Kucoin",
                            Symbol    = _kucoinOrderBookSymbol,
                            DataType  = 82,
                            Data      = JsonConvert.SerializeObject(orderBook),
                            Bid       = (double)top.Bid.Price,
                            Ask       = (double)top.Ask.Price
                        });
                    }

                    lock (Program.ConsoleSync)
                    {
                        Console.WriteLine($"  Kucoin  {top.Symbol}  -  Bid: {top.Bid.Price:.00000000}  |  {top.MidMarketPrice():.00000000}  |  Ask: {top.Ask.Price:.00000000}  -  Spread: {top.Spread():.00000000}");
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.ToString());
                }
                finally
                {
                    _kucoinOrderBookTimer.Change(_kucoinOrderBookPeriod, Timeout.Infinite);
                }
            }
        }
Beispiel #9
0
        private static void OnDepthUpdate(DepthUpdateEventArgs e)
        {
            var top = OrderBookTop.Create(e.Symbol, e.Bids.First(), e.Asks.First());

            using (var conn = new SQLiteConnection(_pathToDatabase, false))
            {
                conn.Insert(new OrderBookSqlite
                {
                    Timestamp = e.Time,
                    Market    = "Binance",
                    Symbol    = e.Symbol,
                    DataType  = 81,
                    Data      = JsonConvert.SerializeObject(e),
                    Bid       = (double)top.Bid.Price,
                    Ask       = (double)top.Ask.Price
                });
            }

            lock (Program.ConsoleSync)
            {
                Console.WriteLine($"  Binance {top.Symbol}  -  Bid: {top.Bid.Price:.00000000}  |  {top.MidMarketPrice():.00000000}  |  Ask: {top.Ask.Price:.00000000}  -  Spread: {top.Spread():.00000000}");
            }
        }
Beispiel #10
0
        public static async Task ExampleMain()
        {
            try
            {
                // Load configuration.
                var configuration = new ConfigurationBuilder()
                                    .SetBasePath(Directory.GetCurrentDirectory())
                                    .AddJsonFile("appsettings.json", true, false)
                                    .Build();

                // Configure services.
                var services = new ServiceCollection()
                               .AddBinance()
                               .AddLogging(builder => builder.SetMinimumLevel(LogLevel.Trace))
                               .BuildServiceProvider();

                // Configure logging.
                services.GetService <ILoggerFactory>()
                .AddFile(configuration.GetSection("Logging:File"));

                // Get configuration settings.
                var symbols = configuration.GetSection("CombinedStreamsExample:Symbols").Get <string[]>()
                              ?? new string[] { Symbol.BTC_USDT };

                Console.Clear(); // clear the display.

                var limit = 5;

                var client = services.GetService <IDepthWebSocketClient>();

                using (var controller = new RetryTaskController())
                {
                    if (symbols.Length == 1)
                    {
                        // Monitor latest candlestick for a symbol and display.
                        controller.Begin(
                            tkn => client.SubscribeAndStreamAsync(symbols[0], evt => Display(OrderBookTop.Create(evt.Symbol, evt.Bids.First(), evt.Asks.First())), tkn),
                            err => Console.WriteLine(err.Message));
                    }
                    else
                    {
                        // Alternative usage (combined streams).
                        client.DepthUpdate += (s, evt) => { Display(OrderBookTop.Create(evt.Symbol, evt.Bids.First(), evt.Asks.First())); };

                        // Subscribe to all symbols.
                        foreach (var symbol in symbols)
                        {
                            client.Subscribe(symbol, limit); // using event instead of callbacks.
                        }

                        // Begin streaming.
                        controller.Begin(
                            tkn => client.StreamAsync(tkn),
                            err => Console.WriteLine(err.Message));
                    }

                    message = "...press any key to continue.";
                    Console.ReadKey(true); // wait for user input.

                    //*//////////////////////////////////////////////////
                    // Example: Unsubscribe/Subscribe after streaming...

                    // Cancel streaming.
                    await controller.CancelAsync();

                    // Unsubscribe a symbol.
                    client.Unsubscribe(symbols[0], limit);

                    // Remove unsubscribed symbol and clear display (application specific).
                    _orderBookTops.Remove(symbols[0]);
                    Console.Clear();

                    // Subscribe to the real Bitcoin :D
                    client.Subscribe(Symbol.BCH_USDT, limit); // a.k.a. BCC.

                    // Begin streaming again.
                    controller.Begin(
                        tkn => client.StreamAsync(tkn),
                        err => Console.WriteLine(err.Message));

                    message = "...press any key to exit.";
                    Console.ReadKey(true); // wait for user input.
                    ///////////////////////////////////////////////////*/
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                Console.WriteLine();
                Console.WriteLine("  ...press any key to close window.");
                Console.ReadKey(true);
            }
        }