Esempio n. 1
0
        private async void FetchTickers()
        {
            if (!Created || string.IsNullOrWhiteSpace(cmbExchange.SelectedItem as string))
            {
                return;
            }

            this.UseWaitCursor = true;
            try
            {
                var api = await ExchangeAPI.GetExchangeAPIAsync(cmbExchange.SelectedItem as string);

                var tickers = await api.GetTickersAsync();

                StringBuilder b = new StringBuilder();
                foreach (var ticker in tickers)
                {
                    b.AppendFormat("{0,-12}{1}\r\n", ticker.Key, ticker.Value);
                }
                textTickersResult.Text = b.ToString();
            }
            catch (Exception ex)
            {
                textTickersResult.Text = ex.ToString();
            }
            finally
            {
                Invoke(new Action(() => this.UseWaitCursor = false));
            }
        }
Esempio n. 2
0
        public async Task CurrenciesParsedCorrectly()
        {
            var requestMaker = Substitute.For <IAPIRequestMaker>();
            var binance      = await ExchangeAPI.GetExchangeAPIAsync <ExchangeBinanceAPI>();

            binance.RequestMaker = requestMaker;
            requestMaker.MakeRequestAsync("/capital/config/getall", ((ExchangeBinanceAPI)binance).BaseUrlSApi).Returns(Resources.BinanceGetAllAssets);
            IReadOnlyDictionary <string, ExchangeCurrency> currencies = await binance.GetCurrenciesAsync();

            currencies.Should().HaveCount(3);
            currencies.TryGetValue("bnb", out ExchangeCurrency bnb).Should().BeTrue();
            bnb.DepositEnabled.Should().BeFalse();
            bnb.WithdrawalEnabled.Should().BeTrue();
            bnb.MinConfirmations.Should().Be(30);
            bnb.FullName.Should().Be("Binance Coin");
            bnb.Name.Should().Be("BNB");
            bnb.TxFee.Should().Be(0.006m);
            bnb.CoinType.Should().Be("ETH");

            bnb.BaseAddress.Should().BeNullOrEmpty("api does not provide this info");

            currencies.TryGetValue("NEO", out ExchangeCurrency neo).Should().BeTrue();
            neo.Name.Should().Be("NEO");
            neo.FullName.Should().Be("NEO");
            neo.DepositEnabled.Should().BeTrue();
            neo.WithdrawalEnabled.Should().BeFalse();
            neo.TxFee.Should().Be(0);
            neo.MinConfirmations.Should().Be(5);
            neo.CoinType.Should().Be("NEO");
        }
Esempio n. 3
0
        public void GetDataFromMarketWithSpecialChar()
        {
            IExchangeAPI api          = ExchangeAPI.GetExchangeAPIAsync("Bitfinex").Result;
            string       marketTicker = "DOGE:USD";
            DateTime     start        = new DateTime(2021, 12, 1);
            DateTime     end          = DateTime.Today;

            System.Collections.Generic.IEnumerable <MarketCandle> result = api.GetCandlesAsync(marketTicker, 86400, start, end, 1000).Result;
            result.Should().HaveCountGreaterThan(0, "Returned data");
        }
        public async Task <PairRate[]> GetRatesAsync(CancellationToken cancellationToken)
        {
            var result  = new List <PairRate>();
            var symbols = await GetSymbolsAsync(cancellationToken);

            var helper = (ExchangeKrakenAPI)await ExchangeAPI.GetExchangeAPIAsync <ExchangeKrakenAPI>();

            var    normalizedPairsList = symbols.Where(s => !notFoundSymbols.ContainsKey(s)).Select(s => helper.NormalizeMarketSymbol(s)).ToList();
            var    csvPairsList        = string.Join(",", normalizedPairsList);
            JToken apiTickers          = await MakeJsonRequestAsync <JToken>("/0/public/Ticker", null, new Dictionary <string, object> {
                { "pair", csvPairsList }
            }, cancellationToken : cancellationToken);

            var tickers = new List <KeyValuePair <string, ExchangeTicker> >();

            foreach (string symbol in symbols)
            {
                var ticker = ConvertToExchangeTicker(symbol, apiTickers[symbol]);
                if (ticker != null)
                {
                    try
                    {
                        string global  = null;
                        var    mapped1 = _TickerMapping.Where(t => symbol.StartsWith(t.Key, StringComparison.OrdinalIgnoreCase))
                                         .Select(t => new { KrakenTicker = t.Key, PayTicker = t.Value }).SingleOrDefault();
                        if (mapped1 != null)
                        {
                            var p2 = symbol.Substring(mapped1.KrakenTicker.Length);
                            if (_TickerMapping.TryGetValue(p2, out var mapped2))
                            {
                                p2 = mapped2;
                            }
                            global = $"{mapped1.PayTicker}_{p2}";
                        }
                        else
                        {
                            global = await helper.ExchangeMarketSymbolToGlobalMarketSymbolAsync(symbol);
                        }
                        if (CurrencyPair.TryParse(global, out var pair))
                        {
                            result.Add(new PairRate(pair, new BidAsk(ticker.Bid, ticker.Ask)));
                        }
                        else
                        {
                            notFoundSymbols.TryAdd(symbol, symbol);
                        }
                    }
                    catch (ArgumentException)
                    {
                        notFoundSymbols.TryAdd(symbol, symbol);
                    }
                }
            }
            return(result.ToArray());
        }
        private async Task <ExchangeCoinbaseAPI> MakeMockRequestMaker(string response = null)
        {
            var requestMaker = new MockAPIRequestMaker();

            if (response != null)
            {
                requestMaker.GlobalResponse = response;
            }
            var api = (await ExchangeAPI.GetExchangeAPIAsync(ExchangeName.Coinbase) as ExchangeCoinbaseAPI) !;

            api.RequestMaker = requestMaker;
            return(api);
        }
