Ejemplo n.º 1
0
        public ActionResult ExchangePairs(string exchange, string baseCurrency)
        {
            var result = new JArray();

            var symbolArray = new JArray();

            IExchangeAPI api           = ExchangeAPI.GetExchangeAPI(exchange);
            var          exchangeCoins = api.GetSymbolsMetadataAsync().Result;

            if (!String.IsNullOrEmpty(baseCurrency))
            {
                exchangeCoins = exchangeCoins.Where(e => e.BaseCurrency.ToLowerInvariant() == baseCurrency.ToLowerInvariant());
            }

            foreach (var coin in exchangeCoins)
            {
                symbolArray.Add(api.ExchangeSymbolToGlobalSymbol(coin.MarketName));
            }

            var baseCurrencyArray      = new JArray();
            var exchangeBaseCurrencies = api.GetSymbolsMetadataAsync().Result.Select(m => m.BaseCurrency).Distinct();

            foreach (var currency in exchangeBaseCurrencies)
            {
                baseCurrencyArray.Add(currency);
            }

            result.Add(symbolArray);
            result.Add(baseCurrencyArray);

            return(new JsonResult(result));
        }
        public static void RunGetOrderHistory(Dictionary <string, string> dict)
        {
            RequireArgs(dict, "exchangeName", "marketSymbol");

            string       exchangeName = dict["exchangeName"];
            IExchangeAPI api          = ExchangeAPI.GetExchangeAPI(exchangeName);
            string       marketSymbol = dict["marketSymbol"];

            Authenticate(api);

            DateTime?startDate = null;

            if (dict.ContainsKey("startDate"))
            {
                startDate = DateTime.Parse(dict["startDate"]).ToUniversalTime();
            }

            var completedOrders = api.GetCompletedOrderDetailsAsync(marketSymbol, startDate).Sync();

            foreach (var completedOrder in completedOrders)
            {
                Console.WriteLine(completedOrder);
            }

            Console.Write("Press enter to exit..");
            Console.ReadLine();
        }
Ejemplo n.º 3
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));
            }
        }
Ejemplo n.º 4
0
        public static string MarketBuy(string symbol, decimal amount, decimal price, ExchangeAPI exchange)
        {
            var order  = CreateOrder(true, amount, OrderType.Market, price, symbol);
            var result = PlaceOrder(exchange, order);

            return(result.ToString());
        }
Ejemplo n.º 5
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");
        }
Ejemplo n.º 6
0
        private static void PerformTests(Dictionary <string, string> dict)
        {
            IExchangeAPI[] apis = ExchangeAPI.GetExchangeAPIDictionary().Values.ToArray();
            foreach (IExchangeAPI api in apis)
            {
                // test all public API for each exchange
                try
                {
                    string symbol = GetSymbol(api);

                    IReadOnlyCollection <string> symbols = api.GetSymbols();
                    Assert(symbols != null && symbols.Count != 0 && symbols.Contains(symbol));

                    ExchangeTrade[] trades = api.GetHistoricalTrades(symbol).ToArray();
                    Assert(trades.Length != 0 && trades[0].Price > 0m && trades[0].Amount > 0m);

                    var book = api.GetOrderBook(symbol);
                    Assert(book.Asks.Count != 0 && book.Bids.Count != 0 && book.Asks[0].Amount > 0m &&
                           book.Asks[0].Price > 0m && book.Bids[0].Amount > 0m && book.Bids[0].Price > 0m);

                    trades = api.GetRecentTrades(symbol).ToArray();
                    Assert(trades.Length != 0 && trades[0].Price > 0m && trades[0].Amount > 0m);

                    var ticker = api.GetTicker(symbol);
                    Assert(ticker != null && ticker.Ask > 0m && ticker.Bid > 0m && ticker.Last > 0m &&
                           ticker.Volume != null && ticker.Volume.PriceAmount > 0m && ticker.Volume.QuantityAmount > 0m);
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Request failed, api: {0}, error: {1}", api, ex);
                }
            }
        }
Ejemplo n.º 7
0
        public string GlobalToExchangeSymbol(string exchange, string symbol)
        {
            IExchangeAPI api            = ExchangeAPI.GetExchangeAPI(exchange);
            string       exchangeSymbol = api.GlobalMarketSymbolToExchangeMarketSymbolAsync(symbol).Result;

            return(exchangeSymbol);
        }
