/// <summary>
        /// Get all <see cref="IWebSocketPublisherClient"/> clients.
        /// </summary>
        /// <param name="manager"></param>
        /// <returns></returns>
        public static IEnumerable <IWebSocketPublisherClient> Clients(this IBinanceWebSocketClientManager manager)
        {
            Throw.IfNull(manager, nameof(manager));

            yield return(manager.AggregateTradeClient as IWebSocketPublisherClient);

            yield return(manager.CandlestickClient as IWebSocketPublisherClient);

            yield return(manager.DepthClient as IWebSocketPublisherClient);

            yield return(manager.StatisticsClient as IWebSocketPublisherClient);

            yield return(manager.TradeClient as IWebSocketPublisherClient);
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Get all <see cref="IControllerManager"/> managers.
        /// </summary>
        /// <param name="manager"></param>
        /// <returns></returns>
        public static IEnumerable <IControllerManager <IWebSocketStream> > Managers(this IBinanceWebSocketClientManager manager)
        {
            Throw.IfNull(manager, nameof(manager));

            yield return(manager.AggregateTradeClient as IControllerManager <IWebSocketStream>);

            yield return(manager.CandlestickClient as IControllerManager <IWebSocketStream>);

            yield return(manager.DepthClient as IControllerManager <IWebSocketStream>);

            yield return(manager.StatisticsClient as IControllerManager <IWebSocketStream>);

            yield return(manager.TradeClient as IControllerManager <IWebSocketStream>);
        }
Ejemplo n.º 3
0
        public static async Task Main(string[] args)
        {
            // Un-comment to run...
            //await AccountBalancesExample.ExampleMain(args);
            //await AccountBalancesExample.AdvancedExampleMain(args);
            //await MinimalWithDependencyInjection.ExampleMain(args);
            //await MinimalWithoutDependencyInjection.ExampleMain(args);
            //await OrderBookCacheAccountBalanceExample.AdvancedExampleMain(args);
            //await ReadMeExample.ExampleMain(args);


            var cts = new CancellationTokenSource();

            try
            {
                // Load configuration.
                Configuration = new ConfigurationBuilder()
                                .SetBasePath(Directory.GetCurrentDirectory())
                                .AddJsonFile("appsettings.json", true, false)
                                .AddUserSecrets <Program>() // for access to API key and secret.
                                .Build();

                // Configure services.
                ServiceProvider = new ServiceCollection()
                                                                             // ReSharper disable once ArgumentsStyleLiteral
                                  .AddBinance(useSingleCombinedStream: true) // add default Binance services.

                                                                             // Use alternative, low-level, web socket client implementation.
                                                                             //.AddTransient<IWebSocketClient, WebSocket4NetClient>()
                                                                             //.AddTransient<IWebSocketClient, WebSocketSharpClient>()

                                  .AddOptions()
                                  .Configure <BinanceApiOptions>(Configuration.GetSection("ApiOptions"))

                                  .AddLogging(builder => builder.SetMinimumLevel(LogLevel.Trace))
                                  .BuildServiceProvider();

                // Configure logging.
                ServiceProvider
                .GetService <ILoggerFactory>()
                .AddConsole(Configuration.GetSection("Logging:Console"))
                .AddFile(Configuration.GetSection("Logging:File"));
                // NOTE: Using ":" requires Microsoft.Extensions.Configuration.Binder.

                var apiKey = Configuration["BinanceApiKey"]                       // user secrets configuration.
                             ?? Configuration.GetSection("User")["ApiKey"];       // appsettings.json configuration.

                var apiSecret = Configuration["BinanceApiSecret"]                 // user secrets configuration.
                                ?? Configuration.GetSection("User")["ApiSecret"]; // appsettings.json configuration.

                if (string.IsNullOrWhiteSpace(apiKey) || string.IsNullOrWhiteSpace(apiSecret))
                {
                    PrintApiNotice();
                }

                if (!string.IsNullOrEmpty(apiKey))
                {
                    User = ServiceProvider
                           .GetService <IBinanceApiUserProvider>()
                           .CreateUser(apiKey, apiSecret);
                }

                Api = ServiceProvider.GetService <IBinanceApi>();

                ClientManager = ServiceProvider.GetService <IBinanceWebSocketClientManager>();

                ClientManager.Error += (s, e) =>
                {
                    lock (ConsoleSync)
                    {
                        Console.WriteLine();
                        Console.WriteLine($"! Client Manager Error: \"{e.Exception.Message}\"");
                        Console.WriteLine();
                    }
                };

                UserDataManager = ServiceProvider.GetService <IUserDataWebSocketManager>();

                // Instantiate all assembly command handlers.
                foreach (var type in Assembly.GetExecutingAssembly().GetTypes())
                {
                    if (typeof(IHandleCommand).IsAssignableFrom(type) && !type.IsAbstract)
                    {
                        CommandHandlers.Add((IHandleCommand)Activator.CreateInstance(type));
                    }
                }

                await SuperLoopAsync(cts.Token);
            }
            catch (Exception e)
            {
                lock (ConsoleSync)
                {
                    Console.WriteLine($"! FAIL: \"{e.Message}\"");
                    if (e.InnerException != null)
                    {
                        Console.WriteLine($"  -> Exception: \"{e.InnerException.Message}\"");
                    }
                }
            }
            finally
            {
                await DisableLiveTaskAsync();

                cts.Cancel();
                cts.Dispose();

                User?.Dispose();

                ClientManager?.Dispose();

                lock (ConsoleSync)
                {
                    Console.WriteLine();
                    Console.WriteLine("  ...press any key to close window.");
                    Console.ReadKey(true);
                }
            }
        }