Example #1
0
        public void GetAllCoinsAndTestProfitLoss()
        {
            Types.CoinCurrency currency = Types.CoinCurrency.USD;

            List <CryptoCoin> coins           = Deserialize <List <CryptoCoin> >(TestUtilities.File_ReadAllLinesSingle(TestUtilities.GeneratePath(@"TestFiles\Coins\Portfolio_Ref_12-13-17_BitTrexOnly.json")));
            List <MarketCoin> apiFetchedCoins = Deserialize <List <MarketCoin> >(TestUtilities.File_ReadAllLinesSingle(TestUtilities.GeneratePath(@"TestFiles\Coins\CoinMarketCap_12-13-17_getall_coins.json")));

            // Todo: for non CoinCurrency.USD items.
            // Dictionary<int, HistoricCoinPrice> historicPrices = new Dictionary<int, HistoricCoinPrice>();
            // if ((currency == Types.CoinCurrency.BTC || currency == Types.CoinCurrency.ETH) && coins.Any(x => x.OrderDate > DateTime.MinValue)) { historicPrices = await GetAllHistoricCoinPrices(); }

            List <CryptoCoin> updatedCoins = CryptoLogic.UpdateCoinsCurrentPrice(coins, apiFetchedCoins, new Dictionary <int, HistoricCoinPrice>(), useCombinedDisplay: true);

            List <CoinDisplay> displayModeCoins = updatedCoins.ToCoinDisplay(currency);

            CoinsVM vm = new CoinsVM(displayModeCoins)
            {
                DisplayCurrency = currency
            };

            //vm.CalculateCurrentHoldingProfit();
            //vm.CalculateSoldProfit();

            //Console.WriteLine(vm.CurrentHoldingMarketValue());
        }
Example #2
0
        // identifier -> symbol or name
        public async Task <OfficialCoin> GetOfficialCoin(string identifier)
        {
            async Task <OfficialCoinFetchData> UpdateAndStoreOfficialCoinData(OfficialCoinFetchData officialCoinFetchData)
            {
                List <MarketCoin> marketCoins = await GetAllCoinsMarketDetailsAPI();

                officialCoinFetchData.OfficialCoins.ForEach(x => { x.MarketCoin = marketCoins.FirstOrDefault(m => m.CoinMarketCapID == x.Name); });
                officialCoinFetchData.LastMarketUpdated = DateTime.Now;
                _memoryCache.Set(Constant.Session.GlobalAllOfficialCoins, officialCoinFetchData, TimeSpan.FromDays(7));
                return(officialCoinFetchData);
            }

            if (_memoryCache.TryGetValue(Constant.Session.GlobalAllOfficialCoins, out OfficialCoinFetchData fetchData))
            {
                if (fetchData.LastMarketUpdated.AddMinutes(1) < DateTime.Now)
                {
                    fetchData = await UpdateAndStoreOfficialCoinData(fetchData);
                }                                                                                                                              // Update market result
                return(CryptoLogic.FindOfficialCoinFromIdentifier(identifier, fetchData.OfficialCoins));
            }

            // Data does not exist yet.
            fetchData = new OfficialCoinFetchData {
                OfficialCoins = CryptoLogic.GetAllOfficialCoins()
            };
            fetchData = await UpdateAndStoreOfficialCoinData(fetchData);

            return(CryptoLogic.FindOfficialCoinFromIdentifier(identifier, fetchData.OfficialCoins));
        }
Example #3
0
        public async Task <JsonResult> ExecuteCoinChanges(CoinManagementVM vm)
        {
            ResultsItem validationResult = CoinManagementValidation(vm, isSoldMode: false);

            if (!validationResult.IsSuccess)
            {
                return(Json(validationResult));
            }

            vm.Coin.OrderType   = Types.OrderType.Buy;
            vm.Coin.Exchange    = Types.Exchanges.Custom;
            vm.Coin.PortfolioId = vm.SelectedPortfolioID;

            if (vm.Coin.TotalPricePaidUSD.GetValueOrDefault() == 0)
            {
                vm.Coin.TotalPricePaidUSD = vm.Coin.OrderDate.Date == DateTime.Now.Date ? vm.Coin.Shares * CryptoLogic.GetLatestPriceOfSymbol(vm.Coin.Symbol, await GetAllCoinsMarketDetailsAPI())
                                                                                        : CryptoLogic.GenerateTotalPricePaidUSD(vm.Coin, await GetAllHistoricCoinPrices());
            }

            var coinResult = vm.IsCreateMode ? await CryptoLogic.InsertCoinsToUserPortfolioAsync(new List <CryptoCoin> {
                vm.Coin
            }, CurrentUser, vm.SelectedPortfolioID)
                                             : await CryptoLogic.UpdateUserCoinAsync(vm.Coin, CurrentUser);

            return(Json(coinResult));
        }
