Example #1
0
        public async Task <IActionResult> GetEOSBalanceAsync(string account, string symbol, string lang, [FromServices] ILogger logger, [FromServices] KyubeyContext db, [FromServices] TokenRepositoryFactory tokenRepositoryFactory, [FromServices] NodeApiInvoker nodeApiInvoker, CancellationToken cancellationToken)
        {
            var tokenRespository = await tokenRepositoryFactory.CreateAsync(lang);

            var buyTokens = await db.DexBuyOrders.Where(x => x.Account == account).Select(x => x.TokenId).Distinct().ToListAsync(cancellationToken);

            var sellTokens = await db.DexSellOrders.Where(x => x.Account == account).Select(x => x.TokenId).Distinct().ToListAsync(cancellationToken);

            var matchTokens = await db.MatchReceipts
                              .Where(x => x.Time >= DateTime.Now.AddMonths(-3) &&
                                     (x.Asker == account || x.Bidder == account))
                              .Select(x => x.TokenId).Distinct().ToListAsync(cancellationToken);

            var tokens = buyTokens.Concat(sellTokens).Concat(matchTokens).Distinct().ToList();

            if (!string.IsNullOrWhiteSpace(symbol))
            {
                if (!tokens.Contains(symbol))
                {
                    tokens.Add(symbol);
                }
            }

            var responseData = new Dictionary <string, double>();

            tokens.ForEach(x =>
            {
                var currentTokenBalance = 0.0;
                try
                {
                    var tokenInfo = tokenRespository.GetSingle(x);
                    if (tokenInfo != null)
                    {
                        currentTokenBalance = nodeApiInvoker.GetCurrencyBalanceAsync(account, tokenInfo?.Basic?.Contract?.Transfer, x, cancellationToken).Result;
                    }
                }
                catch (Newtonsoft.Json.JsonSerializationException ex)
                {
                    logger.LogError(ex.ToString());
                }
                finally
                {
                    responseData.Add(x, currentTokenBalance);
                }
            });
            responseData.Add("EOS", await nodeApiInvoker.GetCurrencyBalanceAsync(account, "eosio.token", "EOS", cancellationToken));
            return(ApiResult(responseData));
        }
Example #2
0
        static async Task StartBotMatchAsync()
        {
            Console.WriteLine("Total {0} tokens found in configuration file.", configObject.Pairs.Count());
            Console.WriteLine("—————————— GO ——————————");
            while (true)
            {
                //foreach (var pair in configObject.Pairs)
                {
                    var randomPairIndex = random.Next(configObject.Pairs.Count());
                    var pair            = configObject.Pairs[randomPairIndex];
                    try
                    {
                        decimal price = (decimal) await GetPriceAsync(pair.Symbol);

                        Console.WriteLine("[{2}] {0}: Price: {1} EOS", DateTime.Now.ToString("T"),
                                          price.ToString("0.00000000"),
                                          pair.Symbol);

                        var eosBalance = await client.GetCurrencyBalanceAsync("eosio.token", configObject.TestAccount, "EOS");

                        var tokenBalance = await nodeAPI.GetCurrencyBalanceAsync(configObject.TestAccount, pair.Contract, pair.Symbol);

                        if ((decimal)eosBalance.Result.Amount < price)
                        {
                            Console.WriteLine("EOS balance: {0}, Price = {1}, Cannot execute buy", eosBalance.Output, price);

                            await EmailService.SendEmailAsync("BOT: " + "时间: " + DateTime.Now.ToString("T") + "TokenID: " + pair.Symbol + "EOS 余额不足",
                                                              String.Format("EOS balance: {0}, Price = {1}, Cannot execute buy", eosBalance.Output, price),
                                                              configObject.EmailAddress,
                                                              configObject.SendTo
                                                              );

                            continue;
                        }

                        var amount = BotMath.GetEffectiveRandomAmount(ref price, MaxEOSExchangeTotal, (decimal)tokenBalance, pair.Symbol);

                        Console.WriteLine("Sell! ");
                        await AutoSellAsync(pair.Symbol, amount, price, pair.Contract);

                        Console.WriteLine($"Sell {amount} {pair.Symbol},total {price * amount} EOS");

                        Console.WriteLine("Wait 0.2 seconds");
                        await Task.Delay(200);

                        Console.WriteLine("Buy! ");
                        await AutoBuyAsync(pair.Symbol, amount, price);

                        Console.WriteLine($"Buy {amount} {pair.Symbol},total {price * amount} EOS");

                        var waitingTime = random.Next(1000 * 60 * 1, 1000 * 60 * 3);
                        Console.WriteLine("———— Next run time: {0} ————", MillisecondsSpanToDateTimeString(waitingTime));
                        await Task.Delay(waitingTime);
                    }
                    catch (Exception ex)
                    {
                        await EmailService.SendEmailAsync("BOT: " + "时间: " + DateTime.Now.ToString("T") + "TokenID: " + pair.Symbol + "发生异常",
                                                          ex.ToString(),
                                                          configObject.EmailAddress,
                                                          configObject.SendTo
                                                          );
                    }
                }
            }
        }
