private void BinanceWebsocketPublic()
 {
     var successDepth = m_socketClient.SubscribeToDepthStream("bnbbtc", (data) =>
     {
         // handle data
     });
     var successTrades = m_socketClient.SubscribeToTradesStream("bnbbtc", (data) =>
     {
         // handle data
     });
     var successKline = m_socketClient.SubscribeToKlineStream("bnbbtc", KlineInterval.OneMinute, (data) =>
     {
         // handle data
     });
     var successSymbol = m_socketClient.SubscribeToSymbolTicker("bnbbtc", (data) =>
     {
         // handle data
     });
     var successSymbols = m_socketClient.SubscribeToAllSymbolTicker((data) =>
     {
         // handle data
     });
     var successOrderBook = m_socketClient.SubscribeToPartialBookDepthStream("bnbbtc", 10, (data) =>
     {
         // handle data
     });
 }
示例#2
0
        public void UnsubscribingAll_Should_CloseAllSockets()
        {
            // arrange
            int closed = 0;
            var socket = new Mock <IWebsocket>();

            socket.Setup(s => s.Close()).Raises(s => s.OnClose += null, new ClosedEventArgs(0, "", true));
            socket.Setup(s => s.Connect());
            socket.Setup(s => s.Url).Returns("test");
            socket.Setup(s => s.SetEnabledSslProtocols(It.IsAny <System.Security.Authentication.SslProtocols>()));
            socket.Object.OnClose += (sender, args) =>
            {
                closed++;
            };

            var factory = new Mock <IWebsocketFactory>();

            factory.Setup(s => s.CreateWebsocket(It.IsAny <string>())).Returns(socket.Object);

            var client = new BinanceSocketClient {
                SocketFactory = factory.Object
            };

            client.SubscribeToTradesStream("test", (data) => { });
            client.SubscribeToDepthStream("test", (data) => { });

            // act
            client.UnsubscribeAllStreams();

            // assert
            Assert.IsTrue(closed == 2);
        }
示例#3
0
        public void UnsubscribingStream_Should_CloseTheSocket()
        {
            // arrange
            bool closed = false;
            var  socket = new Mock <IWebsocket>();

            socket.Setup(s => s.Close()).Returns(Task.Run(() => Thread.Sleep(1))).Raises(s => s.OnClose += null);
            socket.Setup(s => s.Connect()).Returns(Task.FromResult(true));
            socket.Setup(s => s.SetEnabledSslProtocols(It.IsAny <System.Security.Authentication.SslProtocols>()));
            socket.Object.OnClose += () =>
            {
                closed = true;
            };

            var factory = new Mock <IWebsocketFactory>();

            factory.Setup(s => s.CreateWebsocket(It.IsAny <Log>(), It.IsAny <string>())).Returns(socket.Object);

            var client = new BinanceSocketClient {
                SocketFactory = factory.Object
            };
            var subscription = client.SubscribeToTradesStream("test", (data) => { });

            // act
            client.UnsubscribeFromStream(subscription.Data);

            // assert
            Assert.IsTrue(closed);
        }
        public void StartProcessingLiveTrades()
        {
            if (_isStarted)
            {
                throw new InvalidOperationException($"{nameof(TradeProcessingService)} was already started processing live trades.");
            }

            _isStarted = true;
            _logger.Debug("Starting processing live trades.");
            _tradeRegistrar.UserTraded += OnUserTraded;
            var symbolPair = SymbolPair.Create(_config.FirstSymbol, _config.SecondSymbol);

            _client.SubscribeToTradesStream(symbolPair.ToString(), trade =>
            {
                var ping = (DateTime.UtcNow - trade.TradeTime).TotalSeconds;
                if (ping > _config.Limiters.MaximalAllowedTradeSyncSeconds / 2 ||
                    ping < _config.Limiters.MaximalAllowedTradeSyncSeconds / -2)
                {
                    _logger.Warning($"Detected trade sync time downgrade with ping {ping} seconds. Try synchronizing machine time or checking the config value with name: {nameof(_config.Limiters.MaximalAllowedTradeSyncSeconds)}");
                }

                if (trade.Quantity <= _config.Limiters.MinimalTradeQuantity)
                {
                    return;
                }

                _logger.Verbose($"Detected trade with Id {trade.TradeId}");
                _tradeRegistrar.RegisterTrade(trade.ToTradeModel(symbolPair));
            });
        }