Ejemplo n.º 8
0
        public Scanner(Settings settings)
        {
            _settings = settings;

            switch (_settings.Exchange.ToLowerInvariant())
            {
            case "bitfinex":
                _api = new ExchangeBitfinexAPI();
                break;

            case "bittrex":
                _api = new ExchangeBittrexAPI();
                break;

            case "binance":
                _api = new ExchangeBinanceAPI();
                break;

            case "kraken":
                _api = new ExchangeKrakenAPI();
                break;

            default:
                Console.WriteLine($"Unknown exchange:{_settings.Exchange}");
                return;
            }

            _api.RateLimit = new RateGate(800, TimeSpan.FromSeconds(60d));

            FindCoinsWithEnoughVolume();
        }
Ejemplo n.º 9
0
        public Trade_package(decimal _precent, string _currency, SymbolsDate _buySymbolsDate, SymbolsDate _sellSymbolsDate)
        {
            api             = StaticVariables.api;
            itsBuyArbitrage = true;

            percent         = _precent;
            buySymbolsDate  = _buySymbolsDate;
            sellSymbolsDate = _sellSymbolsDate;
            currency        = _currency;

            buySymbol  = buySymbolsDate.symbole;
            sellSymbol = sellSymbolsDate.symbole;

            minAmountTrade = Math.Max(buySymbolsDate.MinAmount, sellSymbolsDate.MinAmount);
            maxAmountTrade = WalletFunc.GetMaxAmountTrade(buySymbolsDate.orderTrade.request.Price, buySymbolsDate.payment);
            maxAmountTrade = StaticVariables.api.ClampOrderQuantity(buySymbol, maxAmountTrade);
            if (maxAmountTrade < minAmountTrade)
            {
                string warningMessage = String.Format("currency - {0}, buySymbol - {1}, buy.MinAmount - {2}, sellSymbols - {3}, sell.MinAmount- {4}, minAmountTrade - {5}, maxAmountTrade - {6}", currency, buySymbol, buySymbolsDate.MinAmount, sellSymbol, sellSymbolsDate.MinAmount, minAmountTrade, maxAmountTrade);
                PrintTable.PrintConsole(warningMessage);
                PrintFunc.AddLine(StaticVariables.pathWithDate + "WARNING_maxAmount.txt", warningMessage);

                maxAmountTrade = minAmountTrade;
            }
        }
Ejemplo n.º 10
0
        public static void RunGetHistoricalTrades(Dictionary <string, string> dict)
        {
            RequireArgs(dict, "exchangeName", "symbol");

            string       exchangeName = dict["exchangeName"];
            IExchangeAPI api          = ExchangeAPI.GetExchangeAPI(exchangeName);
            string       symbol       = dict["symbol"];

            Console.WriteLine("Showing historical trades for exchange {0}...", exchangeName);
            DateTime?startDate = null;
            DateTime?endDate   = null;

            if (dict.ContainsKey("startDate"))
            {
                startDate = DateTime.Parse(dict["startDate"]).ToUniversalTime();
            }
            if (dict.ContainsKey("endDate"))
            {
                endDate = DateTime.Parse(dict["endDate"]).ToUniversalTime();
            }
            api.GetHistoricalTrades((IEnumerable <ExchangeTrade> trades) =>
            {
                foreach (ExchangeTrade trade in trades)
                {
                    Console.WriteLine("Trade at timestamp {0}: {1}/{2}/{3}", trade.Timestamp.ToLocalTime(), trade.Id, trade.Price, trade.Amount);
                }
                return(true);
            }, symbol, startDate, endDate);
        }
 private static async Task RunWebSocket(Dictionary <string, string> dict, Func <IExchangeAPI, Task <IWebSocket> > func)
 {
     RequireArgs(dict, "exchangeName");
     using (var api = ExchangeAPI.GetExchangeAPI(dict["exchangeName"]))
     {
         if (api == null)
         {
             throw new ArgumentException("Cannot find exchange with name {0}", dict["exchangeName"]);
         }
         try
         {
             Logger.Info("Connecting web socket to {0}...", api.Name);
             using (var socket = await func(api))
             {
                 SetWebSocketEvents(socket);
                 Console.WriteLine("Press any key to quit.");
                 Console.ReadKey();
             }
         }
         catch (Exception ex)
         {
             Logger.Error(ex);
         }
     }
 }