Example #3
0
        public async Task <IActionResult> InfoAsync(
            string id,
            [FromQuery] string username,
            GetBaseRequest request,
            [FromServices] KyubeyContext db,
            [FromServices] TokenRepositoryFactory tokenRepositoryFactory,
            [FromServices] NodeApiInvoker nodeApiInvoker,
            [FromServices] ILogger logger,
            CancellationToken cancellationToken)
        {
            var dbToken = await db.Tokens.FirstOrDefaultAsync(x => x.Id == id && x.Status == TokenStatus.Active, cancellationToken);

            if (dbToken == null)
            {
                return(ApiResult(404, "not found this token"));
            }

            var tokenRepository = await tokenRepositoryFactory.CreateAsync(request.Lang);

            var tokenInfo      = tokenRepository.GetSingle(id);
            var supporterCount = await db.RaiseLogs.Where(x =>
                                                          (x.Timestamp > (tokenInfo.Incubation.Begin_Time ?? DateTime.MinValue) &&
                                                           x.Timestamp < tokenInfo.Incubation.DeadLine) &&
                                                          x.TokenId == dbToken.Id && !x.Account.StartsWith("eosio.")).Select(x => x.Account).Distinct().CountAsync();

            GetSymbolSupplyResponse symbolSupply = null;
            TokenContractPriceModel currentPrice = null;
            var eosBalance   = 0.0;
            var tokenBalance = 0.0;

            try
            {
                symbolSupply = await nodeApiInvoker.GetSymbolSupplyAsync(tokenInfo?.Basic?.Contract?.Transfer, id, cancellationToken);

                currentPrice = await tokenRepository.GetContractPriceAsync(id);

                eosBalance = await nodeApiInvoker.GetCurrencyBalanceAsync(username, "eosio.token", "EOS", cancellationToken);

                tokenBalance = await nodeApiInvoker.GetCurrencyBalanceAsync(username, tokenInfo?.Basic?.Contract?.Transfer, id, cancellationToken);
            }
            catch (Exception ex)
            {
                logger.LogError(ex.ToString());
            }

            var whitepaperPath = tokenRepository.GetWhitePaper(id, request.Lang);

            var response = new GetIncubatorInfoResponse()
            {
                CurrentPrice   = currentPrice?.BuyPrice ?? 0,
                EOSBalance     = (decimal)eosBalance,
                TokenBalance   = (decimal)tokenBalance,
                Contract       = tokenInfo.Basic?.Contract?.Pricing ?? tokenInfo.Basic?.Contract?.Transfer,
                BuyMemo        = tokenInfo.Basic?.Contract_Exchange_Info?.Buy_Memo,
                CurrentRaised  = dbToken.Raised,
                IsFavorite     = false,
                Protocol       = tokenInfo.Basic?.Protocol,
                RemainingDay   = tokenInfo?.Incubation?.DeadLine == null ? -999 : Math.Max((tokenInfo.Incubation.DeadLine - DateTime.Now).Days, 0),
                BeginTime      = tokenInfo?.Incubation.Begin_Time,
                DeadLine       = tokenInfo?.Incubation.DeadLine ?? DateTime.MaxValue,
                SupporterCount = supporterCount,
                Target         = tokenInfo?.Incubation?.Goal ?? 0,
                TotalSupply    = (decimal)(symbolSupply?.MaxSupply ?? 0),
                WhitePaper     = whitepaperPath == null ? null : "/token_assets/" + whitepaperPath
            };

            return(ApiResult(response));
        }