示例#5
0
        public void Subcribe(string pair)
        {
            var symbolTtradeSubscription = _socketClient.SubscribeToTradesStream(pair, _ => ProduceEvent(_));

            if (symbolTtradeSubscription.Success)
            {
                symbolTtradeSubscription.Data.ConnectionLost += Data_ConnectionLost;
                Console.WriteLine("Subcsribed succesfully");
            }
            else
            {
                Console.WriteLine(symbolTtradeSubscription.Error.Message);
                Subcribe("WAVESBTC");
            }
        }
示例#6
0
        public void SubscribingToTradeStream_Should_TriggerWhenTradeStreamMessageIsReceived()
        {
            // arrange
            var socket = new Mock <IWebsocket>();

            socket.Setup(s => s.Close());
            socket.Setup(s => s.Connect()).Returns(Task.FromResult(true));
            socket.Setup(s => s.SetEnabledSslProtocols(It.IsAny <System.Security.Authentication.SslProtocols>()));

            var factory = new Mock <IWebsocketFactory>();

            factory.Setup(s => s.CreateWebsocket(It.IsAny <Log>(), It.IsAny <string>())).Returns(socket.Object);

            BinanceStreamTrade result = null;
            var client = new BinanceSocketClient {
                SocketFactory = factory.Object
            };

            client.SubscribeToTradesStream("test", (test) => result = test);

            var data = new BinanceCombinedStream <BinanceStreamTrade>()
            {
                Stream = "test",
                Data   = new BinanceStreamTrade()
                {
                    Event         = "TestTradeStream",
                    EventTime     = new DateTime(2017, 1, 1),
                    Symbol        = "test",
                    TradeId       = 1000000000000,
                    BuyerIsMaker  = true,
                    BuyerOrderId  = 10000000000000,
                    SellerOrderId = 2000000000000,
                    Price         = 1.1m,
                    Quantity      = 2.2m,
                    TradeTime     = new DateTime(2017, 1, 1)
                }
            };

            // act
            socket.Raise(r => r.OnMessage += null, JsonConvert.SerializeObject(data));

            // assert
            Assert.IsNotNull(result);
            Assert.IsTrue(TestHelpers.PublicInstancePropertiesEqual(data.Data, result));
        }
示例#7
0
        private void SubscribeUserStream()
        {
            if (string.IsNullOrWhiteSpace(ApiKey) || string.IsNullOrWhiteSpace(ApiSecret))
            {
                return;
            }

            Task.Run(() =>
            {
                using (var client = new BinanceClient())
                {
                    var startOkay = client.StartUserStream();
                    if (!startOkay.Success)
                    {
                        messageBoxService.ShowMessage($"Error Starting UserStream.\n{startOkay.Error.Message}", $"Error {startOkay.Error.Code}", MessageBoxButton.OK, MessageBoxImage.Error);
                    }
                    else
                    {
                        binanceSocketClient.SubscribeToAccountUpdateStream(startOkay.Data.ListenKey, OnAccountUpdate);
                        binanceSocketClient.SubscribeToOrderUpdateStream(startOkay.Data.ListenKey, OnOrderUpdate);
                        binanceSocketClient.SubscribeToTradesStream(startOkay.Data.ListenKey, OnTradesUpdate);
                    }

                    var accountResult = client.GetAccountInfo();
                    if (accountResult.Success)
                    {
                        Assets = new ObservableCollection <AssetViewModel>(accountResult.Data.Balances.Where(b => b.Free != 0 || b.Locked != 0).Select(b => new AssetViewModel()
                        {
                            Asset = b.Asset, Free = b.Free, Locked = b.Locked
                        }).ToList());
                        Ledger = new ObservableCollection <LedgerAssetViewModel>(accountResult.Data.Balances.Where(b => b.Free != 0 || b.Locked != 0 || b.Asset == "MTH").Select(b => new LedgerAssetViewModel()
                        {
                            Asset = b.Asset, Amount = b.Total
                        }).OrderByDescending(ledge => ledge.ValueUSD).ToList());

                        GetLedgerHistory();
                        GetLedgerTrades();
                    }
                    else
                    {
                        messageBoxService.ShowMessage($"Error Getting AccountInfo.\n{accountResult.Error.Message}", $"Error {accountResult.Error.Code}", MessageBoxButton.OK, MessageBoxImage.Error);
                    }
                }
            });
        }
