예제 #1
0
        public async Task <JsonResult> ImportSyncAPI(int apiId, int portfolioId)
        {
            ExchangeApiInfo exchangeApiInfo = CurrentUser.ExchangeApiList.FirstOrDefault(x => x.Id == apiId);

            if (exchangeApiInfo == null)
            {
                return(Json(ResultsItem.Error("This API Id cannot be found")));
            }

            if (!CurrentUser.HasPortfolio(portfolioId))
            {
                return(Json(ResultsItem.Error(Lang.PortfolioNotFound)));
            }

            // Test -> Move to .Tests solution
            //List<Core.Data.ServiceModels.ImportedCoin> importedCoins = FetchAPILogic.ImportCSV_Coins(exchangeApiInfo.Exchange,
            //     System.IO.File.OpenRead(@"C:\Users\Ref\Downloads\pegatrade_importFiles\api_test1\2nd-half.csv"));

            List <Core.Data.ServiceModels.ImportedCoin> importedCoins = await FetchAPILogic.ImportAPI_Coins(exchangeApiInfo, CurrentUser);

            if (importedCoins.IsNullOrEmpty())
            {
                return(Json(ResultsItem.Error(Lang.UnableToImportWrongKeyPermission)));
            }

            List <CryptoCoin> existingExchangeCoins = (await CryptoLogic.GetAllUserCoinsByPortfolioIdAsync(portfolioId)).Where(x => x.Exchange == exchangeApiInfo.Exchange).ToList();
            DateTime          latestDate            = existingExchangeCoins.IsNullOrEmpty() ? DateTime.MinValue : existingExchangeCoins.Max(x => x.OrderDate);

            // Get rid of ANY imported coins that are less than already existing date.
            // We dont' want to mess with those, we just want to add new ones.
            importedCoins = importedCoins.Where(x => x.OrderDate > latestDate).ToList();
            if (importedCoins.IsNullOrEmpty())
            {
                Json(ResultsItem.Error(Lang.ApiAlreadyUptoDate));
            }

            List <CryptoCoin> fetchedCoins = FetchAPILogic.FormatCoinsAndGenerateTotalPricePaid(importedCoins, await GetAllHistoricCoinPrices());

            if (fetchedCoins.Count > 0)
            {
                // Get all current holding coins that will be affected by new coins. Delete them from db as well, we'll re-add them.
                existingExchangeCoins = existingExchangeCoins.Where(x => x.OrderType == Types.OrderType.Buy && fetchedCoins.Any(f => f.Symbol.EqualsTo(x.Symbol))).ToList();
                await CryptoLogic.DeleteUserCoinsAsync(existingExchangeCoins, CurrentUser);

                existingExchangeCoins.ForEach(x => x.CoinId = 0); // Reset PK so DB can generate a new one.
                existingExchangeCoins.AddRange(fetchedCoins);
                existingExchangeCoins = CryptoLogic.FormatCoinsAndBoughtSoldLogicUpdate(existingExchangeCoins);

                ResultsItem insertResults = await CryptoLogic.InsertCoinsToUserPortfolioAsync(existingExchangeCoins, CurrentUser, portfolioId);

                if (insertResults.IsSuccess)
                {
                    return(Json(ResultsItem.Success("Successfully imported coins to your portfolio.")));
                }
            }

            return(Json(ResultsItem.Error(Lang.ApiNoNewTradesOrError)));
        }
예제 #2
0
        public async Task <Dictionary <int, HistoricCoinPrice> > GetAllHistoricCoinPrices()
        {
            if (!_memoryCache.TryGetValue(Constant.Session.GlobalHistoricCoinsPrice, out Dictionary <int, HistoricCoinPrice> historicPrices))
            {
                string serverMapPath = System.IO.Path.Combine(_hostingEnvironment.WebRootPath, "files\\prices");
                var    results       = await FetchAPILogic.GetAllHistoricPrice_BTC_ETH(serverMapPath : serverMapPath);

                _memoryCache.Set(Constant.Session.GlobalHistoricCoinsPrice, results, TimeSpan.FromHours(24));

                return(results);
            }

            return(historicPrices);
        }