Esempio n. 6
0
        private static async Task <ExchangePoloniexAPI> CreatePoloniexAPI(string response = null)
        {
            var requestMaker = new MockAPIRequestMaker();

            if (response != null)
            {
                requestMaker.GlobalResponse = response;
            }
            var api = (await ExchangeAPI.GetExchangeAPIAsync(ExchangeName.Poloniex) as ExchangePoloniexAPI) !;

            api.RequestMaker = requestMaker;
            return(api);
        }
Esempio n. 7
0
        public void SubmitStopMarginOrder()
        {
            IExchangeAPI         api   = ExchangeAPI.GetExchangeAPIAsync("Bitfinex").Result;
            ExchangeOrderRequest order = new ExchangeOrderRequest
            {
                MarketSymbol = "ADAUSD",
                Amount       = System.Convert.ToDecimal(0.0001),
                IsBuy        = true,
                IsMargin     = true,
                OrderType    = OrderType.Stop,
                StopPrice    = System.Convert.ToDecimal(100)
            };

            api.PrivateApiKey = _pvtKey;
            api.PublicApiKey  = _pubKey;
            ExchangeOrderResult result = api.PlaceOrderAsync(order).Result;
        }
Esempio n. 8
0
        public override async Task RunCommand()
        {
            using var api = await ExchangeAPI.GetExchangeAPIAsync(ExchangeName.Kraken);

            var ticker = await api.GetTickerAsync("XXBTZUSD");

            Console.WriteLine("On the Kraken exchange, 1 bitcoin is worth {0} USD.", ticker.Bid);

            try
            {
                // load API keys created from ExchangeSharpConsole.exe keys mode=create path=keys.bin keylist=public_key,private_key
                api.LoadAPIKeys(KeyPath);
            }
            catch (ArgumentException)
            {
                Console.Error.WriteLine(
                    "Invalid key file.\n" +
                    "Try generating a key file with the \"keys\" utility."
                    );
                Environment.Exit(Program.ExitCodeError);
                return;
            }

            // place limit order for 0.01 bitcoin at ticker.Ask USD
            var result = await api.PlaceOrderAsync(new ExchangeOrderRequest
            {
                Amount       = 0.01m,
                IsBuy        = true,
                Price        = ticker.Ask,
                MarketSymbol = "XXBTZUSD"
            });

            // Kraken is a bit funny in that they don't return the order details in the initial request, so you have to follow up with an order details request
            //  if you want to know more info about the order - most other exchanges don't return until they have the order details for you.
            // I've also found that Kraken tends to fail if you follow up too quickly with an order details request, so sleep a bit to give them time to get
            //  their house in order.
            await Task.Delay(500);

            result = await api.GetOrderDetailsAsync(result.OrderId);

            Console.WriteLine(
                "Placed an order on Kraken for 0.01 bitcoin at {0} USD. Status is {1}. Order id is {2}.",
                ticker.Ask, result.Result, result.OrderId
                );
        }