示例#8
0
        public void SubscribingToTradeStream_Should_TriggerWhenTradeStreamMessageIsReceived()
        {
            // arrange
            var socket = new Mock <IWebsocket>();

            socket.Setup(s => s.Close());
            socket.Setup(s => s.Connect());
            socket.Setup(s => s.Url).Returns("test");
            socket.Setup(s => s.SetEnabledSslProtocols(It.IsAny <System.Security.Authentication.SslProtocols>()));

            var factory = new Mock <IWebsocketFactory>();

            factory.Setup(s => s.CreateWebsocket(It.IsAny <string>())).Returns(socket.Object);

            BinanceStreamTrade result = null;
            var client = new BinanceSocketClient {
                SocketFactory = factory.Object
            };

            client.SubscribeToTradesStream("test", (test) => result = test);

            var data = new BinanceStreamTrade()
            {
                Event             = "TestTradeStream",
                EventTime         = new DateTime(2017, 1, 1),
                Symbol            = "test",
                AggregatedTradeId = 1000000000000,
                BuyerIsMaker      = true,
                FirstTradeId      = 10000000000000,
                LastTradeId       = 2000000000000,
                Price             = 1.1,
                Quantity          = 2.2,
                TradeTime         = new DateTime(2017, 1, 1)
            };

            // act
            socket.Raise(r => r.OnMessage += null, new MessagedEventArgs(JsonConvert.SerializeObject(data), false, false, true, new byte[2]));

            // assert
            Assert.IsNotNull(result);
            Assert.IsTrue(Compare.PublicInstancePropertiesEqual(data, result));
        }
示例#9
0
        public void WhenSocketConnectionFailsIt_Should_ReturnAnError()
        {
            // arrange
            var socket = new Mock <IWebsocket>();

            socket.Setup(s => s.Close()).Returns(Task.Run(() => Thread.Sleep(1))).Raises(s => s.OnClose += null);
            socket.Setup(s => s.Connect()).Throws(new Exception("Can't connect"));
            socket.Setup(s => s.SetEnabledSslProtocols(It.IsAny <System.Security.Authentication.SslProtocols>()));

            var factory = new Mock <IWebsocketFactory>();

            factory.Setup(s => s.CreateWebsocket(It.IsAny <Log>(), It.IsAny <string>())).Returns(socket.Object);

            var client = new BinanceSocketClient {
                SocketFactory = factory.Object
            };

            // act
            var result = client.SubscribeToTradesStream("test", (data) => { });

            // assert
            Assert.IsFalse(result.Success);
        }
示例#10
0
        static void Main(string[] args)
        {
            BinanceDefaults.SetDefaultApiCredentials("APIKEY", "APISECRET");
            BinanceDefaults.SetDefaultLogVerbosity(LogVerbosity.Debug);
            BinanceDefaults.SetDefaultLogOutput(Console.Out);

            using (var client = new BinanceClient())
                using (var socketClient = new BinanceSocketClient())
                {
                    // Public
                    var ping          = client.Ping();
                    var serverTime    = client.GetServerTime();
                    var orderBook     = client.GetOrderBook("BNBBTC", 10);
                    var aggTrades     = client.GetAggregatedTrades("BNBBTC", startTime: DateTime.UtcNow.AddMinutes(-2), endTime: DateTime.UtcNow, limit: 10);
                    var klines        = client.GetKlines("BNBBTC", KlineInterval.OneHour, startTime: DateTime.UtcNow.AddHours(-10), endTime: DateTime.UtcNow, limit: 10);
                    var prices24h     = client.Get24HPrices("BNBBTC");
                    var allPrices     = client.GetAllPrices();
                    var allBookPrices = client.GetAllBookPrices();

                    // Private
                    var openOrders      = client.GetOpenOrders("BNBBTC");
                    var allOrders       = client.GetAllOrders("BNBBTC");
                    var testOrderResult = client.PlaceTestOrder("BNBBTC", OrderSide.Buy, OrderType.Limit, TimeInForce.GoodTillCancel, 1, 1);
                    var queryOrder      = client.QueryOrder("BNBBTC", allOrders.Data[0].OrderId);
                    var orderResult     = client.PlaceOrder("BNBBTC", OrderSide.Sell, OrderType.Limit, TimeInForce.GoodTillCancel, 10, 0.0002);
                    var cancelResult    = client.CancelOrder("BNBBTC", orderResult.Data.OrderId);
                    var accountInfo     = client.GetAccountInfo();
                    var myTrades        = client.GetMyTrades("BNBBTC");


                    // Withdrawal/deposit
                    var withdrawalHistory = client.GetWithdrawHistory();
                    var depositHistory    = client.GetDepositHistory();
                    var withdraw          = client.Withdraw("ASSET", "ADDRESS", 0);


                    // Streams
                    var successDepth = socketClient.SubscribeToDepthStream("bnbbtc", (data) =>
                    {
                        // handle data
                    });
                    var successTrades = socketClient.SubscribeToTradesStream("bnbbtc", (data) =>
                    {
                        // handle data
                    });
                    var successKline = socketClient.SubscribeToKlineStream("bnbbtc", KlineInterval.OneMinute, (data) =>
                    {
                        // handle data
                    });

                    var successStart   = client.StartUserStream();
                    var successAccount = socketClient.SubscribeToAccountUpdateStream(successStart.Data.ListenKey, (data) =>
                    {
                        // handle data
                    });
                    var successOrder = socketClient.SubscribeToOrderUpdateStream(successStart.Data.ListenKey, (data) =>
                    {
                        // handle data
                    });

                    socketClient.UnsubscribeFromStream(successDepth.Data);
                    socketClient.UnsubscribeFromAccountUpdateStream();
                    socketClient.UnsubscribeAllStreams();
                }

            Console.ReadLine();
        }