Example #4
0
        public async Task <PartialViewResult> GetAllConversationThreads(int take = 50)
        {
            ConversationsVM vm = new ConversationsVM
            {
                Threads = await CommunityLogic.GetMessageThreads(take, new List <Types.ConvThreadCategory> {
                    Types.ConvThreadCategory.MainDashboard,
                    Types.ConvThreadCategory.OfficialCoins, Types.ConvThreadCategory.FeatureRequests
                }, CurrentUser),
                CurrentUser       = CurrentUser,
                HideCreateNewPost = true
            };

            List <OfficialCoin> officialCoins = CryptoLogic.GetAllOfficialCoins();

            foreach (var x in vm.Threads.Where(x => x.OfficialCoinId > 0))
            {
                OfficialCoin officialCoin = officialCoins.FirstOrDefault(o => o.OfficialCoinId == x.OfficialCoinId);
                if (officialCoin == null)
                {
                    continue;
                }

                x.OfficialCoin = officialCoin;
                x.ShowOfficialCoinNameOnThread = true;
            }

            return(PartialView("_Conversations", vm));
        }
Example #5
0
 private void Init()
 {
     if (!CryptoLogic.LoadKeys())
     {
         CryptoLogic.GenerateKeys();
         CryptoLogic.LoadKeys();
     }
 }
Example #6
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)));
        }
        private void encryptToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string sourceName = PathModifier.RemoveLastBackSlash(searchBar.Text) + @"\" + filesListView.FocusedItem.Text;

            if (saveFile.ShowDialog() == DialogResult.OK)
            {
                CryptoLogic.EncryptFile(sourceName, saveFile.FileName);
                MessageBox.Show("Succesfully Encrypted!");
            }
        }
Example #8
0
        public JsonResult DeleteImportAPI(int apiId)
        {
            ResultsItem results = CryptoLogic.DeleteAPI(apiId, CurrentUser);

            if (results.IsSuccess)
            {
                CurrentUser.ExchangeApiList = CurrentUser.ExchangeApiList.Where(x => x.Id != apiId).ToList();
                SubmitCurrentUserUpdate();
            }

            return(Json(results));
        }
Example #9
0
        private async Task <List <CryptoCoin> > GetCoinsBasedOnPortfolioId(PortfolioRequest request)
        {
            // Only let ViewPortfolio viewers allow getting that user's coins. Portfolio(public) would have been validated by this point.
            if (!request.ViewOtherUser && !CurrentUser.HasPortfolio(request.PortfolioID))
            {
                return(new List <CryptoCoin>());
            }

            List <CryptoCoin> coins = await CryptoLogic.GetAllUserCoinsByPortfolioIdAsync(request.PortfolioID);

            return(await UpdateCoinsCurrentPrice(coins, request.UseCombinedDisplay, request.Currency));
        }
Example #10
0
        public async Task <JsonResult> DeletePortfolio(int portfolioId)
        {
            ResultsItem deleteResult = await CryptoLogic.DeletePortfolio(portfolioId, CurrentUser);

            if (deleteResult.IsSuccess)
            {
                CurrentUser.Portfolios = await CryptoLogic.GetAllUserPortfolioAsync(CurrentUser);

                SubmitCurrentUserUpdate();
            }
            return(Json(deleteResult));
        }
Example #11
0
        public async Task <JsonResult> GetAllPortfolioSelectList(bool updateUser = false)
        {
            List <Portfolio> portfolioList = await CryptoLogic.GetAllUserPortfolioAsync(CurrentUser);

            if (updateUser)
            {
                CurrentUser.Portfolios = await CryptoLogic.GetAllUserPortfolioAsync(CurrentUser);

                SubmitCurrentUserUpdate();
            }

            return(Json(portfolioList.ToSelectList(x => x.Name, x => x.PortfolioId.ToString())));
        }
Example #12
0
        public JsonResult CreateNewImportAPI(ExchangeApiInfo exchangeApiInfo)
        {
            if (!ModelState.IsValid)
            {
                return(Json(ResultsItem.Error(ModelState.GetAllErrorsString())));
            }

            exchangeApiInfo.ApiAction  = Types.ApiAction.TradesImport;
            exchangeApiInfo.ApiPrivate = exchangeApiInfo.ApiPrivate.Replace("%2B", "+");
            ResultsItem apiResult = CryptoLogic.InsertNewAPI(exchangeApiInfo, CurrentUser);

            return(Json(apiResult));
        }