Esempio n. 9
0
        public override async Task RunCommand()
        {
            long total = 0;

            await TraderExchangeExport.ExportExchangeTrades(
                await ExchangeAPI.GetExchangeAPIAsync(ExchangeName),
                MarketSymbol,
                Path,
                DateTime.Parse(SinceDateString, CultureInfo.InvariantCulture),
                count =>
            {
                total = count;
                Console.WriteLine($"Exporting {ExchangeName}: {total}");
            }
                );

            Console.WriteLine($"Finished Exporting {ExchangeName}: {total}");
        }
        public async Task <ExchangeAPI> ConstructClient()
        {
            var data = GetData();

            var result = await ExchangeAPI.GetExchangeAPIAsync(data.ExchangeName);

            if (result is ExchangeAPI api)
            {
                if (!string.IsNullOrEmpty(data.OverrideUrl))
                {
                    api.BaseUrl = data.OverrideUrl;
                }

                api.LoadAPIKeysUnsecure(data.PublicKey, data.PrivateKey, data.PassPhrase);
                return(api);
            }

            return(null);
        }
Esempio n. 11
0
        protected async Task RunWebSocket(string exchangeName, Func <IExchangeAPI, Task <IWebSocket> > getWebSocket)
        {
            using var api = await ExchangeAPI.GetExchangeAPIAsync(exchangeName);

            Console.WriteLine("Connecting web socket to {0}...", api.Name);

            IWebSocket socket = null;
            var        tcs    = new TaskCompletionSource <bool>();

            // ReSharper disable once AccessToModifiedClosure
            var disposable = KeepSessionAlive(() =>
            {
                socket?.Dispose();
                tcs.TrySetResult(true);
            });

            try
            {
                socket = await getWebSocket(api);

                socket.Connected += _ =>
                {
                    Console.WriteLine("Web socket connected.");
                    return(Task.CompletedTask);
                };
                socket.Disconnected += _ =>
                {
                    Console.WriteLine("Web socket disconnected.");

                    // ReSharper disable once AccessToDisposedClosure
                    disposable.Dispose();

                    return(Task.CompletedTask);
                };

                await tcs.Task;
            }
            catch
            {
                disposable.Dispose();
                throw;
            }
        }
        public async Task <PairRate[]> GetRatesAsync(CancellationToken cancellationToken)
        {
            await new SynchronizationContextRemover();

            var exchangeAPI = (T)await ExchangeAPI.GetExchangeAPIAsync <T>();

            exchangeAPI.RequestMaker = new HttpClientRequestMaker(exchangeAPI, _httpClient, cancellationToken);
            var rates = await exchangeAPI.GetTickersAsync();

            var exchangeRateTasks = rates
                                    .Where(t => t.Value.Ask != 0m && t.Value.Bid != 0m)
                                    .Select(t => CreateExchangeRate(exchangeAPI, t));

            var exchangeRates = await Task.WhenAll(exchangeRateTasks);

            return(exchangeRates
                   .Where(t => t != null)
                   .ToArray());
        }
Esempio n. 13
0
        public async Task ExchangeGetCreateTest()
        {
            // make sure get exchange api calls serve up the same instance
            var ex1 = await ExchangeAPI.GetExchangeAPIAsync <ExchangeGeminiAPI>();

            var ex2 = await ExchangeAPI.GetExchangeAPIAsync(ExchangeName.Gemini);

            Assert.AreSame(ex1, ex2);
            Assert.IsInstanceOfType(ex2, typeof(ExchangeGeminiAPI));

            // make sure create exchange serves up new instances
            var ex3 = await ExchangeAPI.CreateExchangeAPIAsync <ExchangeGeminiAPI>();

            Assert.AreNotSame(ex3, ex2);

            // make sure a bad exchange name throws correct exception
            await Assert.ThrowsExceptionAsync <ApplicationException>(() =>
            {
                return(ExchangeAPI.GetExchangeAPIAsync("SirExchangeNotAppearingInThisFilm"));
            });
        }
Esempio n. 14
0
 protected Task <IExchangeAPI> GetExchangeInstanceAsync(string exchangeName)
 {
     return(ExchangeAPI.GetExchangeAPIAsync(exchangeName));
 }