Ejemplo n.º 12
0
        /// <summary>
        /// Loop through all exchanges, get a json string for all symbols
        /// </summary>
        /// <returns></returns>
        private async Task <string> GetAllSymbolsJsonAsync()
        {
            Dictionary <string, string[]> allSymbols = new Dictionary <string, string[]>();
            List <Task> tasks = new List <Task>();

            foreach (ExchangeAPI api in ExchangeAPI.GetExchangeAPIs())
            {
                tasks.Add(Task.Run(async() =>
                {
                    try
                    {
                        string[] symbols = (await api.GetMarketSymbolsAsync()).ToArray();
                        lock (allSymbols)
                        {
                            allSymbols[api.Name] = symbols;
                        }
                    }
                    catch (NotImplementedException)
                    {
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("Failed to get symbols for {0}, error: {1}", api, ex);
                    }
                }));
            }
            await Task.WhenAll(tasks);

            return(JsonConvert.SerializeObject(allSymbols));
        }
Ejemplo n.º 13
0
        public OrderTrade(ExchangeOrderRequest _request)
        {
            done              = false;
            succsseTrade      = false;
            succsseFirstOrder = false;
            itsCanAdded       = true;
            itsMinimumPrice   = false;
            itsCanRevnu       = true;
            itsCanUpdate      = true;
            itsOrderLeft      = false;
            itsFirstOrder     = false;
            amountFilled      = 0;
            AmountFilledDifferentOrderNumber = 0;
            numUpdate = -1;

            Request = _request;
            decimal valueMaxOrMinPrice = _request.Price;  //  TO VIEW Since the default value transfer "by reference" we want to get  here "by Value" because the _request.Price value Will change during the run when we update the Request

            originalMaxOrMinPrice = valueMaxOrMinPrice;
            maxOrMinPrice         = valueMaxOrMinPrice;
            newPrice = valueMaxOrMinPrice;

            api           = StaticVariables.api;
            roundingPrice = StaticVariables.roundingPrice;
        }
Ejemplo n.º 14
0
        public string GlobalToExchangeSymbol(string exchange, string symbol)
        {
            IExchangeAPI api            = ExchangeAPI.GetExchangeAPI(exchange.ToLower());
            string       exchangeSymbol = api.GlobalSymbolToExchangeSymbol(symbol);

            return(exchangeSymbol);
        }
 private static void RunWebSocketTickers(Dictionary <string, string> dict)
 {
     using (var api = ExchangeAPI.GetExchangeAPI(dict["exchangeName"]))
     {
         if (api == null)
         {
             throw new ArgumentException("Cannot find exchange with name {0}", dict["exchangeName"]);
         }
         try
         {
             using (var socket = api.GetTickersWebSocket(freshTickers =>
             {
                 foreach (KeyValuePair <string, ExchangeTicker> kvp in freshTickers)
                 {
                     Console.WriteLine($"market {kvp.Key}, ticker {kvp.Value}");
                 }
             }))
             {
                 Console.WriteLine("Press any key to quit.");
                 Console.ReadKey();
             }
         }
         catch (Exception ex)
         {
             Console.WriteLine("Web socket error: " + ex);
         }
     }
 }
        private static void RunOrderBookWebSocket(Dictionary <string, string> dict)
        {
            RequireArgs(dict, "exchangeName");
            var api = ExchangeAPI.GetExchangeAPI(dict["exchangeName"]);

            if (api == null)
            {
                throw new ArgumentException("Cannot find exchange with name {0}", dict["exchangeName"]);
            }
            var apiSymbols = api.GetSymbols();

            string[] symbols = dict["symbols"].Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
            foreach (string symbol in symbols)
            {
                if (!apiSymbols.Contains(symbol))
                {
                    throw new ArgumentException(string.Format("Symbol {0} does not exist in API {1}, valid symbols: {2}", symbol, api.Name, string.Join(",", apiSymbols.OrderBy(s => s))));
                }
            }

            IDisposable socket = api.GetOrderBookWebSocket(message =>
            {
                //print the top bid and ask with amount
                var topBid = message.Bids.FirstOrDefault();
                var topAsk = message.Asks.FirstOrDefault();
                Console.WriteLine($"[{message.Symbol}:{message.SequenceId}] {topBid.Value.Price} ({topBid.Value.Amount}) | {topAsk.Value.Price} ({topAsk.Value.Amount})");
            }, symbols: symbols);

            Console.WriteLine("Press any key to quit.");
            Console.ReadKey();
            socket.Dispose();
        }