Example #13
0
        private ResultsItem CoinManagementValidation(CoinManagementVM vm, bool isSoldMode = false)
        {
            if (!ModelState.IsValid)
            {
                return(ResultsItem.Error(ModelState.GetAllErrorsString()));
            }

            if (!isSoldMode)
            {
                vm.Coin.Symbol = vm.Coin.Symbol.ToUpperInvariant();
                if (!vm.Coin.Symbol.StartsWith("BTC-") && !vm.Coin.Symbol.StartsWith("ETH-") && !vm.Coin.Symbol.StartsWith("USD-") && !vm.Coin.Symbol.StartsWith("USDT-"))
                {
                    return(ResultsItem.Error("Error: The coin symbol must start with BTC-, ETH-, USD-, or USDT-"));
                }

                if (vm.Coin.OrderDate > DateTime.Now)
                {
                    return(ResultsItem.Error("Error: Order date must be today or the past."));
                }

                vm.Coin.CoinCurrency = CryptoLogic.GenerateCoinCurrencyFromSymbol(vm.Coin.Symbol);
                if (vm.Coin.CoinCurrency == Types.CoinCurrency.Unknown || vm.Coin.CoinCurrency == Types.CoinCurrency.EUR)
                {
                    return(ResultsItem.Error("Error: only BTC, ETH, and USD currency is currently supported."));
                }

                if (vm.Coin.PricePerUnit <= 0)
                {
                    return(ResultsItem.Error("Please enter Price Per Unit."));
                }
            }
            else
            {
                if (!CurrentUser.HasPortfolio(vm.Coin.PortfolioId))
                {
                    return(ResultsItem.Error(Lang.PortfolioNotFound));
                }
                if (vm.Coin.SoldCoinCurrency == Types.CoinCurrency.Unknown || vm.Coin.SoldPricePerUnit.GetValueOrDefault() <= 0)
                {
                    return(ResultsItem.Error("Please enter all sold details. TotalSoldPrice is optional."));
                }

                if (vm.SoldDate < vm.Coin.OrderDate)
                {
                    return(ResultsItem.Error("Sold date cannot be lower than Buy date. Unless you're a time traveler."));
                }
            }

            return(ResultsItem.Success());
        }
Example #14
0
        private async Task <List <CryptoCoin> > UpdateCoinsCurrentPrice(List <CryptoCoin> coins, bool useCombinedDisplay = true, Types.CoinCurrency currency = Types.CoinCurrency.USD)
        {
            // Get all API coins that has the latest price, and etc. (CoinMarketCap price get)
            List <MarketCoin> apiFetchedCoins = await GetAllCoinsMarketDetailsAPI();

            Dictionary <int, HistoricCoinPrice> historicPrices = new Dictionary <int, HistoricCoinPrice>();

            if ((currency == Types.CoinCurrency.BTC || currency == Types.CoinCurrency.ETH) && coins.Any(x => x.OrderDate > DateTime.MinValue))
            {
                historicPrices = await GetAllHistoricCoinPrices();
            }

            return(CryptoLogic.UpdateCoinsCurrentPrice(coins, apiFetchedCoins, historicPrices, useCombinedDisplay, currency));
        }
Example #15
0
        public async Task <JsonResult> ResetAllTradesData()
        {
            var result = await CryptoLogic.ResetAllUserTrades(CurrentUser);

            if (result.Result.IsSuccess)
            {
                CurrentUser.Portfolios = new List <Portfolio> {
                    result.Value
                };
                SubmitCurrentUserUpdate();
            }

            return(Json(result.Result));
        }
Example #16
0
        public async Task <JsonResult> DeleteCoin(int coinId, int portfolioId)
        {
            CryptoCoin fetchedCoin = await CryptoLogic.GetSingleCoinByUser(coinId, CurrentUser);

            if (fetchedCoin?.PortfolioId != portfolioId)
            {
                return(Json(ResultsItem.Error(Lang.PortfolioNotFound)));
            }
            return(Json(await CryptoLogic.DeleteUserCoinsAsync(new List <CryptoCoin> {
                new CryptoCoin {
                    CoinId = coinId, PortfolioId = portfolioId
                }
            }, CurrentUser)));
        }
Example #17
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));
        }
Example #18
0
        public async Task <PartialViewResult> GetPortfolioList(bool isUpdated = false)
        {
            if (isUpdated)
            {
                CurrentUser.Portfolios = await CryptoLogic.GetAllUserPortfolioAsync(CurrentUser);

                SubmitCurrentUserUpdate();
            }

            PortfolioVM vm = new PortfolioVM
            {
                Portfolios = CurrentUser.Portfolios
            };

            return(PartialView("Crud/_PortfolioList", vm));
        }
