/// <summary>
        /// The DI constructor.
        /// </summary>
        /// <param name="api"></param>
        /// <param name="stream"></param>
        /// <param name="onError"></param>
        public BinanceWebSocketStreamController(IBinanceApi api, IWebSocketStream stream, Action <Exception> onError = null)
            : base(stream, onError)
        {
            Throw.IfNull(api, nameof(api));

            _api = api;
        }
        /// <summary>
        /// Get older (non-compressed) trades.
        /// </summary>
        /// <param name="api"></param>
        /// <param name="user"></param>
        /// <param name="symbol"></param>
        /// <param name="fromId"></param>
        /// <param name="limit"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        public static Task <IEnumerable <Trade> > GetTradesFromAsync(this IBinanceApi api, IBinanceApiUser user, string symbol, long fromId, int limit = default, CancellationToken token = default)
        {
            Throw.IfNull(api, nameof(api));
            Throw.IfNull(user, nameof(user));

            return(api.GetTradesFromAsync(user.ApiKey, symbol, fromId, limit, token));
        }
        /// <summary>
        /// Get all symbols.
        /// </summary>
        /// <param name="api"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        public static async Task <IEnumerable <string> > SymbolsAsync(this IBinanceApi api, CancellationToken token = default)
        {
            Throw.IfNull(api, nameof(api));

            return((await api.GetPricesAsync(token).ConfigureAwait(false))
                   .Select(p => p.Symbol));
        }
        /// <summary>
        /// Get the most recent trades from trade (EXCLUSIVE).
        /// </summary>
        /// <param name="api"></param>
        /// <param name="trade"></param>
        /// <param name="limit"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        public static Task <IEnumerable <AggregateTrade> > GetAggregateTradesAsync(this IBinanceApi api, AggregateTrade trade, int limit = default, CancellationToken token = default)
        {
            Throw.IfNull(api, nameof(api));
            Throw.IfNull(trade, nameof(trade));

            return(api.GetAggregateTradesFromAsync(trade.Symbol, trade.Id + 1, limit, token));
        }
Beispiel #5
0
        /// <summary>
        /// Update the symbol cache and asset cache.
        /// </summary>
        /// <param name="api"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        public static async Task UpdateCacheAsync(IBinanceApi api, CancellationToken token = default)
        {
            var symbols = await api.GetSymbolsAsync(token)
                          .ConfigureAwait(false);

            Cache.Clear();
            Cache.Set(symbols);
            AddCacheRedirections();

            var assets = new List <Asset>();

            foreach (var symbol in symbols)
            {
                if (!assets.Contains(symbol.BaseAsset))
                {
                    assets.Add(symbol.BaseAsset);
                }

                if (!assets.Contains(symbol.QuoteAsset))
                {
                    assets.Add(symbol.QuoteAsset);
                }
            }

            Asset.Cache.Clear();
            Asset.Cache.Set(assets);
            Asset.AddCacheRedirections();
        }
Beispiel #6
0
        /// <summary>
        /// Update the symbol cache and asset cache.
        /// </summary>
        /// <param name="api"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        public static async Task UpdateCacheAsync(IBinanceApi api, CancellationToken token = default)
        {
            var symbols = await api.GetSymbolsAsync(token)
                          .ConfigureAwait(false);

            UpdateCache(symbols);
        }
        /// <summary>
        /// The DI constructor.
        /// </summary>
        /// <param name="api"></param>
        /// <param name="stream"></param>
        /// <param name="logger"></param>
        public BinanceWebSocketStreamController(IBinanceApi api, IBinanceWebSocketStream stream, ILogger <BinanceWebSocketStreamController> logger = null)
            : base(stream, logger)
        {
            Throw.IfNull(api, nameof(api));

            _api = api;
        }
Beispiel #8
0
        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="api">The Binance API.</param>
        /// <param name="client">The WebSocket client.</param>
        /// <param name="options">The options.</param>
        /// <param name="logger">The logger.</param>
        public UserDataWebSocketClient(IBinanceApi api, IWebSocketStream webSocket, IOptions <UserDataWebSocketClientOptions> options = null, ILogger <UserDataWebSocketClient> logger = null)
            : base(webSocket, logger)
        {
            Throw.IfNull(api, nameof(api));
            Throw.IfNull(webSocket, nameof(webSocket));

            _api     = api;
            _options = options?.Value;

            webSocket.Client.Open += (s, e) =>
            {
                var period = _options?.KeepAliveTimerPeriod ?? KeepAliveTimerPeriodDefault;
                period = Math.Min(Math.Max(period, KeepAliveTimerPeriodMin), KeepAliveTimerPeriodMax);

                _keepAliveTimer = new Timer(OnKeepAliveTimer, CancellationToken.None, period, period);
            };

            webSocket.Client.Close += async(s, e) =>
            {
                _keepAliveTimer.Dispose();

                foreach (var _ in _listenKeys)
                {
                    await _api.UserStreamCloseAsync(_.Key, _.Value, CancellationToken.None)
                    .ConfigureAwait(false);
                }
            };
        }