Ejemplo n.º 17
0
        public static void RunGetHistoricalTrades(Dictionary <string, string> dict)
        {
            RequireArgs(dict, "exchangeName", "marketSymbol");

            string       exchangeName = dict["exchangeName"];
            IExchangeAPI api          = ExchangeAPI.GetExchangeAPI(exchangeName);
            string       marketSymbol = dict["marketSymbol"];

            Console.WriteLine("Showing historical trades for exchange {0}...", exchangeName);
            DateTime?startDate = null;
            DateTime?endDate   = null;

            if (dict.ContainsKey("startDate"))
            {
                startDate = DateTime.Parse(dict["startDate"]).ToUniversalTime();
            }
            if (dict.ContainsKey("endDate"))
            {
                endDate = DateTime.Parse(dict["endDate"]).ToUniversalTime();
            }
            //api.GetHistoricalTradesAsync((List<ExchangeTrade> trades) =>
            //{
            //    foreach (ExchangeTrade trade in trades)
            //    {
            //        Console.WriteLine("Trade at timestamp {0}: {1}/{2}/{3}", trade.DateTime.ToLocalTime(), trade.Id, trade.Price, trade.Amount);
            //    }
            //    return true;
            //}, marketSymbol, startDate, endDate).Sync();
        }
        public static void RunGetMarketSymbols(Dictionary <string, string> dict)
        {
            RequireArgs(dict, "exchangeName");
            using (var api = ExchangeAPI.GetExchangeAPI(dict["exchangeName"]))
            {
                if (api == null)
                {
                    throw new ArgumentException("Cannot find exchange with name {0}", dict["exchangeName"]);
                }

                try
                {
                    var marketSymbols = api.GetMarketSymbolsAsync().Sync();

                    foreach (var marketSymbol in marketSymbols)
                    {
                        Console.WriteLine(marketSymbol);
                    }

                    Console.WriteLine("Press any key to quit.");
                    Console.ReadKey();
                }
                catch (Exception ex)
                {
                    Logger.Error(ex);
                }
            }
        }
        public static async Task RunGetMarketSymbols(Dictionary <string, string> dict)
        {
            RequireArgs(dict, "exchangeName");
            using (var api = ExchangeAPI.GetExchangeAPI(dict["exchangeName"]))
            {
                if (api == null)
                {
                    throw new ArgumentException("Cannot find exchange with name {0}", dict["exchangeName"]);
                }

                try
                {
                    var marketSymbols = await api.GetMarketSymbolsAsync();

                    foreach (var marketSymbol in marketSymbols)
                    {
                        Logger.Info(marketSymbol);
                    }

                    WaitForKey();
                }
                catch (Exception ex)
                {
                    Logger.Error(ex);
                }
            }
        }
        public static void RunGetCandles(Dictionary <string, string> dict)
        {
            RequireArgs(dict, "exchangeName", "marketSymbol");
            using (var api = ExchangeAPI.GetExchangeAPI(dict["exchangeName"]))
            {
                if (api == null)
                {
                    throw new ArgumentException("Cannot find exchange with name {0}", dict["exchangeName"]);
                }

                try
                {
                    var marketSymbol = dict["marketSymbol"];
                    var candles      = api.GetCandlesAsync(marketSymbol, 1800, DateTime.UtcNow.AddDays(-12), DateTime.UtcNow).Sync();

                    foreach (var candle in candles)
                    {
                        Console.WriteLine(candle);
                    }

                    Console.WriteLine("Press any key to quit.");
                    Console.ReadKey();
                }
                catch (Exception ex)
                {
                    Logger.Error(ex);
                }
            }
        }
        public static async Task RunGetCandles(Dictionary <string, string> dict)
        {
            RequireArgs(dict, "exchangeName", "marketSymbol");
            using (var api = ExchangeAPI.GetExchangeAPI(dict["exchangeName"]))
            {
                if (api == null)
                {
                    throw new ArgumentException("Cannot find exchange with name {0}", dict["exchangeName"]);
                }

                try
                {
                    var marketSymbol = dict["marketSymbol"];
                    var candles      = await api.GetCandlesAsync(marketSymbol, 1800, CryptoUtility.UtcNow.AddDays(-12), CryptoUtility.UtcNow);

                    foreach (var candle in candles)
                    {
                        Logger.Info(candle.ToString());
                    }

                    WaitForKey();
                }
                catch (Exception ex)
                {
                    Logger.Error(ex);
                }
            }
        }