Example #19
0
        public async Task <decimal> GetCurrentCoinPrice(string symbol)
        {
            Types.CoinCurrency predictedCurrency = CryptoLogic.GenerateCoinCurrencyFromSymbol(symbol);
            if (predictedCurrency == Types.CoinCurrency.Unknown)
            {
                return(0);
            }

            CryptoCoin coin = (await UpdateCoinsCurrentPrice(new List <CryptoCoin> {
                new CryptoCoin {
                    Symbol = symbol.ToUpperInvariant()
                }
            }, false)).First();

            return(CryptoLogic.GetPricePerUnitOfCoin(coin, predictedCurrency));
        }
Example #20
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?")));
        }
Example #21
0
        public static async Task <ResultsPair <LocalAccount.PegaUser> > AuthorizeUser(string username, string password)
        {
            using (HttpClient client = new HttpClient())
            {
                HttpResponseMessage response = await client.GetAsync($"{baseUrl}/v1/Account/Authenticate?username={username}&password={password}");

                if (response.IsSuccessStatusCode)
                {
                    string jsonString = await response.Content.ReadAsStringAsync();

                    PegasunAPIAuthorization apiUser = NetJSON.NetJSON.Deserialize <PegasunAPIAuthorization>(jsonString);

                    if (apiUser != null && apiUser.result.resultType == 0)
                    {
                        // Todo: Move this out? make less calls
                        var portfolioTask = CryptoLogic.GetAllUserPortfolioAsync(new LocalAccount.PegaUser {
                            UserId = apiUser.userId, Username = apiUser.username
                        });
                        var apiResultsTask = CryptoLogic.GetAllUserExchangeAPIAsync(apiUser.userId);
                        var ptUserInfoTask = GetPTUserInfo(apiUser.userId);
                        var portfolios     = await portfolioTask;
                        var apiList        = await apiResultsTask;
                        var ptUserInfo     = await ptUserInfoTask;

                        return(ResultsPair.CreateSuccess(new LocalAccount.PegaUser
                        {
                            UserId = apiUser.userId,
                            Username = apiUser.username,
                            Email = apiUser.email,
                            FullName = apiUser.fullName,
                            Portfolios = portfolios,
                            ExchangeApiList = apiList,
                            PTUserInfo = ptUserInfo,
                            EmailConfirmed = apiUser.emailConfirmed
                        }));
                    }

                    return(ResultsPair.CreateError <LocalAccount.PegaUser>(apiUser?.result.message ?? "An unknown error occured."));
                }
            }

            return(ResultsPair.CreateError <LocalAccount.PegaUser>(Lang.ServerConnectionError));
        }
Example #22
0
        public async Task <JsonResult> ExecutePortfolioChanges(PortfolioVM vm)
        {
            if (!ModelState.IsValid)
            {
                return(Json(ResultsItem.Error(ModelState.GetAllErrorsString())));
            }

            int maxPortfolioAllowed = SubscriptionLogic.GetMaxAllowedPortfolioPerUser(CurrentUser.PTUserInfo.SubscriptionLevel);

            if (vm.IsCreateMode && CurrentUser.Portfolios.Count >= maxPortfolioAllowed)
            {
                return(Json(ResultsItem.Error($"We're sorry, you can only have {maxPortfolioAllowed} portfolios max for your subscription level: {CurrentUser.PTUserInfo.SubscriptionLevel.ToString()}")));
            }

            var portfolioResultPair = vm.IsCreateMode ? (await CryptoLogic.InsertNewPortfolio(CurrentUser, vm.Portfolio.Name, vm.Portfolio.DisplayType, vm.Portfolio.IsDefault))
                                                      : CryptoLogic.UpdatePortfolio(vm.Portfolio.PortfolioId, vm.Portfolio.Name, vm.Portfolio.DisplayType, vm.Portfolio.IsDefault, CurrentUser);

            return(Json(portfolioResultPair.Result));
        }
Example #23
0
        public async Task <PartialViewResult> UpdateCoin(long coinId)
        {
            CryptoCoin coin = await CryptoLogic.GetSingleCoinByUser(coinId, CurrentUser);

            if (coin == null)
            {
                return(GeneratePartialViewError(Lang.PortfolioNotFound));
            }

            coin.SoldCoinCurrency = coin.CoinCurrency;
            CoinManagementVM vm = new CoinManagementVM
            {
                Coin                = coin,
                IsCreateMode        = false,
                SoldDate            = DateTime.Today,
                SelectedPortfolioID = coin.PortfolioId
            };

            return(PartialView("Crud/_ManageCoin", vm));
        }