예제 #3
0
        public async Task <List <MarketCoin> > GetAllCoinsMarketDetailsAPI()
        {
            if (_memoryCache.TryGetValue(Constant.Session.GlobalAllCoinsAPIData, out MarketFetchData marketData))
            {
                if (marketData.LastUpdated.AddSeconds(45) < DateTime.Now)                                    // Update/Refresh Data
                {
                    if (marketData.CurrentlyUpdating && marketData.LastUpdated.AddMinutes(3) > DateTime.Now) // It's already updating & less than 3 minutes has passed since API call
                    {
                        // Just wait for it to get automatically get updated in the threadpool. Return outdated data for now.
                        return(marketData.MarketCoins);
                    }

                    // Data is outdated & It's not updating yet || It's trying to update, it's been over 3 minutes, still nothing. Retry again. API Server is slow/down.
                    if (!marketData.CurrentlyUpdating)
                    {
                        marketData.CurrentlyUpdating = true;
                        _memoryCache.Set(Constant.Session.GlobalAllCoinsAPIData, marketData, TimeSpan.FromHours(1));
                    }

                    ThreadPool.QueueUserWorkItem(delegate
                    {
                        // Start an update process in the background.
                        MarketFetchData data = new MarketFetchData
                        {
                            MarketCoins = FetchAPILogic.GetAllCoinsFromApiAsync().Result,
                            LastUpdated = DateTime.Now
                        };
                        if (!data.MarketCoins.IsNullOrEmpty())
                        {
                            _memoryCache.Set(Constant.Session.GlobalAllCoinsAPIData, data, TimeSpan.FromHours(1));
                        }
                    });
                }

                // Fresh data
                return(marketData.MarketCoins);
            }

            List <MarketCoin> fetchedCoins = await FetchAPILogic.GetAllCoinsFromApiAsync();

            MarketFetchData newData = new MarketFetchData
            {
                MarketCoins = fetchedCoins,
                LastUpdated = DateTime.Now
            };

            _memoryCache.Set(Constant.Session.GlobalAllCoinsAPIData, newData, TimeSpan.FromHours(1));
            return(newData.MarketCoins);
        }
예제 #4
0
        public async Task <JsonResult> ImportEtherAddress(ExchangeApiInfo apiInfo)
        {
            var resultsPair = await FetchAPILogic.ApiImport_EtherAddress(await GetAllCoinsMarketDetailsAPI(), apiInfo.ApiPublic, apiInfo.PortfolioID, CurrentUser);

            if (!resultsPair.Result.IsSuccess)
            {
                return(Json(resultsPair.Result));
            }

            await CryptoLogic.DeleteAllUserCoinByExchangeAsync(apiInfo.PortfolioID, Types.Exchanges.EtherAddressLookup, CurrentUser);

            ResultsItem insertResult = await CryptoLogic.InsertCoinsToUserPortfolioAsync(resultsPair.Value, CurrentUser, apiInfo.PortfolioID);

            return(Json(insertResult));
        }
예제 #5
0
        // Warn, this will delete previous imported Exchange (BitTrex, Kraken, etc) trades
        public async Task <IActionResult> PostCSVTradeHistoryFile(IFormFile file, Types.Exchanges exchange, int portfolioId)
        {
            if (file == null || file.Length > 100000 ||
                (!file.FileName.EndsWith(".csv", StringComparison.OrdinalIgnoreCase) && !file.FileName.EndsWith(".xlsx", StringComparison.OrdinalIgnoreCase)))
            {
                return(Json(ResultsItem.Error("Please select a proper .csv/.xlsx file that is less than 100kb.")));
            }

            List <Core.Data.ServiceModels.ImportedCoin> importedCoins = new List <Core.Data.ServiceModels.ImportedCoin>();

            using (var stream = file.OpenReadStream())
            {
                importedCoins = FetchAPILogic.ImportCSV_Coins(exchange, stream);
            }

            if (importedCoins.IsNullOrEmpty())
            {
                return(Json(ResultsItem.Error(Lang.ImportFailedCSV)));
            }

            int maxAllowedImport = SubscriptionLogic.GetMaxAllowedTradesImportPerUser(CurrentUser.PTUserInfo.SubscriptionLevel);

            if (importedCoins.Count > maxAllowedImport)
            {
                return(Json(ResultsItem.Error(string.Format(Lang.CSVMaxImportAllowed, maxAllowedImport))));
            }

            List <CryptoCoin> fetchedCoins = FetchAPILogic.FormatCoinsAndGenerateTotalPricePaid(importedCoins, await GetAllHistoricCoinPrices());

            if (fetchedCoins.Count > 0)
            {
                fetchedCoins = CryptoLogic.FormatCoinsAndBoughtSoldLogicUpdate(fetchedCoins);

                await CryptoLogic.DeleteAllUserCoinByExchangeAsync(portfolioId, exchange, CurrentUser);

                ResultsItem insertResults = await CryptoLogic.InsertCoinsToUserPortfolioAsync(fetchedCoins, CurrentUser, portfolioId);

                if (insertResults.IsSuccess)
                {
                    return(Json(ResultsItem.Success("Successfully imported coins to your portfolio.")));
                }
            }

            return(Json(ResultsItem.Error("An error occured when trying to import trades. Are you sure the import .csv file has correct format?")));
        }
예제 #6
0
        //[TestMethod]
        public void RefreshOfficialCoinsInDB()
        {
            List <LocalCoins.MarketCoin> fetchedCoins = FetchAPILogic.GetAllCoinsFromApiAsync().Result;

            using (PegasunDBContext db = new PegasunDBContext())
            {
                List <OfficialCoins> existingOfficialCoins = db.OfficialCoins.ToList();
                fetchedCoins.ForEach(x =>
                {
                    if (!existingOfficialCoins.Any(o => o.Name == x.CoinMarketCapID))
                    {
                        db.OfficialCoins.Add(new OfficialCoins
                        {
                            Name   = x.CoinMarketCapID,
                            Symbol = x.Symbol
                        });
                    }
                });
                db.SaveChanges();
            }
        }