Ejemplo n.º 22
0
        public BaseExchange BaseExchange(string exchange)
        {
            IExchangeAPI   api           = ExchangeAPI.GetExchangeAPI(exchange.ToLower());
            var            builder       = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("appsettings.json", optional: true);
            IConfiguration configuration = builder.Build();

            ExchangeOptions exchangeOptions = new ExchangeOptions();

            exchangeOptions.Exchange = (Exchange)Enum.Parse(typeof(Exchange), exchange, true);

            string apiKey;
            string apiSecret;

            //Check if there are multiple exchanges in config, else Fallback to single mode
            if (configuration.GetSection("Exchanges").GetSection(exchange) != null)
            {
                apiKey    = configuration.GetSection("Exchanges").GetSection(exchange).GetValue <string>("ApiKey");
                apiSecret = configuration.GetSection("Exchanges").GetSection(exchange).GetValue <string>("ApiSecret");
            }
            else
            {
                apiKey    = configuration.GetValue <string>("ApiKey");
                apiSecret = configuration.GetValue <string>("ApiSecret");
            }

            exchangeOptions.Exchange  = (Exchange)Enum.Parse(typeof(Exchange), exchange, true);
            exchangeOptions.ApiKey    = apiKey;
            exchangeOptions.ApiSecret = apiSecret;

            return(new BaseExchange(exchangeOptions));
        }
Ejemplo n.º 23
0
        public static string LimitSell(string symbol, decimal amount, decimal price, ExchangeAPI exchange)
        {
            var order  = CreateOrder(false, amount, OrderType.Limit, price, symbol);
            var result = PlaceOrder(new ExchangeBinanceAPI(), order);

            return(result.ToString());
        }
Ejemplo n.º 24
0
        public ActionResult BacktesterResults(string exchange, string coinsToBuy, string baseCurrency, string candleSize = "5", string strategy = "all")
        {
            JObject strategies = new JObject();

            List <string> coins = new List <string>();

            if (String.IsNullOrEmpty(coinsToBuy))
            {
                IExchangeAPI api           = ExchangeAPI.GetExchangeAPI(exchange.ToLower());
                var          exchangeCoins = api.GetSymbolsMetadataAsync().Result.Where(m => m.BaseCurrency == baseCurrency);
                foreach (var coin in exchangeCoins)
                {
                    coins.Add(api.ExchangeSymbolToGlobalSymbol(coin.MarketName));
                }
            }
            else
            {
                Char     delimiter       = ',';
                String[] coinsToBuyArray = coinsToBuy.Split(delimiter);
                foreach (var coin in coinsToBuyArray)
                {
                    coins.Add(coin.ToUpper());
                }
            }

            var backtestOptions = new BacktestOptions
            {
                DataFolder   = Global.DataPath,
                Exchange     = (Exchange)Enum.Parse(typeof(Exchange), exchange, true),
                Coins        = coins,
                CandlePeriod = Int32.Parse(candleSize)
            };

            var cts             = new CancellationTokenSource();
            var parallelOptions = new ParallelOptions
            {
                CancellationToken      = cts.Token,
                MaxDegreeOfParallelism = Environment.ProcessorCount
            };

            Parallel.ForEach(BacktestFunctions.GetTradingStrategies(), parallelOptions, async tradingStrategy =>
            {
                if (strategy != "all")
                {
                    var base64EncodedBytes = Convert.FromBase64String(strategy);
                    if (tradingStrategy.Name != Encoding.UTF8.GetString(base64EncodedBytes))
                    {
                        return;
                    }
                }
                var result = await BacktestFunctions.BackTestJson(tradingStrategy, backtestOptions, Global.DataStoreBacktest);
                foreach (var item in result)
                {
                    await Runtime.GlobalHubBacktest.Clients.All.SendAsync("Send", JsonConvert.SerializeObject(item));
                }
            });

            return(new JsonResult(strategies));
        }
Ejemplo n.º 25
0
        public string GlobalToTradingViewSymbol(string exchange, string symbol)
        {
            //Trading view use same format as Binance -> BTC-ETH is ETHBTC
            IExchangeAPI api            = ExchangeAPI.GetExchangeAPI(exchange);
            string       exchangeSymbol = api.GlobalMarketSymbolToExchangeMarketSymbolAsync(symbol).Result;

            return(exchangeSymbol);
        }
Ejemplo n.º 26
0
        public string GlobalToTradingViewSymbol(string exchange, string symbol)
        {
            //Trading view use same format as Binance -> BTC-ETH is ETHBTC
            IExchangeAPI api            = ExchangeAPI.GetExchangeAPI("binance");
            string       exchangeSymbol = api.GlobalSymbolToExchangeSymbol(symbol);

            return(exchangeSymbol);
        }