Example #24
0
        public async Task <PartialViewResult> AddNewCoins(int portfolioId, bool isUpdated = false)
        {
            if (CurrentUser.ExchangeApiList.IsNullOrEmpty() || isUpdated)
            {
                CurrentUser.ExchangeApiList = await CryptoLogic.GetAllUserExchangeAPIAsync(CurrentUser.UserId);

                SubmitCurrentUserUpdate();
            }

            CoinManagementVM vm = new CoinManagementVM
            {
                PortfolioList              = CurrentUser.Portfolios.ToSelectList(x => x.Name, x => x.PortfolioId.ToString()),
                IsCreateMode               = true,
                SelectedPortfolioID        = portfolioId,
                ExistingSavedImportAPIList = CurrentUser.ExchangeApiList.ToSelectList(x => (string.IsNullOrEmpty(x.Name) ? x.Exchange.ToString() : x.Name), x => x.Id.ToString()),
                Coin = new CryptoCoin
                {
                    OrderDate = DateTime.Today
                }
            };

            return(PartialView("_AddNewCoins", vm));
        }
Example #25
0
        public async Task <JsonResult> GetGeneratedWatchOnlyDetails(string symbol)
        {
            Types.CoinCurrency predictedCurrency = CryptoLogic.GenerateCoinCurrencyFromSymbol(symbol);
            if (predictedCurrency == Types.CoinCurrency.Unknown)
            {
                return(Json(ResultsItem.Error("Unknown currency type. Please use USD-, BTC-, or ETH-")));
            }

            CryptoCoin coin = (await UpdateCoinsCurrentPrice(new List <CryptoCoin> {
                new CryptoCoin {
                    Symbol = symbol.ToUpperInvariant()
                }
            }, false)).First();

            if (coin.MarketCoin?.CurrentSymbolPriceUSD <= 0)
            {
                return(Json(ResultsItem.Error("This coin/symbol was not found. Did you use the correct format? E.g. BTC-XRP")));
            }

            decimal pricePerUnit = CryptoLogic.GetPricePerUnitOfCoin(coin, predictedCurrency);
            decimal quantity     = decimal.Round(100 / coin.MarketCoin.CurrentSymbolPriceUSD, 5);

            return(Json(new { pricePerUnit, quantity }));
        }
Example #26
0
        public async Task <JsonResult> MarkCoinSold(CoinManagementVM vm)
        {
            ResultsItem validationResult = CoinManagementValidation(vm, isSoldMode: true);

            if (!validationResult.IsSuccess)
            {
                return(Json(validationResult));
            }

            CryptoCoin fetchedCoin = await CryptoLogic.GetSingleCoinByUser(vm.Coin.CoinId, CurrentUser);

            if (fetchedCoin == null)
            {
                return(Json(ResultsItem.Error("This coin cannot be found or belogns to someone else.")));
            }

            fetchedCoin.OrderType             = Types.OrderType.Sell;
            fetchedCoin.OrderDate             = vm.SoldDate;
            fetchedCoin.SoldCoinCurrency      = vm.Coin.SoldCoinCurrency;
            fetchedCoin.SoldPricePerUnit      = vm.Coin.SoldPricePerUnit;
            fetchedCoin.TotalSoldPricePaidUSD = vm.Coin.TotalSoldPricePaidUSD;
            if (fetchedCoin.TotalSoldPricePaidUSD.GetValueOrDefault() <= 0)
            {
                decimal totalPricePaidToUSD = CryptoLogic.GenerateTotalPricePaidUSD(fetchedCoin, await GetAllHistoricCoinPrices(), fetchedCoin.SoldCoinCurrency);
                if (totalPricePaidToUSD == 0)
                {
                    // Getting historic priced failed. Their sold date is probably from another dimension. Screw the user, just get latest from the market.
                    totalPricePaidToUSD = CryptoLogic.GetLatestPriceOfCurrency(vm.Coin.SoldCoinCurrency, await GetAllCoinsMarketDetailsAPI());
                }
                fetchedCoin.TotalSoldPricePaidUSD = totalPricePaidToUSD;
            }

            ResultsItem result = await CryptoLogic.UpdateUserCoinAsync(fetchedCoin, CurrentUser);

            return(Json(result));
        }
Example #27
0
        public CryptoLogicTests()
        {
            _mockCryptoExternalRates = new Mock <ICryptoExternalRates>();

            _target = new CryptoLogic(_mockCryptoExternalRates.Object);
        }