示例#11
0
        static void Main(string[] args)
        {
            BinanceClient.SetDefaultOptions(new BinanceClientOptions()
            {
                ApiCredentials = new ApiCredentials("APIKEY", "APISECRET"),
                LogVerbosity   = LogVerbosity.Debug,
                LogWriters     = new List <TextWriter> {
                    Console.Out
                }
            });
            BinanceSocketClient.SetDefaultOptions(new BinanceSocketClientOptions()
            {
                ApiCredentials = new ApiCredentials("APIKEY", "APISECRET"),
                LogVerbosity   = LogVerbosity.Debug,
                LogWriters     = new List <TextWriter> {
                    Console.Out
                }
            });

            using (var client = new BinanceClient())
            {
                // Public
                var ping             = client.Ping();
                var exchangeInfo     = client.GetExchangeInfo();
                var serverTime       = client.GetServerTime();
                var orderBook        = client.GetOrderBook("BNBBTC", 10);
                var aggTrades        = client.GetAggregatedTrades("BNBBTC", startTime: DateTime.UtcNow.AddMinutes(-2), endTime: DateTime.UtcNow, limit: 10);
                var klines           = client.GetKlines("BNBBTC", KlineInterval.OneHour, startTime: DateTime.UtcNow.AddHours(-10), endTime: DateTime.UtcNow, limit: 10);
                var price            = client.GetPrice("BNBBTC");
                var prices24h        = client.Get24HPrice("BNBBTC");
                var allPrices        = client.GetAllPrices();
                var allBookPrices    = client.GetAllBookPrices();
                var historicalTrades = client.GetHistoricalTrades("BNBBTC");

                // Private
                var openOrders      = client.GetOpenOrders("BNBBTC");
                var allOrders       = client.GetAllOrders("BNBBTC");
                var testOrderResult = client.PlaceTestOrder("BNBBTC", OrderSide.Buy, OrderType.Limit, 1, price: 1, timeInForce: TimeInForce.GoodTillCancel);
                var queryOrder      = client.QueryOrder("BNBBTC", allOrders.Data[0].OrderId);
                var orderResult     = client.PlaceOrder("BNBBTC", OrderSide.Sell, OrderType.Limit, 10, price: 0.0002m, timeInForce: TimeInForce.GoodTillCancel);
                var cancelResult    = client.CancelOrder("BNBBTC", orderResult.Data.OrderId);
                var accountInfo     = client.GetAccountInfo();
                var myTrades        = client.GetMyTrades("BNBBTC");

                // Withdrawal/deposit
                var withdrawalHistory = client.GetWithdrawHistory();
                var depositHistory    = client.GetDepositHistory();
                var withdraw          = client.Withdraw("ASSET", "ADDRESS", 0);
            }

            var socketClient = new BinanceSocketClient();
            // Streams
            var successDepth = socketClient.SubscribeToDepthStream("bnbbtc", (data) =>
            {
                // handle data
            });
            var successTrades = socketClient.SubscribeToTradesStream("bnbbtc", (data) =>
            {
                // handle data
            });
            var successKline = socketClient.SubscribeToKlineStream("bnbbtc", KlineInterval.OneMinute, (data) =>
            {
                // handle data
            });
            var successTicker = socketClient.SubscribeToAllSymbolTicker((data) =>
            {
                // handle data
            });
            var successSingleTicker = socketClient.SubscribeToSymbolTicker("bnbbtc", (data) =>
            {
                // handle data
            });

            string listenKey;

            using (var client = new BinanceClient())
                listenKey = client.StartUserStream().Data.ListenKey;

            var successAccount = socketClient.SubscribeToUserStream(listenKey, data =>
            {
                // Hanlde account info data
            },
                                                                    data =>
            {
                // Hanlde order update info data
            });

            socketClient.UnsubscribeAllStreams();

            Console.ReadLine();
        }