Example #4
0
        public async Task <IActionResult> GetWalletAsync(string lang, string account, [FromServices] KyubeyContext db, [FromServices] TokenRepositoryFactory tokenRepositoryFactory, [FromServices] ILogger logger, [FromServices] NodeApiInvoker nodeApiInvoker, CancellationToken cancellationToken)
        {
            var tokenRespository = await tokenRepositoryFactory.CreateAsync(lang);

            var tokensCurrentPrice = await db.MatchReceipts.OrderByDescending(x => x.Time).GroupBy(x => x.TokenId).Select(g => new
            {
                TokenId = g.Key,
                Price   = g.FirstOrDefault().UnitPrice
            }).ToListAsync(cancellationToken);

            var buyList = await db.DexBuyOrders
                          .Where(x => x.Account == account)
                          .GroupBy(x => x.TokenId)
                          .Select(x => new
            {
                TokenId   = x.Key,
                FreezeEOS = x.Sum(s => s.Bid)
            }).ToListAsync(cancellationToken);

            var sellList = await db.DexSellOrders
                           .Where(x => x.Account == account)
                           .GroupBy(x => x.TokenId)
                           .Select(x => new
            {
                TokenId     = x.Key,
                FreezeToken = x.Sum(s => s.Ask)
            }).ToListAsync(cancellationToken);

            var matchTokens = await db.MatchReceipts
                              .Where(x => x.Time >= DateTime.Now.AddMonths(-3) &&
                                     (x.Asker == account || x.Bidder == account))
                              .Select(x => x.TokenId).Distinct().ToListAsync(cancellationToken);

            var tokens = buyList.Select(x => x.TokenId).Concat(sellList.Select(x => x.TokenId)).Concat(matchTokens).Distinct().ToList();

            var responseData = new List <GetWalletResponse>();

            responseData.Add(new GetWalletResponse()
            {
                IconSrc   = "/img/eos.png",
                Freeze    = buyList.Sum(x => x.FreezeEOS),
                Symbol    = "EOS",
                UnitPrice = 1,
                Valid     = nodeApiInvoker.GetCurrencyBalanceAsync(account, "eosio.token", "EOS", cancellationToken).Result
            });

            tokens.ForEach(x =>
            {
                var currentTokenBalance = 0.0;
                try
                {
                    var tokenInfo = tokenRespository.GetSingle(x);
                    if (tokenInfo != null)
                    {
                        currentTokenBalance = nodeApiInvoker.GetCurrencyBalanceAsync(account, tokenInfo?.Basic?.Contract?.Transfer, x, cancellationToken).Result;
                    }
                }
                catch (Newtonsoft.Json.JsonSerializationException ex)
                {
                    logger.LogError(ex.ToString());
                }
                finally
                {
                    responseData.Add(new GetWalletResponse()
                    {
                        IconSrc   = $"/token_assets/{x}/icon.png",
                        Valid     = currentTokenBalance,
                        Symbol    = x,
                        Freeze    = sellList.FirstOrDefault(s => s.TokenId == x)?.FreezeToken ?? 0,
                        UnitPrice = tokensCurrentPrice.FirstOrDefault(s => s.TokenId == x)?.Price ?? 0
                    });
                }
            });

            return(ApiResult(responseData));
        }