/// <summary> /// Generate loop of Jpeg images with overlay image /// With Retry included /// </summary> /// <param name="profile">contains sizes</param> /// <param name="fileIndexItemsList">list of items to generate jpeg for</param> /// <param name="outputParentFullFilePathFolder">outputParentFullFilePathFolder</param> /// <param name="delay">when failed output, has default value</param> /// <returns></returns> internal async Task <Dictionary <string, bool> > GenerateJpeg(AppSettingsPublishProfiles profile, IReadOnlyCollection <FileIndexItem> fileIndexItemsList, string outputParentFullFilePathFolder, int delay = 6) { _toCreateSubfolder.Create(profile, outputParentFullFilePathFolder); foreach (var item in fileIndexItemsList) { var outputPath = _overlayImage.FilePathOverlayImage(outputParentFullFilePathFolder, item.FilePath, profile); async Task <bool> ResizerLocal() { return(await Resizer(outputPath, profile, item)); } try { await RetryHelper.DoAsync(ResizerLocal, TimeSpan.FromSeconds(delay)); } catch (AggregateException e) { _logger.LogError($"[ResizerLocal] Skip due errors: (catch-ed exception) {item.FilePath} {item.FileHash}"); foreach (var exception in e.InnerExceptions) { _logger.LogError("[ResizerLocal] " + exception.Message, exception); } } } return(fileIndexItemsList.ToDictionary(item => _overlayImage.FilePathOverlayImage(item.FilePath, profile), item => profile.Copy)); }
public async Task <List <Pair> > GetPairs(CancellationToken token = default(CancellationToken)) { return(await RetryHelper.DoAsync(async() => { JArray jArray = await JObjectQuery(_baseUri.AbsoluteUri + $"v{Version}/symbols", token); return jArray.Select(x => { var data = x.ToString().ToChunks(3); if (data.Length > 1) { var supported = SupportedCurrencyHelper.GetSupportedCurrencies(); var inCurrency = supported.FirstOrDefault(curency => curency == data[0].ToUpper()); var outCurrency = supported.FirstOrDefault(curency => curency == data[1].ToUpper()); if (inCurrency != null && outCurrency != null) { return new Pair(inCurrency, outCurrency); } } return null; }).Where(x => x != null).ToList(); }, TimeSpan.FromMilliseconds(Constant.DefaultRetryInterval))); }
public async Task <string> SellLimit(Order order, CancellationToken token = default(CancellationToken)) { try { WaitResourceFreeSignal(); return(await RetryHelper.DoAsync(async() => { if (order.MarketSide != MarketSide.Ask) { throw new ApplicationException("Bittrex API, Incorrect market side: {0}".FormatAs(order)); } var result = await Query <BittrexResult>("/market/selllimit", new Dictionary <string, string> { { "market", ToBittrexPair(order.Pair) }, { "quantity", Convert.ToString(order.Amount, _culture.NumberFormat) }, { "rate", Convert.ToString(order.Price, _culture.NumberFormat) } }, true, token, RequestCategory.SubmitOrder); return result.Uuid; }, TimeSpan.FromMilliseconds(Constant.DefaultRetryInterval))); } finally { AutoResetEventSet(); } }
public async Task <OrderChange> GetOrderStatus(Order order, CancellationToken token = default(CancellationToken)) { return(await RetryHelper.DoAsync(async() => { if (order == null) { throw new ArgumentNullException(nameof(order), "BitFinexApi GetOrderStatus method."); } if (!string.IsNullOrEmpty(order.Id)) { var bitFinexOrder = await GetOrderStatus(order.Id, token); if (!bitFinexOrder.IsLive && bitFinexOrder.RemainingAmount == 0.0m) { return new OrderChange(order, bitFinexOrder.OriginalAmount, bitFinexOrder.AvgExecutionPrice, OrderStatus.Filled, UnixTimeStampToDateTime(bitFinexOrder.Timestamp) ?? DateTime.UtcNow, bitFinexOrder.OriginalAmount); } if (bitFinexOrder.RemainingAmount > 0.0m && bitFinexOrder.ExecutedAmount > 0.0m) { return new OrderChange(order, 0, bitFinexOrder.AvgExecutionPrice, OrderStatus.PartiallyFilled, UnixTimeStampToDateTime(bitFinexOrder.Timestamp) ?? DateTime.UtcNow, bitFinexOrder.ExecutedAmount); } } return new OrderChange(order, 0, 0, OrderStatus.Unknown, DateTime.UtcNow); }, TimeSpan.FromMilliseconds(Constant.DefaultRetryInterval), 1)); }
public async Task <OrderChange> GetOrderStatus(Order order, CancellationToken token = default(CancellationToken)) { return(await RetryHelper.DoAsync(async() => { if (order == null) { throw new ArgumentNullException(nameof(order), "Poloniex GetOrderStatus method."); } if (!string.IsNullOrEmpty(order.Id)) { var trades = (await GetTradeHistory(order.Pair, token)).ToList(); if (trades.Any(x => x.OrderNumber == order.Id)) { var amount = trades.Sum(x => x.Amount); var avgPrice = trades.Average(x => x.Rate); if (amount == order.Amount) { return new OrderChange(order, amount, avgPrice, OrderStatus.Filled, DateTime.UtcNow, amount); } if (amount < order.Amount) { return new OrderChange(order, 0, avgPrice, OrderStatus.PartiallyFilled, DateTime.UtcNow, amount); } } } return new OrderChange(order, 0, 0, OrderStatus.Unknown, DateTime.UtcNow); }, TimeSpan.FromMilliseconds(Constant.DefaultRetryInterval), 1)); }
public async Task <BitFinexOrderStatus> CancelOrder(int orderId, CancellationToken token = default(CancellationToken)) { try { WaitResourceFreeSignal(); return(await RetryHelper.DoAsync(async() => { var methods = $"v{Version}/order/cancel"; var result = await PrivateQuery <BitFinexOrderStatus>(_baseUri.AbsoluteUri + methods, new Dictionary <string, object> { { "request", "/" + methods }, { "nonce", Convert.ToString(GetNonce()) }, { "order_id", orderId } }, token, RequestCategory.CancelOrder); return result; }, TimeSpan.FromMilliseconds(Constant.DefaultRetryInterval))); } finally { AutoResetEventSet(); } }
public async Task <CexPlaceOrderResponse> PlaceOrder(Pair pair, OrderSide type, decimal amount, decimal price, CancellationToken token = default(CancellationToken)) { try { WaitResourceFreeSignal(); var culture = CultureHelper.GetEnglishCulture(); var data = await RetryHelper.DoAsync(async() => { var nonce = GetNonce(); var signature = GetSignature(nonce, _userName, _key, _secret); return(await PrivateQuery <CexPlaceOrderResponse>(ApiUrl + "place_order/" + pair, new Dictionary <string, string> { { "key", _key }, { "signature", signature.ToUpper() }, { "nonce", Convert.ToString(nonce) }, { "type", type.ToString().ToLower() }, { "amount", Convert.ToString(amount, culture) }, { "price", Convert.ToString(price, culture) } }, token, RequestCategory.SubmitOrder)); }, TimeSpan.FromMilliseconds(Constant.DefaultRetryInterval), 1); return(data); } finally { AutoResetEventSet(); } }
public async Task <bool> CancelOrder(string orderId, CancellationToken token = default(CancellationToken)) { try { WaitResourceFreeSignal(); var data = await RetryHelper.DoAsync(async() => { var nonce = GetNonce(); var signature = GetSignature(nonce, _userName, _key, _secret); return(await PrivateQuery(ApiUrl + "cancel_order/", new Dictionary <string, string> { { "key", _key }, { "signature", signature.ToUpper() }, { "nonce", Convert.ToString(nonce) }, { "id", orderId } }, token, RequestCategory.CancelOrder)); }, TimeSpan.FromMilliseconds(Constant.CexRetryInterval)); return(bool.Parse(data)); } finally { AutoResetEventSet(); } }
public async Task <IEnumerable <CexOrderArchive> > GetArchivedOrders(Pair pair, CancellationToken token = default(CancellationToken)) { try { WaitResourceFreeSignal(); var data = await RetryHelper.DoAsync(async() => { var nonce = GetNonce(); var signature = GetSignature(nonce, _userName, _key, _secret); return(await PrivateQuery <List <CexOrderArchive> >( ApiUrl + "archived_orders/" + PairConvertorHelper.DashToDrkPair(pair), new Dictionary <string, string> { { "key", _key }, { "signature", signature.ToUpper() }, { "nonce", Convert.ToString(nonce) }, { "limit", Convert.ToString(LimitMax) }, { "dateFrom", Convert.ToString(UnixTime.GetNowAddDays(-3)) }, { "dateTo", Convert.ToString(UnixTime.GetNowAddDays(1)) } }, token, RequestCategory.OrderHistory)); }, TimeSpan.FromMilliseconds(Constant.DefaultRetryInterval), 1); return(data); } finally { AutoResetEventSet(); } }
public async Task <string> BuyLimit(Order order, CancellationToken token = default(CancellationToken)) { try { WaitResourceFreeSignal(); return(await RetryHelper.DoAsync(async() => { if (order == null) { throw new ArgumentNullException(nameof(order), "Cex BuyLimit method."); } if (order.MarketSide != MarketSide.Bid) { throw new CexException("Cex API, Incorrect market side: {0}".FormatAs(order)); } var neworder = await PlaceOrder(PairConvertorHelper.DashToDrkPair(order.Pair), OrderSide.Buy, order.Amount, decimal.Round(order.Price, 4), token); if (string.IsNullOrEmpty(neworder.Id) || !string.IsNullOrEmpty(neworder.Error)) { throw new CexException("Cex API, Order rejected: {0}".FormatAs(order)); } return Convert.ToString(neworder.Id); }, TimeSpan.FromMilliseconds(Constant.DefaultRetryInterval), 1)); } finally { AutoResetEventSet(); } }
public async Task <OrderChange> GetOrderStatus(Order order, CancellationToken token = default(CancellationToken)) { return(await RetryHelper.DoAsync(async() => { if (order == null) { throw new ArgumentNullException(nameof(order), "Cex GetOrderStatus method."); } if (!string.IsNullOrEmpty(order.Id)) { var openOrders = await GetOpenOrders(order.Pair, token); var openOrder = openOrders.SingleOrDefault(x => x.Id == order.Id && x.PendingAmount > 0); if (openOrder != null) { return new OrderChange(order, 0, openOrder.Price, OrderStatus.PartiallyFilled, DateTime.UtcNow, openOrder.PendingAmount); } var archiveOrders = (await GetArchivedOrders(order.Pair, token)).ToList(); var archiveOrder = archiveOrders.SingleOrDefault(x => x.OrderId == order.Id); if (archiveOrder != null && archiveOrder.OrderStatus == OrderStatus.Filled) { return new OrderChange(order, order.Amount, archiveOrder.Price, OrderStatus.Filled, DateTime.UtcNow, order.Amount); } } return new OrderChange(order, 0, 0, OrderStatus.Unknown, DateTime.UtcNow); }, TimeSpan.FromMilliseconds(Constant.DefaultRetryInterval), 1)); }
public async Task <BitFinexOrderStatus> GetOrderStatus(string orderId, CancellationToken token = default(CancellationToken)) { try { WaitResourceFreeSignal(); return(await RetryHelper.DoAsync(async() => { if (string.IsNullOrEmpty(orderId)) { throw new ArgumentNullException(nameof(orderId), "BitFinexApi GetOrderStatus method."); } var methods = $"v{Version}/order/status"; var result = await PrivateQuery <BitFinexOrderStatus>(_baseUri.AbsoluteUri + methods, new Dictionary <string, object> { { "request", "/" + methods }, { "nonce", Convert.ToString(GetNonce()) }, { "order_id", Convert.ToUInt32(orderId) } }, token, RequestCategory.OrderStatus); return result; }, TimeSpan.FromMilliseconds(Constant.DefaultRetryInterval))); } finally { AutoResetEventSet(); } }
public async Task <string> PlaceOrder(Order order, BterOrderType type, CancellationToken token = default(CancellationToken)) { return(await RetryHelper.DoAsync(async() => { if (order == null) { throw new ArgumentNullException(nameof(order), "BterApi PlaceOrder method."); } var result = await PrivateQuery("placeorder", new NameValueCollection { { "nonce", GetNonce().ToString("D") }, { "pair", ToBterPair(order.Pair) }, { "type", type.ToString().ToLower() }, //sell, buy { "rate", Convert.ToString(order.Price, CultureHelper.GetEnglishCulture().NumberFormat) }, { "amount", Convert.ToString(order.Amount, CultureHelper.GetEnglishCulture().NumberFormat) }, }, _key, _secret, token, RequestCategory.SubmitOrder); if (!result.BterResponse.Result || !result.BterResponse.IsSuccess) { throw new BterException("Bter API, PlaceOrder rejected: {0}, Message - {1}".FormatAs(order, result.BterResponse.Message ?? result.BterResponse.Msg)); } return result.BterResponse.OrderId; }, TimeSpan.FromMilliseconds(Constant.DefaultRetryInterval))); }
public async Task <string> NewOrder(string clientOrderId, Pair pair, HitBtcTradeType type, decimal price, int?quantity, OrderType orderType, HitBtcTimeInForce?timeInForce, CancellationToken token = default(CancellationToken)) { var culture = CultureHelper.GetEnglishCulture(); var parameters = new Dictionary <string, string> { { "nonce", Convert.ToString(GetNonce(), culture) }, { "apikey", _apiKey }, { "clientOrderId", clientOrderId }, { "symbol", pair.ToString().Replace("/", string.Empty) }, { "side", type.ToString() }, { "price", Convert.ToString(price, culture) } }; if (quantity.HasValue) { parameters.Add("quantity", quantity.Value.ToString()); } parameters.Add("type", orderType.ToString()); if (timeInForce.HasValue) { parameters.Add("timeInForce", timeInForce.Value.ToString()); } return(await RetryHelper.DoAsync(async() => await PrivateQuery <string>( $"api/{Version}/trading/cancel_order", parameters, token), TimeSpan.FromMilliseconds(Constant.DefaultRetryInterval))); }
public async Task <IEnumerable <Pair> > GetSupportedPairs(CancellationToken token = default(CancellationToken)) { return(await RetryHelper.DoAsync(async() => { var data = await GetTickers(token); var results = data.ToList().Select(x => { var pairs = x.PairStr.Split('_'); var supported = SupportedCurrencyHelper.GetSupportedCurrencies(); var inCurrency = supported.FirstOrDefault(curency => curency == pairs[0].ToUpper()); var outCurrency = supported.FirstOrDefault(curency => curency == pairs[1].ToUpper()); if (inCurrency != null && outCurrency != null) { return new Pair(inCurrency, outCurrency); } return null; }); return results.Where(n => n != null).Distinct().ToList(); }, TimeSpan.FromMilliseconds(Constant.DefaultRetryInterval), 1)); }
public async Task <CexBalance> GetBalances(CancellationToken token = default(CancellationToken)) { try { WaitResourceFreeSignal(); var data = await RetryHelper.DoAsync(async() => { var nonce = GetNonce(); var signature = GetSignature(nonce, _userName, _key, _secret); return(await PrivateQuery(ApiUrl + "balance/", new Dictionary <string, string> { { "key", _key }, { "signature", signature.ToUpper() }, { "nonce", Convert.ToString(nonce) } }, token, RequestCategory.AccountHoldings)); }, TimeSpan.FromMilliseconds(Constant.DefaultRetryInterval)); var jobj = JObject.Parse(data); var result = jobj.ToObject <CexBalance>(); var balances = CexAccountBalance.GetFromJObject(jobj); result.AccountBalances = balances; return(result); } finally { AutoResetEventSet(); } }
/// <summary> /// Write async and disposed after /// </summary> /// <param name="stream">fileStream</param> /// <param name="path">filePath</param> /// <returns>success or fail</returns> public async Task <bool> WriteStreamAsync(Stream stream, string path) { if (!stream.CanRead) { return(false); } async Task <bool> LocalRun() { try { stream.Seek(0, SeekOrigin.Begin); } catch (NotSupportedException) { // HttpConnection.ContentLengthReadStream does not support this } using (var fileStream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read, 4096, FileOptions.Asynchronous | FileOptions.SequentialScan)) { await stream.CopyToAsync(fileStream); fileStream.Dispose(); } stream.Dispose(); return(true); } return(await RetryHelper.DoAsync(LocalRun, TimeSpan.FromSeconds(1))); }
public async Task <BterOrderStatus> GetOrder(string orderId, CancellationToken token = default(CancellationToken)) { return(await RetryHelper.DoAsync(async() => { BterOrderStatus orderStatus = null; if (string.IsNullOrEmpty(orderId)) { throw new ArgumentNullException(nameof(orderId), "BterApi GetOrder method."); } var result = await PrivateQuery("getorder", new NameValueCollection { { "nonce", GetNonce().ToString("D") }, { "order_id", orderId } }, _key, _secret, token, RequestCategory.OrderStatus); if (!result.BterResponse.Result || !result.BterResponse.IsSuccess) { throw new BterException("Bter API, GetOrder: orderId - {0}, Message -{1}".FormatAs(orderId, result.BterResponse.Message ?? result.BterResponse.Msg)); } var jobject = result.JObject; if (jobject["order"] != null) { orderStatus = jobject["order"].ToObject <BterOrderStatus>(); } return orderStatus; }, TimeSpan.FromMilliseconds(Constant.DefaultRetryInterval))); }
public async Task <Tuple <decimal, decimal> > GetAvgPriceAndTotalFilledAmount(Order order, CancellationToken token = default(CancellationToken)) { try { WaitResourceFreeSignal(); return(await RetryHelper.DoAsync(async() => { decimal totalFillAmount = -1; decimal avgPrice = -1; var userTransactions = (await GetUserTransactions(0, 1000, "desc", token)).ToArray(); if (userTransactions.Any(x => Convert.ToString(x.OrderId) == order.Id)) { totalFillAmount = userTransactions.Sum(x => Math.Abs(x.Btc)); avgPrice = userTransactions.Average(x => x.BtcUsd); } return Tuple.Create(avgPrice, totalFillAmount); }, TimeSpan.FromMilliseconds(Constant.DefaultRetryInterval), 1)); } finally { WaitResourceFreeSignal(); } }
public async Task <IEnumerable <HitBtcTicker> > GetTickers(CancellationToken token = default(CancellationToken)) { return(await RetryHelper.DoAsync(async() => { JObject jobject = await JObjectQuery(_baseUri.AbsoluteUri + $"api/{Version}/public/ticker", token); return HitBtcTicker.GetFromJObject(jobject); }, TimeSpan.FromMilliseconds(Constant.DefaultRetryInterval))); }
public async Task <IEnumerable <Pair> > GetPairs(CancellationToken token = default(CancellationToken)) { return(await RetryHelper.DoAsync(async() => { var result = await Query <SymbolsResponse>(_baseUri.AbsoluteUri + $"api/{Version}/public/symbols", token); return result.Symbols.Select(x => new Pair(x.Commodity, x.Currency)).Where(x => x != null).ToList(); }, TimeSpan.FromMilliseconds(Constant.DefaultRetryInterval))); }
public async Task <IEnumerable <PoloniexCurrency> > GetCurrencies(CancellationToken token = default(CancellationToken)) { return(await RetryHelper.DoAsync(async() => { JObject jobject = await JObjectQuery(PublicUrl + "?command=returnCurrencies", token); return PoloniexCurrency.GetFromJObject(jobject); }, TimeSpan.FromMilliseconds(Constant.DefaultRetryInterval))); }
public async Task <OrderBook> GetOrderBook(Pair pair, CancellationToken token = default(CancellationToken)) { return(await RetryHelper.DoAsync(async() => { var data = await Query <PoloniexOrderBook>(PublicUrl + "?command=returnOrderBook¤cyPair=" + pair.ToString().Replace("/", "_"), token); return FromPoloniexOrderBook(data, pair); }, TimeSpan.FromMilliseconds(Constant.DefaultRetryInterval))); }
public async Task <BitStampOrder> SellLimit(decimal amount, decimal price, CancellationToken token = default(CancellationToken)) { return(await RetryHelper.DoAsync(async() => { var culture = CultureHelper.GetEnglishCulture(); return await SellLimit(Convert.ToString(decimal.Round(amount, 8), culture.NumberFormat), Convert.ToString(Decimal.Round(price, 2), culture.NumberFormat), token); }, TimeSpan.FromMilliseconds(Constant.DefaultRetryInterval), 1)); }
public async Task <ConcurrentBag <BterTicker> > GetTickers(CancellationToken token = default(CancellationToken)) { return(await RetryHelper.DoAsync(async() => { JObject jobject = await Query(_apiVersion + "tickers", null, token); return BterTicker.GetFromJObject(jobject); }, TimeSpan.FromMilliseconds(Constant.DefaultRetryInterval))); }
/// <summary> /// Get tradable asset pairs /// </summary> public async Task <KrakenAssetPairs> GetAssetPairs(CancellationToken token = default(CancellationToken)) { return(await RetryHelper.DoAsync(async() => { JObject o = await Query("0/public/AssetPairs", null, token); return KrakenAssetPairs.ReadFromJObject(o); }, TimeSpan.FromMilliseconds(Constant.DefaultRetryInterval), 1)); }
/// <summary> /// Transactions /// </summary> /// <returns>Transactions</returns> public async Task <List <BitStampTransact> > GetTransactions(int delta = 3600, CancellationToken token = default(CancellationToken)) { return(await RetryHelper.DoAsync(async() => { var result = await Query(_baseUri.AbsoluteUri + "transactions/?timedelta=" + delta, token); return JsonConvert.DeserializeObject <List <BitStampTransact> >(result); }, TimeSpan.FromMilliseconds(Constant.DefaultRetryInterval))); }
/// <summary> /// Reserve /// </summary> /// <returns>Reserve</returns> public async Task <BitStampReserve> GetReserve(CancellationToken token = default(CancellationToken)) { return(await RetryHelper.DoAsync(async() => { var result = await Query(_baseUri.AbsoluteUri + "bitinstant/", token); return JsonConvert.DeserializeObject <BitStampReserve>(result); }, TimeSpan.FromMilliseconds(Constant.DefaultRetryInterval))); }
/// <summary> /// Get server time /// </summary> public async Task <DateTime> GetTime(CancellationToken token = default(CancellationToken)) { return(await RetryHelper.DoAsync(async() => { JObject o = await Query("0/public/Time", null, token); return KrakenTime.ReadFromJObject(o).Time; }, TimeSpan.FromMilliseconds(Constant.DefaultRetryInterval), 1)); }
public async Task <OrderBook> GetOrderBook(Pair pair, CancellationToken token = default(CancellationToken)) { return(await RetryHelper.DoAsync(async() => { var data = await Query <CexOrderBook>(ApiUrl + $"order_book/{pair.BaseCurrency}/{pair.CounterCurrency}", token); return FromCexOrderBook(data, pair); }, TimeSpan.FromMilliseconds(Constant.DefaultRetryInterval))); }