Ejemplo n.º 27
0
 public void Dispose()
 {
     if (_api != null)
     {
         _api.Dispose();
         _api = null;
     }
 }
Ejemplo n.º 28
0
        private static void TestExchanges()
        {
            IExchangeAPI[] apis = ExchangeAPI.GetExchangeAPIDictionary().Values.ToArray();
            foreach (IExchangeAPI api in apis)
            {
                // test all public API for each exchange
                try
                {
                    string symbol = GetSymbol(api);

                    IReadOnlyCollection <string> symbols = api.GetSymbols().ToArray();
                    Assert(symbols != null && symbols.Count != 0 && symbols.Contains(symbol, StringComparer.OrdinalIgnoreCase));
                    Console.WriteLine($"API {api.Name} GetSymbols OK (default: {symbol}; {symbols.Count} symbols)");

                    ExchangeTrade[] trades = api.GetHistoricalTrades(symbol).ToArray();
                    Assert(trades.Length != 0 && trades[0].Price > 0m && trades[0].Amount > 0m);
                    Console.WriteLine($"API {api.Name} GetHistoricalTrades OK ({trades.Length})");

                    var book = api.GetOrderBook(symbol);
                    Assert(book.Asks.Count != 0 && book.Bids.Count != 0 && book.Asks[0].Amount > 0m &&
                           book.Asks[0].Price > 0m && book.Bids[0].Amount > 0m && book.Bids[0].Price > 0m);
                    Console.WriteLine($"API {api.Name} GetOrderBook OK ({book.Asks.Count} asks, {book.Bids.Count} bids)");

                    trades = api.GetRecentTrades(symbol).ToArray();
                    Assert(trades.Length != 0 && trades[0].Price > 0m && trades[0].Amount > 0m);
                    Console.WriteLine($"API {api.Name} GetRecentTrades OK ({trades.Length} trades)");

                    var ticker = api.GetTicker(symbol);
                    Assert(ticker != null && ticker.Ask > 0m && ticker.Bid > 0m && ticker.Last > 0m &&
                           ticker.Volume != null && ticker.Volume.PriceAmount > 0m && ticker.Volume.QuantityAmount > 0m);
                    Console.WriteLine($"API {api.Name} GetTicker OK (ask: {ticker.Ask}, bid: {ticker.Bid}, last: {ticker.Last})");

                    try
                    {
                        var candles = api.GetCandles(symbol, 86400, DateTime.UtcNow.Subtract(TimeSpan.FromDays(7.0)), null).ToArray();
                        Assert(candles.Length != 0 && candles[0].ClosePrice > 0m && candles[0].HighPrice > 0m && candles[0].LowPrice > 0m && candles[0].OpenPrice > 0m &&
                               candles[0].HighPrice >= candles[0].LowPrice && candles[0].HighPrice >= candles[0].ClosePrice && candles[0].HighPrice >= candles[0].OpenPrice &&
                               !string.IsNullOrWhiteSpace(candles[0].Name) && candles[0].ExchangeName == api.Name && candles[0].PeriodSeconds == 86400 && candles[0].VolumePrice > 0.0 &&
                               candles[0].VolumeQuantity > 0.0 && candles[0].WeightedAverage >= 0m);

                        Console.WriteLine($"API {api.Name} GetCandles OK ({candles.Length})");
                    }
                    catch (NotSupportedException)
                    {
                        Console.WriteLine($"API {api.Name} GetCandles not supported");
                    }
                    catch (NotImplementedException)
                    {
                        Console.WriteLine($"API {api.Name} GetCandles not implemented");
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Request failed, api: {0}, error: {1}", api, ex.Message);
                }
            }
        }
Ejemplo n.º 29
0
 protected override async void OnShown(EventArgs e)
 {
     base.OnShown(e);
     foreach (var exchange in await ExchangeAPI.GetExchangeAPIsAsync())
     {
         cmbExchange.Items.Add(exchange.Name);
     }
     cmbExchange.SelectedIndex = 0;
 }
Ejemplo n.º 30
0
        public Engine()
        {
            api = new ExchangeBinanceUSAPI();

            // load in the api keys.
            api.LoadAPIKeysUnsecure(ConfigurationManager.AppSettings.Get("PublicKey"), ConfigurationManager.AppSettings.Get("SecretKey"));

            logger.Trace($"Starting {QUOTECURRENCY} trading. LiveTrading={isLiveTrading}, StakeSize={stakeSize}, LowWaterMark={balanceLowWaterMark}");
        }