コード例 #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));
                    });
                }
            }
        }
コード例 #2
0
        private static void Display(OrderBookTop orderBookTop)
        {
            lock (_sync)
            {
                _orderBookTops[orderBookTop.Symbol] = orderBookTop;

                if (_displayTask.IsCompleted)
                {
                    // Delay to allow multiple data updates between display updates.
                    _displayTask = Task.Delay(100)
                                   .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})");
                            Console.WriteLine();
                        }

                        Console.WriteLine(message);
                    });
                }
            }
        }
コード例 #3
0
ファイル: Program.cs プロジェクト: martijnspaan/Binance
 internal static void Display(OrderBookTop top)
 {
     lock (ConsoleSync)
     {
         Console.WriteLine($"  {top.Symbol.PadLeft(8)}  -  Bid: {top.Bid.Price.ToString("0.00000000").PadLeft(13)} (qty: {top.Bid.Quantity})   |   Ask: {top.Ask.Price.ToString("0.00000000").PadLeft(13)} (qty: {top.Ask.Quantity})");
     }
 }
コード例 #4
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));
        }
コード例 #5
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>()));
 }
コード例 #6
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}");
            }
        }
コード例 #7
0
        public virtual string Serialize(OrderBookTop orderBookTop)
        {
            Throw.IfNull(orderBookTop, nameof(orderBookTop));

            var jObject = new JObject
            {
                new JProperty(KeySymbol, orderBookTop.Symbol),
                new JProperty(KeyBidPrice, orderBookTop.Bid.Price.ToString(CultureInfo.InvariantCulture)),
                new JProperty(KeyBidQuantity, orderBookTop.Bid.Quantity.ToString(CultureInfo.InvariantCulture)),
                new JProperty(KeyAskPrice, orderBookTop.Ask.Price.ToString(CultureInfo.InvariantCulture)),
                new JProperty(KeyAskQuantity, orderBookTop.Ask.Quantity.ToString(CultureInfo.InvariantCulture))
            };

            return(jObject.ToString(Formatting.None));
        }
コード例 #8
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 = new OrderBookTop(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);
        }
コード例 #9
0
        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));
        }
コード例 #10
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);
        }
コード例 #11
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);
                }
            }
        }
コード例 #12
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}");
            }
        }
コード例 #13
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);
            }
        }
コード例 #14
0
 /// <summary>
 /// Get whether a price is the best bid or ask price.
 /// </summary>
 /// <param name="orderBookTop">The order book top.</param>
 /// <param name="price">The price.</param>
 /// <returns></returns>
 public static bool IsBestPrice(this OrderBookTop orderBookTop, decimal price)
 {
     return(price == orderBookTop.Bid.Price || price == orderBookTop.Ask.Price);
 }
コード例 #15
0
        /// <summary>
        /// Get the mid-market price between the best (top) ask and bid prices.
        /// </summary>
        /// <param name="top"></param>
        /// <returns></returns>
        public static decimal MidMarketPrice(this OrderBookTop top)
        {
            Throw.IfNull(top, nameof(top));

            return((top.Ask.Price + top.Bid.Price) / 2);
        }
コード例 #16
0
        /// <summary>
        /// Get the price difference between the best (top) ask and bid prices.
        /// </summary>
        /// <param name="top"></param>
        /// <returns></returns>
        public static decimal Spread(this OrderBookTop top)
        {
            Throw.IfNull(top, nameof(top));

            return(top.Ask.Price - top.Bid.Price);
        }