public KrakenClientTests(ITestOutputHelper output, KrakenFixture fixture) { _client = fixture.Client; // Log request and response for each test. _client.InterceptRequest = async req => { output.WriteLine("REQUEST"); output.WriteLine(req.ToString()); string content = await req.Content.ReadAsStringAsync(); if (!string.IsNullOrWhiteSpace(content)) { output.WriteLine(content); } return(req); }; _client.InterceptResponse = async res => { output.WriteLine(""); output.WriteLine("RESPONSE"); output.WriteLine(res.ToString()); string content = await res.Content.ReadAsStringAsync(); output.WriteLine(JToken.Parse(content).ToString(Formatting.Indented)); return(res); }; }
private static async Task SuperOrderAsync(KrakenClient cli, OrderKind kind, string pair, decimal amount) { OrderBook orderBook = await cli.GetOrderBookAsync(pair); var(price, volumeAbove) = GetBestCurrentPrice(orderBook, kind, -1, amount); string txid = await LimitOrderAsync(cli, kind, pair, amount, price); Console.WriteLine("Opened initial order to {0} {1} {2} @ {3} ({4} volume above)", kind == OrderKind.Buy ? "buy" : "sell", amount, pair, price, volumeAbove); while (true) { Task <Dictionary <string, OrderInfo> > orderReq = cli.QueryOrdersAsync(new[] { txid }); Task <OrderBook> orderBookReq = cli.GetOrderBookAsync(pair); OrderInfo order = (await orderReq).Values.Single(); orderBook = await orderBookReq; if (order.Status == OrderStatus.Closed) { break; } decimal amountLeft = order.Volume - order.VolumeExecuted; var(newPrice, newVolumeAbove) = GetBestCurrentPrice(orderBook, kind, price, amountLeft); if (newPrice == price) { Console.WriteLine("Positioned correctly. Current volume: {0}, {1} above", amountLeft, newVolumeAbove); await Task.Delay(2000); continue; } try { await cli.CancelOrderAsync(txid); } catch (KrakenException) { await Task.Delay(2000); continue; } order = (await cli.QueryOrdersAsync(new[] { txid })).Values.Single(); amountLeft = order.Volume - order.VolumeExecuted; if (order.Status == OrderStatus.Closed || amountLeft <= 0) { break; } txid = await LimitOrderAsync(cli, kind, pair, amountLeft, newPrice); Console.WriteLine("Moved order from {0} to {1} ({2} above)", price, newPrice, newVolumeAbove); price = newPrice; await Task.Delay(4000); } }
public async Task GetAssetPairs() { var cr = new KrakenClient(); var result = await cr.GetTradableAssetPairs(); Assert.That(result, Is.Not.Null); }
public async void TestName() { var cr = new KrakenClient(); var result = await cr.GetTrades("ETHUSD"); Assert.That(result, Is.Not.Null); }
public async Task GetEtherAssetInfo() { var cr = new KrakenClient(); var result = await cr.GetAssetInfo(assets : "ETH"); Assert.That(result.Values.First().Altname, Is.EqualTo("ETH")); }
public async Task GetServerTime() { var cr = new KrakenClient(); var time = await cr.GetServerTime(); Assert.That(time.Rfc1123, Is.Not.Null); }
public static KrakenClient CreateWorkingClient(bool debug = false) { var connection = KrakenConnection.Create(Settings.ApiKey, Settings.ApiSecret, debug); var krakenClient = new KrakenClient(connection); return(krakenClient); }
private Kraken(string apikey, string apisecret) { ApiKey = apikey; ApiSecret = apisecret; m_api = new KrakenClient(ApiKey, ApiSecret, 1000); m_instance = this; }
/*public Dictionary<string, ZCryptoSymbol> GetSymbols() * { * Dictionary<string, ZCryptoSymbol> result = new Dictionary<string, ZCryptoSymbol>(); * List<string> errors; * var pairs = GetAssetPairs(out errors); * foreach (string symbol in pairs.Keys) * { * result.Add(symbol, new ZCryptoSymbol(symbol, CryptoExchange.Kraken)); * } * return result; * }*/ public void getit() { try { var api = new KrakenClient(ApiKey, ApiSecret, 500); string symbol = "XETHXXBT"; var ticker = api.GetTicker(symbol); var t = ticker[symbol]; var bid = t.Bid[0]; var bidSize = t.Bid[2]; var ask = t.Ask[0]; var askSize = t.Ask[2]; cout("{0}=> bid:{1}x{2} ask:{3}x{4}", symbol, bid, bidSize, ask, askSize); var pairs = api.GetAssetPairs(); foreach (var s in pairs.Keys) { if (s == symbol) { cout("{0}=> lot:{1} lot_decimals:{2} lot_multiplier:{3} pair_decimals:{4}", s, pairs[s].Lot, pairs[s].LotDecimals, pairs[s].LotMultiplier, pairs[s].PairDecimals); } } var roundPrice = pairs[symbol].PairDecimals; } catch (Exception ex) { cout("[{0}] Error occurred attempting to submit Kraken order: {1}", DateTime.Now.ToShortTimeString(), ex.Message); } //var _params = new Dictionary<string, object>(); //var res = ExecuteCommand<Dictionary<string, decimal>>("/0/private/Balance", _params); }
private static async Task MainAsync() { string[] secrets = File.ReadAllLines("Z:\\Temp\\kraken.txt"); using (var cli = new KrakenClient(secrets[0], secrets[1])) { await SuperOrderAsync(cli, OrderKind.Sell, "LTCEUR", 15); } }
public void BuildUrl() { var cr = new KrakenClient(); var url = cr.BuildPath("Asset", true, new Dictionary <string, string>() { { "asset", "ETH" } }); Assert.That(url.ToString(), Is.EqualTo("https://api.kraken.com/0/public/Asset?asset=ETH")); }
public async Task GetBalance() { var testCredentials = new KrakenCredentials { Secret = "oyk16w/LzydxZ4aAnuy2DK5qzByYG9ja1XaW6BQ9uP1hongaczewuGUeAaWE5rHL5vvIrBEF2j13E97hvuPVmA==", Key = "eR55LkazbSk6AG27P/RgwvORohb2fgZpB2sKVpZOzJlWyRB27ttqgt1d" }; var cr = new KrakenClient(testCredentials); await cr.CallPrivate <int>("Balance"); }
public DataClient() { Binance = new BinanceClient(); Bitfinex = new BitfinexClient(); Poloniex = new PoloniexClient(); Bitstamp = new BitstampClient(); Gdax = new GdaxClient(); Gemini = new GeminiClient(); Kraken = new KrakenClient(); Okex = new OkexClient(); }
public void KrakenClient_UnauthorizedSandbox_IsTrue() { var connection = KrakenConnection.Create("key", "secret"); var krakenClient = new KrakenClient(connection); var response = krakenClient.OptimizeWait( new Uri(TestData.ImageOne)); var result = response.Result; Assert.IsTrue(result.StatusCode == HttpStatusCode.Unauthorized); }
public void KrakenClient_MustProvideAConnection_IsTrue() { try { var krakenClient = new KrakenClient(null); Assert.IsTrue(false, "No exception"); } catch (Exception) { Assert.IsTrue(true); } }
public void KrakenClient_NoErrors_IsTrue() { try { var connection = KrakenConnection.Create("key", "secret"); var krakenClient = new KrakenClient(connection); Assert.IsTrue(true); } catch (Exception) { Assert.IsTrue(false, "Exception"); } }
public void KrakenClient_Dispose_IsTrue() { var krakenConnection = KrakenConnection.Create("key", "secret"); var krakenClient = new KrakenClient(krakenConnection); try { krakenClient.Dispose(); Assert.IsTrue(true); } catch (Exception) { Assert.IsTrue(false, "Exception"); } }
private static async Task <string> LimitOrderAsync( KrakenClient cli, OrderKind kind, string pair, decimal amount, decimal price) { var result = await cli.AddOrderAsync(new OrderRequest { Kind = kind, Pair = pair, Type = OrderType.Limit, Price = price, Volume = amount, }); string txid = result.TransactionIds.Single(); return(txid); }
public KrakenFixture() { if (ApiKey.Length != KrakenClient.DummyApiKey.Length || PrivateKey.Length != KrakenClient.DummyPrivateKey.Length) { throw new InvalidOperationException( $@"Please configure {nameof(ApiKey)} and {nameof(PrivateKey)} in {nameof(KrakenFixture)}! Use {nameof(KrakenClient)}.{nameof(KrakenClient.DummyApiKey)} and {nameof(KrakenClient)}.{nameof(KrakenClient.DummyPrivateKey)} to test only public API."); } Client = new KrakenClient(ApiKey, PrivateKey, ApiRateLimit) { ErrorsAsExceptions = true, WarningsAsExceptions = true, // If the API key has two factor password enabled, set the line below to return it. //GetTwoFactorPassword = () => Task.FromResult("<INSERT_PASSWORD>") }; }
static void Main(string[] args) { var pair = "ETHUSD"; var client = new KrakenClient(); var db = new KrakenDatabaseService(); var coreDb = new DatabaseService(); Config config = null; while (true) { if (!ConnectivityService.CheckForInternetConnection()) { Console.WriteLine($"{DateTime.Now:F} Connection is not available"); Thread.Sleep(10 * 60 * 1000); continue; } try { var mainTask = Task.Run(async() => { config = await coreDb.GetConfig(); var id = await db.GetId(pair); var getTradesReasult = await client.GetTrades(id, pair); await db.SaveLastId(pair, getTradesReasult.LastId); await db.Save(getTradesReasult.Results); Console.WriteLine($"{DateTime.Now:F} Loaded {getTradesReasult.Results.Count} trades"); }); Task.WaitAll(new[] { mainTask }, new TimeSpan(2 * 60 * 1000)); Thread.Sleep((config?.LoadIntervalMinutes ?? 5) * 60 * 1000); } catch (Exception e) { Task.WaitAll(Task.Run(async() => { await coreDb.Log("kraken", "loadingError", e.Message); })); } } }
/// <summary> /// Adds coin sources to the <paramref name="services" />. /// </summary> /// <param name="services">The <see cref="IServiceCollection" />.</param> /// <param name="configurationRoot">Configuration</param> /// <returns></returns> public static IServiceCollection AddClients(this IServiceCollection services, IConfigurationRoot configurationRoot) { #if NOT_DEPRECATED // currently returning errors CoinMarketCapClient.Register(services); #endif BinanceClient.Register(services); BittrexClient.Register(services); GdaxClient.Register(services); GateIoClient.Register(services); KrakenClient.Register(services); PoloniexClient.Register(services); FunFairClientBase.Register(services: services, configurationRoot.GetSection(key: "Sources:FunFair") .Get <FunFairClientConfiguration>()); return(services); }
public void KrakenClient_RequestUploadCallbackNoFileNameError_IsTrue() { var krakenConnection = KrakenConnection.Create("key", "secret"); var krakenClient = new KrakenClient(krakenConnection); try { krakenClient.Optimize( null, string.Empty, new OptimizeUploadRequest() ); Assert.IsTrue(false, "No exception"); } catch (Exception) { Assert.IsTrue(true); } }
static void Main(string[] args) { var client = new KrakenClient("https://api.kraken.com"); var assets = client.GetAssetInfo().Result; foreach (var asset in assets) { Console.WriteLine($"{asset.AssetName} -> {asset.CurrencyName}"); } var assetPairs = client.GetAssetPairs().Result; foreach (var assetPair in assetPairs) { Console.WriteLine($"{assetPair.PairName}: {assetPair.BaseName} -> {assetPair.QuoteName}"); } var tickers = client.GetAssetPairTickers(assetPairs).Result; foreach (var ticker in tickers) { Console.WriteLine($"{ticker.PairName} -> Ask: {ticker.AskPrice} Bid: {ticker.BidPrice} Last: {ticker.LastPrice}"); } var ohlcData = client.GetOHLC("XETHZUSD", OHLCTimeInterval.FiveMinutes).Result; Console.WriteLine($"{ohlcData.PairName} -> Last Id: {ohlcData.LastPollingId}"); foreach (var entry in ohlcData.Entries) { Console.WriteLine($"({entry.Time}) Open: {entry.OpenPrice} / Close: {entry.ClosePrice} / High: {entry.HighPrice} / Low: {entry.LowPrice}"); } Console.ReadKey(); }
protected KrakenClientTests(ITestOutputHelper output, KrakenFixture fixture) { Client = new KrakenClient(ApiKey, PrivateKey) { // If the API key has two factor password enabled, set the line below to return it. //GetTwoFactorPassword = () => Task.FromResult("<INSERT_PASSWORD>") ErrorsAsExceptions = true, WarningsAsExceptions = true, // Log request and response for each test. InterceptRequest = async req => { output.WriteLine("REQUEST"); output.WriteLine(req.HttpRequest.ToString()); string content = await req.HttpRequest.Content.ReadAsStringAsync(); if (!string.IsNullOrWhiteSpace(content)) { output.WriteLine(content); } // Wait if we have hit the API rate limit. RateLimiter limiter = req.HttpRequest.RequestUri.OriginalString.Contains("/private/") ? fixture.PrivateApiRateLimiter : fixture.PublicApiRateLimiter; await limiter.WaitAccess(req.ApiCallCost); }, InterceptResponse = async res => { output.WriteLine(""); output.WriteLine("RESPONSE"); output.WriteLine(res.HttpResponse.ToString()); string content = await res.HttpResponse.Content.ReadAsStringAsync(); output.WriteLine(JToken.Parse(content).ToString(Formatting.Indented)); } }; }
/// <summary> /// ctor /// </summary> public ExchangeKraken() { var cred = @"./credentials"; if (File.Exists(cred)) { using (var stream = File.OpenRead("./credentials")) { var ko = new KrakenClientOptions(); ko.ApiCredentials = new ApiCredentials(stream, "krakenKey", "krakenSecret"); ko.RateLimitingBehaviour = CryptoExchange.Net.Objects.RateLimitingBehaviour.Wait; kc = new KrakenClient(ko); _privateAPI = true; } } else { kc = new KrakenClient(); } kc.AddRateLimiter(new RateLimiterAPIKey(15, TimeSpan.FromSeconds(3))); }
public KrakenRestApi(string apiKey, string apiSecret) { m_client = new KrakenClient(apiKey, apiSecret); }
public KrakenExchange(ExchangeSettingsData setting) : base(setting) { _client = new KrakenClient(setting); }
public KrakenService(ILogger <KrakenService> logger, IOptions <KrakenSettings> options) { _logger = logger; _options = options.Value; _client = new KrakenClient(_options.ApiKey, _options.PrivateKey); }