private void BinanceWebsocketHandleEvents() { // SUBSCRIBE var sub = m_socketClient.Spot.SubscribeToAllSymbolTickerUpdates(data => { Console.WriteLine("Reveived list update"); }); // HANDLE EVENTS //sub.Data.Closed += () => sub.Data.ConnectionLost += () => { Console.WriteLine("Connection lost"); }; sub.Data.ConnectionRestored += (timeOffline) => { Console.WriteLine($"Connection restored after {timeOffline}"); }; sub.Data.Exception += (e) => { Console.WriteLine("Socket error " + e.Message); }; Thread.Sleep(15000); // UNSUBSCRIBE m_socketClient.Unsubscribe(sub.Data); //UnsubscribeFromStream(sub.Data); // Additionaly, all sockets can be closed with the UnsubscribeAllStreams method. m_socketClient.UnsubscribeAll(); }
public async Task <bool> BinanceSocket() { var binanceStreamTick = new Binance.Net.Objects.BinanceStreamTick(); using (var client = new BinanceSocketClient()) { var success = client.SubscribeToSymbolTickerAsync("LSKBTC", data => { binanceStreamTick = data; }); success.Start(); var result = success.Result; await client.UnsubscribeAll(); } return(true); }
/// <inheritdoc /> protected override async Task <CallResult <UpdateSubscription> > DoStart() { CallResult <UpdateSubscription> subResult; if (_limit == null) { subResult = await _socketClient.FuturesUsdt.SubscribeToOrderBookUpdatesAsync(Symbol, _updateInterval, data => HandleUpdate((BinanceFuturesStreamOrderBookDepth)data)).ConfigureAwait(false); } else { subResult = await _socketClient.FuturesUsdt.SubscribeToPartialOrderBookUpdatesAsync(Symbol, _limit.Value, _updateInterval, data => HandleUpdate((BinanceFuturesStreamOrderBookDepth)data)).ConfigureAwait(false); } if (!subResult) { return(new CallResult <UpdateSubscription>(null, subResult.Error)); } Status = OrderBookStatus.Syncing; if (_limit == null) { var bookResult = await _restClient.FuturesUsdt.Market.GetOrderBookAsync(Symbol, _limit ?? 1000).ConfigureAwait(false); if (!bookResult) { await _socketClient.UnsubscribeAll().ConfigureAwait(false); return(new CallResult <UpdateSubscription>(null, bookResult.Error)); } SetInitialOrderBook(bookResult.Data.LastUpdateId, bookResult.Data.Bids, bookResult.Data.Asks); } else { var setResult = await WaitForSetOrderBook(10000).ConfigureAwait(false); return(setResult ? subResult : new CallResult <UpdateSubscription>(null, setResult.Error)); } return(new CallResult <UpdateSubscription>(subResult.Data, null)); }
protected override async Task DoWork(PairConfig config, CancellationToken stoppingToken) { ExchangeConfig exchangeConfig = await _exchangeConfigProcessor.GetExchangeConfig(Exchange.Code); while (!stoppingToken.IsCancellationRequested) { try { string listenKey = String.Empty; using (BinanceClient client = new BinanceClient()) { listenKey = client.StartUserStream().Data; } using (BinanceSocketClient socketClient = new BinanceSocketClient()) { ConnectionInfo cnInfo = new ConnectionInfo(_settings.Value.BusConnectionString); using (NatsClient natsClient = new NatsClient(cnInfo)) { if (!natsClient.IsConnected) { natsClient.Connect(); } CallResult <UpdateSubscription> successAccount = socketClient.SubscribeToUserDataUpdates(listenKey, accountData => { }, async orderData => { Order order = orderData.ToOrder(); Deal deal = await _dealProcessor.UpdateForOrder(order, config); await natsClient.PubAsJsonAsync(_settings.Value.OrdersQueueName, new Notification <Deal>() { Code = ActionCode.UPDATED.Code, Payload = deal }); }, ocoOrderData => { }, async balancesData => { IEnumerable <Balance> balances = balancesData.Select(x => x.ToBalance()); foreach (Balance balance in balances) { await _balanceProcessor.UpdateOrCreate(balance); } }, onAccountBalanceUpdate => { }); while (!stoppingToken.IsCancellationRequested) { } natsClient.Disconnect(); await socketClient.UnsubscribeAll(); } } } catch (Exception ex) { _logger.LogError(ex.Message); } } }
static void Main(string[] args) { var apikey = ConfigurationManager.AppSettings.Get("apiKey"); var secret = ConfigurationManager.AppSettings.Get("apiKey"); BinanceClient.SetDefaultOptions(new BinanceClientOptions() { ApiCredentials = new ApiCredentials(apikey, secret), LogVerbosity = LogVerbosity.Debug, LogWriters = new List <TextWriter> { Console.Out } }); BinanceSocketClient.SetDefaultOptions(new BinanceSocketClientOptions() { ApiCredentials = new ApiCredentials(apikey, secret), LogVerbosity = LogVerbosity.Debug, LogWriters = new List <TextWriter> { Console.Out } }); using (var client = new BinanceClient()) { // Spot.Market | Spot market info endpoints client.Spot.Market.GetBookPrice("BTCUSDT"); // Spot.Order | Spot order info endpoints client.Spot.Order.GetAllOrders("BTCUSDT"); // Spot.System | Spot system endpoints client.Spot.System.GetExchangeInfo(); // Spot.UserStream | Spot user stream endpoints. Should be used to subscribe to a user stream with the socket client client.Spot.UserStream.StartUserStream(); // Spot.Futures | Transfer to/from spot from/to the futures account + cross-collateral endpoints //client.Spot.Futures.TransferFuturesAccount("ASSET", 1, FuturesTransferType.FromSpotToUsdtFutures); //// FuturesCoin | Coin-M general endpoints //client.FuturesCoin.GetPositionInformation(); //// FuturesCoin.Market | Coin-M futures market endpoints //client.FuturesCoin.Market.GetBookPrices("BTCUSD"); //// FuturesCoin.Order | Coin-M futures order endpoints //client.FuturesCoin.Order.GetMyTrades(); //// FuturesCoin.Account | Coin-M account info //client.FuturesCoin.Account.GetAccountInfo(); //// FuturesCoin.System | Coin-M system endpoints //client.FuturesCoin.System.GetExchangeInfo(); //// FuturesCoin.UserStream | Coin-M user stream endpoints. Should be used to subscribe to a user stream with the socket client //client.FuturesCoin.UserStream.StartUserStream(); //// FuturesUsdt | USDT-M general endpoints //client.FuturesUsdt.GetPositionInformation(); //// FuturesUsdt.Market | USDT-M futures market endpoints //client.FuturesUsdt.Market.GetBookPrices("BTCUSDT"); //// FuturesUsdt.Order | USDT-M futures order endpoints //client.FuturesUsdt.Order.GetMyTrades("BTCUSDT"); //// FuturesUsdt.Account | USDT-M account info //client.FuturesUsdt.Account.GetAccountInfo(); //// FuturesUsdt.System | USDT-M system endpoints //client.FuturesUsdt.System.GetExchangeInfo(); //// FuturesUsdt.UserStream | USDT-M user stream endpoints. Should be used to subscribe to a user stream with the socket client //client.FuturesUsdt.UserStream.StartUserStream(); // General | General/account endpoints client.General.GetAccountInfo(); // Lending | Lending endpoints client.Lending.GetFlexibleProductList(); //// Margin | Margin general/account info //client.Margin.GetMarginAccountInfo(); //// Margin.Market | Margin market endpoints //client.Margin.Market.GetMarginPairs(); //// Margin.Order | Margin order endpoints //client.Margin.Order.GetAllMarginAccountOrders("BTCUSDT"); //// Margin.UserStream | Margin user stream endpoints. Should be used to subscribe to a user stream with the socket client //client.Margin.UserStream.StartUserStream(); //// Margin.IsolatedUserStream | Isolated margin user stream endpoints. Should be used to subscribe to a user stream with the socket client //client.Margin.IsolatedUserStream.StartIsolatedMarginUserStream("BTCUSDT"); //// Mining | Mining endpoints //client.Mining.GetMiningCoinList(); //// SubAccount | Sub account management //client.SubAccount.TransferSubAccount("fromEmail", "toEmail", "asset", 1); //// Brokerage | Brokerage management //client.Brokerage.CreateSubAccountAsync(); //// WithdrawDeposit | Withdraw and deposit endpoints //client.WithdrawDeposit.GetWithdrawalHistory(); } var socketClient = new BinanceSocketClient(); // Spot | Spot market and user subscription methods socketClient.Spot.SubscribeToAllBookTickerUpdates(data => { // Handle data }); // FuturesCoin | Coin-M futures market and user subscription methods socketClient.FuturesCoin.SubscribeToAllBookTickerUpdates(data => { // Handle data }); // FuturesUsdt | USDT-M futures market and user subscription methods socketClient.FuturesUsdt.SubscribeToAllBookTickerUpdates(data => { // Handle data }); // Unsubscribe socketClient.UnsubscribeAll(); Console.ReadLine(); }
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; var successAccount = socketClient.SubscribeToUserStream(listenKey, data => { // Handle account info data }, data => { // Handle order update info data }); socketClient.UnsubscribeAll(); Console.ReadLine(); }
public async Task StopAsync(CancellationToken cancellationToken) { await _socketClient.UnsubscribeAll(); }
/*public async Task UnsubscribeSymbolTickerUpdates() * { * await sock.Unsubscribe(subscription); * }*/ public async Task UnsubscribeAllUpdates() { await sock.UnsubscribeAll(); }