Beispiel #9
0
        /// <summary>
        /// Get current server time.
        /// </summary>
        /// <param name="api"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        public static async Task <DateTime> GetTimeAsync(this IBinanceApi api, CancellationToken token = default)
        {
            Throw.IfNull(api, nameof(api));

            var timestamp = await api.GetTimestampAsync(token).ConfigureAwait(false);

            return(DateTimeOffset.FromUnixTimeMilliseconds(timestamp).UtcDateTime);
        }
 public BinanceDataFacade(IBinanceApi api, ICandlestickRepository candlestickRepository, IEnumerable <string> onlySymbols, IEnumerable <string> excludeSymbols, string startSymbol)
 {
     _api = api;
     _candlestickRepository = candlestickRepository;
     _onlySymbols           = onlySymbols;
     _excludeSymbols        = excludeSymbols;
     _startSymbol           = startSymbol;
 }
        /// <summary>
        /// Get current server time.
        /// </summary>
        /// <param name="api"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        public static async Task <DateTime> GetTimeAsync(this IBinanceApi api, CancellationToken token = default)
        {
            Throw.IfNull(api, nameof(api));

            var timestamp = await api.GetTimestampAsync(token).ConfigureAwait(false);

            return(timestamp.ToDateTime());
        }
        /// <summary>
        /// ctor.
        /// </summary>
        /// <param name="binanceApi">API client to be used for API calls.</param>
        /// <param name="loadTradingRules">Optional parameter to skip loading trading rules.</param>
        public BinanceClient(IBinanceApi binanceApi, bool loadTradingRules = false) : base(binanceApi)
        {
            _bApi = (BinanceApi)binanceApi;

            if (loadTradingRules)
            {
                LoadTradingRules();
            }
        }
Beispiel #13
0
        protected WebSocketClientCache(IBinanceApi api, TClient client, ILogger logger = null)
        {
            Throw.IfNull(api, nameof(api));
            Throw.IfNull(client, nameof(client));

            Api    = api;
            Client = client;
            Logger = logger;
        }
        public BinanceApiTest()
        {
            // Configure services.
            var serviceProvider = new ServiceCollection()
                                  .AddBinance().BuildServiceProvider();

            // Get IBinanceApi service.
            _api = serviceProvider.GetService <IBinanceApi>();
        }
Beispiel #15
0
        // ReSharper disable once UnusedMember.Local
        private static async Task <SymbolStatistics[]> Get24HourStatisticsAsync(IBinanceApi api, params string[] symbols)
        {
            var statistics = new List <SymbolStatistics>();

            foreach (var symbol in symbols)
            {
                statistics.Add(await api.Get24HourStatisticsAsync(symbol));
            }

            return(statistics.ToArray());
        }
Beispiel #16
0
 public BinanceWebsocketService(BinanceConfig config,
                                IBinanceApi binanceApi,
                                IBinanceCacheService cache,
                                IBinanceSubscriberService subscriber)
 {
     _config     = config;
     _binanceApi = binanceApi;
     _cache      = cache;
     _subscriber = subscriber;
     _semaphore  = new Semaphore(1, 1);
 }
Beispiel #17
0
        public PriceRange(IBinanceApi api, string symbol, decimal multiplierUp, decimal multiplierDown, decimal increment)
            : base(0, 0, increment)
        {
            Throw.IfNull(api, nameof(api));
            Throw.IfNullOrWhiteSpace(symbol, nameof(symbol));

            _api    = api;
            _symbol = symbol;

            MultiplierUp   = multiplierUp;
            MultiplierDown = multiplierDown;
        }
 public BinanceWebsocketService(BinanceConfig config,
                                IBinanceApi binanceApi,
                                IBinanceCacheService cache,
                                IServiceProvider serviceProvider,
                                ILogger <IBinanceWebsocketService> log)
 {
     _config     = config;
     _binanceApi = binanceApi;
     _cache      = cache;
     _subscriber = serviceProvider.GetService <IBinanceSubscriberService>();
     _log        = log;
 }
Beispiel #19
0
        public BinanceService(BinanceConfig config,
                              DatabaseService databaseService,
                              GeneralConfig generalConfig,
                              IBinanceApi binanceApi,
                              ILogger <BinanceService> log)
        {
            _config          = config;
            _databaseService = databaseService;
            _generalConfig   = generalConfig;
            _log             = log;

            _client = binanceApi;
            _client.HttpClient.RateLimiter.Configure(TimeSpan.FromMinutes(1), 200);
        }
        /// <summary>
        /// Get aggregate/compressed trades within a time interval (INCLUSIVE).
        /// </summary>
        /// <param name="api"></param>
        /// <param name="symbol"></param>
        /// <param name="startTime"></param>
        /// <param name="endTime"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        public static Task <IEnumerable <AggregateTrade> > GetAggregateTradesAsync(this IBinanceApi api, string symbol, DateTime startTime, DateTime endTime, CancellationToken token = default)
        {
            Throw.IfNull(api, nameof(api));

            if (startTime.Kind != DateTimeKind.Utc)
            {
                throw new ArgumentException("Date/Time must be UTC.", nameof(startTime));
            }
            if (endTime.Kind != DateTimeKind.Utc)
            {
                throw new ArgumentException("Date/Time must be UTC.", nameof(endTime));
            }

            return(GetAggregateTradesAsync(api, symbol, (new DateTimeOffset(startTime).ToUnixTimeMilliseconds(), new DateTimeOffset(endTime).ToUnixTimeMilliseconds()), token));
        }
        public BinanceService(BinanceConfig config,
                              DatabaseService databaseService,
                              CryptoCompareApiService cryptoCompareService,
                              IServiceProvider serviceProvider,
                              GeneralConfig generalConfig,
                              IBinanceApi binanceApi,
                              ILogger <BinanceService> log)
        {
            _config                  = config;
            _databaseService         = databaseService;
            _cryptoCompareService    = cryptoCompareService;
            _binanceWebsocketService = serviceProvider.GetService <IBinanceWebsocketService>();
            _generalConfig           = generalConfig;
            _log = log;

            _client = binanceApi;
            _client.HttpClient.RateLimiter.Configure(TimeSpan.FromMinutes(1), 200);
        }