Esempio n. 15
0
        public override async Task RunCommand()
        {
            var marketSymbol  = "BTC-USD";
            var marketSymbol2 = "XXBTZUSD";

            IExchangeAPI
                apiCoinbase = await ExchangeAPI.GetExchangeAPIAsync(ExchangeName.Coinbase),
                apiGemini   = await ExchangeAPI.GetExchangeAPIAsync(ExchangeName.Gemini),
                apiKraken   = await ExchangeAPI.GetExchangeAPIAsync(ExchangeName.Kraken),
                apiBitfinex = await ExchangeAPI.GetExchangeAPIAsync(ExchangeName.Bitfinex);

            //TODO: Make this multi-threaded and add parameters
            Console.WriteLine("Use CTRL-C to stop.");

            while (true)
            {
                var ticker = await apiCoinbase.GetTickerAsync(marketSymbol);

                var orders = await apiCoinbase.GetOrderBookAsync(marketSymbol);

                var askAmountSum = orders.Asks.Values.Sum(o => o.Amount);
                var askPriceSum  = orders.Asks.Values.Sum(o => o.Price);
                var bidAmountSum = orders.Bids.Values.Sum(o => o.Amount);
                var bidPriceSum  = orders.Bids.Values.Sum(o => o.Price);

                var ticker2 = await apiGemini.GetTickerAsync(marketSymbol);

                var orders2 = await apiGemini.GetOrderBookAsync(marketSymbol);

                var askAmountSum2 = orders2.Asks.Values.Sum(o => o.Amount);
                var askPriceSum2  = orders2.Asks.Values.Sum(o => o.Price);
                var bidAmountSum2 = orders2.Bids.Values.Sum(o => o.Amount);
                var bidPriceSum2  = orders2.Bids.Values.Sum(o => o.Price);

                var ticker3 = await apiKraken.GetTickerAsync(marketSymbol2);

                var orders3 = await apiKraken.GetOrderBookAsync(marketSymbol2);

                var askAmountSum3 = orders3.Asks.Values.Sum(o => o.Amount);
                var askPriceSum3  = orders3.Asks.Values.Sum(o => o.Price);
                var bidAmountSum3 = orders3.Bids.Values.Sum(o => o.Amount);
                var bidPriceSum3  = orders3.Bids.Values.Sum(o => o.Price);

                var ticker4 = await apiBitfinex.GetTickerAsync(marketSymbol);

                var orders4 = await apiBitfinex.GetOrderBookAsync(marketSymbol);

                var askAmountSum4 = orders4.Asks.Values.Sum(o => o.Amount);
                var askPriceSum4  = orders4.Asks.Values.Sum(o => o.Price);
                var bidAmountSum4 = orders4.Bids.Values.Sum(o => o.Amount);
                var bidPriceSum4  = orders4.Bids.Values.Sum(o => o.Price);

                Console.Clear();
                Console.WriteLine("GDAX: {0,13:N}, {1,15:N}, {2,8:N}, {3,13:N}, {4,8:N}, {5,13:N}", ticker.Last,
                                  ticker.Volume.QuoteCurrencyVolume, askAmountSum, askPriceSum, bidAmountSum, bidPriceSum);
                Console.WriteLine("GEMI: {0,13:N}, {1,15:N}, {2,8:N}, {3,13:N}, {4,8:N}, {5,13:N}", ticker2.Last,
                                  ticker2.Volume.QuoteCurrencyVolume, askAmountSum2, askPriceSum2, bidAmountSum2, bidPriceSum2);
                Console.WriteLine("KRAK: {0,13:N}, {1,15:N}, {2,8:N}, {3,13:N}, {4,8:N}, {5,13:N}", ticker3.Last,
                                  ticker3.Volume.QuoteCurrencyVolume, askAmountSum3, askPriceSum3, bidAmountSum3, bidPriceSum3);
                Console.WriteLine("BITF: {0,13:N}, {1,15:N}, {2,8:N}, {3,13:N}, {4,8:N}, {5,13:N}", ticker4.Last,
                                  ticker4.Volume.QuoteCurrencyVolume, askAmountSum4, askPriceSum4, bidAmountSum4, bidPriceSum4);
                Thread.Sleep(IntervalMs);
            }
        }