Example #1
0
        public void SubscribeAggregateTrades(string symbol, int limit, Action <TradeEventArgs> callback, Action <Exception> exception, CancellationToken cancellationToken)
        {
            try
            {
                var aggregateTradeCache = new AggregateTradeCache(binanceApi, new AggregateTradeWebSocketClient());
                aggregateTradeCache.Subscribe(symbol, limit, e =>
                {
                    if (cancellationToken.IsCancellationRequested)
                    {
                        aggregateTradeCache.Unsubscribe();
                        return;
                    }

                    try
                    {
                        var aggregateTrades = e.Trades.Select(at => NewAggregateTrade(at)).ToList();
                        callback.Invoke(new TradeEventArgs {
                            Trades = aggregateTrades
                        });
                    }
                    catch (Exception ex)
                    {
                        aggregateTradeCache.Unsubscribe();
                        exception.Invoke(ex);
                    }
                });
            }
            catch (Exception ex)
            {
                exception.Invoke(ex);
            }
        }
Example #2
0
        public Task SubscribeAggregateTrades(string symbol, int limit, Action <TradeEventArgs> callback, Action <Exception> exception, CancellationToken cancellationToken)
        {
            var tcs = new TaskCompletionSource <object>();

            var binanceApi          = new BinanceApi();
            var aggregateTradeCache = new AggregateTradeCache(binanceApi, new AggregateTradeWebSocketClient());

            aggregateTradeCache.Subscribe(symbol, limit, e =>
            {
                if (cancellationToken.IsCancellationRequested)
                {
                    aggregateTradeCache.Unsubscribe();
                    return;
                }

                var aggregateTrades = e.Trades.Select(at => NewAggregateTrade(at)).ToList();

                try
                {
                    callback.Invoke(new TradeEventArgs {
                        Trades = aggregateTrades
                    });
                }
                catch (Exception ex)
                {
                    aggregateTradeCache.Unsubscribe();
                    exception.Invoke(ex);
                    return;
                }
            });

            tcs.SetResult(null);

            return(tcs.Task);
        }
Example #3
0
        public void Unsubscribe()
        {
            var api    = new Mock <IBinanceApi>().Object;
            var client = new Mock <IAggregateTradeClient>().Object;

            var cache = new AggregateTradeCache(api, client);

            // Can call unsubscribe before subscribe or multiple times without fail.
            cache.Unsubscribe();
            cache.Unsubscribe();
        }
Example #4
0
        /// <summary>
        /// Example using manager without DI framework (not recommended).
        /// </summary>
        private static void ExampleMainWithoutDI()
        {
            try
            {
                // Load configuration.
                var configuration = new ConfigurationBuilder()
                                    .SetBasePath(Directory.GetCurrentDirectory())
                                    .AddJsonFile("appsettings.json", true, false)
                                    .Build();

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

                var limit = 25;
                try { limit = Convert.ToInt32(configuration.GetSection("TradeHistory")?["Limit"]); }
                catch { /* ignored */ }

                var loggerFactory = new LoggerFactory();
                loggerFactory.AddFile(configuration.GetSection("Logging:File"));

                var api        = new BinanceApi(BinanceHttpClient.Instance, logger: loggerFactory.CreateLogger <BinanceApi>());
                var client     = new AggregateTradeClient(loggerFactory.CreateLogger <AggregateTradeClient>());
                var webSocket  = new DefaultWebSocketClient(loggerFactory.CreateLogger <DefaultWebSocketClient>());
                var stream     = new BinanceWebSocketStream(webSocket, loggerFactory.CreateLogger <BinanceWebSocketStream>());
                var controller = new BinanceWebSocketStreamController(api, stream);

                controller.Error += (s, e) => HandleError(e.Exception);

                // Initialize manager.
                using (var manager = new AggregateTradeWebSocketClientManager(client, controller, loggerFactory.CreateLogger <AggregateTradeWebSocketClientManager>()))
                {
                    // Initialize cache and link manager (JSON client).
                    var cache = new AggregateTradeCache(api, client, loggerFactory.CreateLogger <AggregateTradeCache>())
                    {
                        Client = manager // use manager as client.
                    };

                    foreach (var symbol in symbols)
                    {
                        // Subscribe to symbol with callback.
                        cache.Subscribe(symbol, limit, Display);

                        lock (_sync)
                        {
                            _message = symbol == symbols.Last()
                                ? $"Symbol: \"{symbol}\" ...press any key to exit."
                                : $"Symbol: \"{symbol}\" ...press any key to continue.";
                        }
                        Console.ReadKey(true);

                        // Unsubscribe from symbol.
                        cache.Unsubscribe();
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                Console.WriteLine();
                Console.WriteLine("  ...press any key to close window.");
                Console.ReadKey(true);
            }
        }