Beispiel #22
0
 /// <summary>
 /// The DI constructor.
 /// </summary>
 /// <param name="api">The Binance api (required).</param>
 /// <param name="client">The JSON client (required).</param>
 /// <param name="logger">The logger (optional).</param>
 public OrderBookCache(IBinanceApi api, IDepthClient client, ILogger <OrderBookCache> logger = null)
     : base(api, client, logger)
 {
 }
Beispiel #23
0
        public static async Task Main(string[] args)
        {
            // Un-comment to run...
            //await AccountBalancesExample.ExampleMain(args);
            //await MinimalWithDependencyInjection.ExampleMain(args);
            //await MinimalWithoutDependencyInjection.ExampleMain(args);
            //await SerializationExample.ExampleMain(args);

            var cts = new CancellationTokenSource();

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

                // Configure services.
                ServiceProvider = new ServiceCollection()
                                  .AddBinance()
                                  .AddOptions()
                                  .AddLogging(builder => builder.SetMinimumLevel(LogLevel.Trace))
                                  .Configure <BinanceApiOptions>(Configuration.GetSection("ApiOptions"))
                                  .Configure <UserDataWebSocketClientOptions>(Configuration.GetSection("UserClientOptions"))
                                  .BuildServiceProvider();

                // Configure logging.
                ServiceProvider
                .GetService <ILoggerFactory>()
                .AddConsole(Configuration.GetSection("Logging").GetSection("Console"))
                .AddFile(Configuration.GetSection("Logging").GetSection("File"));

                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>();

                // 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 DisableLiveTask();

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

                User?.Dispose();

                lock (ConsoleSync)
                {
                    Console.WriteLine();
                    Console.WriteLine("  ...press any key to close window.");
                    Console.ReadKey(true);
                }
            }
        }
Beispiel #24
0
 /// <summary>
 /// Constructor.
 /// </summary>
 /// <param name="api">The Binance API.</param>
 /// <param name="client">The WebSocket client.</param>
 /// <param name="options">The options.</param>
 /// <param name="logger">The logger.</param>
 public UserDataWebSocketClient(IBinanceApi api, IWebSocketClient client, IOptions <UserDataWebSocketClientOptions> options = null, ILogger <UserDataWebSocketClient> logger = null)
     : base(client, logger)
 {
     _api     = api;
     _options = options?.Value;
 }
Beispiel #25
0
 public BinanceExchangeApi()
 {
     binanceApi = new BinanceApi();
 }
Beispiel #26
0
 /// <summary>
 /// The DI constructor.
 /// </summary>
 /// <param name="api">The Binance api (required).</param>
 /// <param name="client">The JSON client (required).</param>
 /// <param name="logger">The logger (optional).</param>
 public AccountInfoCache(IBinanceApi api, IUserDataClient client, ILogger <AccountInfoCache> logger = null)
     : base(api, client, logger)
 {
 }
Beispiel #27
0
 public TradeCache(IBinanceApi api, ITradeWebSocketClient client, ILogger <TradeCache> logger = null)
     : base(api, client, logger)
 {
     _trades = new Queue <Trade>();
 }
Beispiel #28
0
 /// <summary>
 /// The DI constructor.
 /// </summary>
 /// <param name="api">The Binance api (required).</param>
 /// <param name="client">The JSON client (required).</param>
 /// <param name="logger">The logger (optional).</param>
 public SymbolStatisticsCache(IBinanceApi api, ISymbolStatisticsClient client, ILogger <SymbolStatisticsCache> logger = null)
     : base(api, client, logger)
 {
 }
Beispiel #29
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);
                }
            }
        }
 /// <summary>
 /// Get aggregate/compressed trades within a time interval (INCLUSIVE).
 /// </summary>
 /// <param name="api"></param>
 /// <param name="symbol"></param>
 /// <param name="timeInterval"></param>
 /// <param name="token"></param>
 /// <returns></returns>
 public static Task <IEnumerable <AggregateTrade> > GetAggregateTradesAsync(this IBinanceApi api, string symbol, (long, long) timeInterval, CancellationToken token = default)