Example #1
0
        public static PlatformApi GetInstance(string userName)
        {
            AccountConfig accountConfig = AccountConfigUtils.GetAccountConfig(userName);
            PlatformApi   api           = new PlatformApi(accountConfig.AccessKey, accountConfig.SecretKey);

            return(api);
        }
Example #2
0
        public async Task BuyTest(string quoteCurrency)
        {
            var symbols = CoinUtils.GetAllCommonSymbols(quoteCurrency);
            var account = AccountConfigUtils.GetAccountConfig("qq");

            foreach (var symbol in symbols)
            {
                PlatformApi       api = PlatformApi.GetInstance("qq");
                OrderPlaceRequest req = new OrderPlaceRequest();
                req.account_id = account.MainAccountId;
                req.amount     = "0.0000001";
                req.price      = "0.001";
                req.source     = "api";
                req.symbol     = symbol.BaseCurrency + symbol.QuoteCurrency;
                req.type       = "buy-limit";

                try
                {
                    HBResponse <long> order = api.OrderPlace(req);

                    logger.Error($"3 ------------------------");
                }
                catch (Exception ex)
                {
                    logger.Error($"{ symbol.BaseCurrency + symbol.QuoteCurrency}" + ex.Message, ex);
                }
            }
        }
Example #3
0
        public static void SearchOrder(long orderId)
        {
            var           userName = "******";
            AccountConfig account  = AccountConfigUtils.GetAccountConfig(userName);

            PlatformApi api = PlatformApi.GetInstance(userName);

            var orderDetail = api.QueryOrderDetail(orderId);

            Console.WriteLine(orderDetail.Status);
            Console.WriteLine(orderDetail.Data.state);
            if (orderDetail.Status == "ok" && orderDetail.Data.state == "filled")
            {
                Console.WriteLine(orderDetail.Data.price);
                Console.WriteLine(orderDetail.Data.id);
                Console.WriteLine(orderDetail.Data.symbol.Replace("usdt", ""));
                Console.WriteLine(orderDetail.Data.amount);

                if (new PigMoreDao().GetByBOrderId(orderId) != null)
                {
                    Console.WriteLine("订单存在");
                    return;
                }

                new PigMoreDao().CreatePigMore(new PigMore()
                {
                    Name        = orderDetail.Data.symbol.Replace("usdt", ""),
                    AccountId   = account.MainAccountId,
                    UserName    = account.UserName,
                    FlexPercent = (decimal)1.04,

                    BQuantity          = orderDetail.Data.amount,
                    BOrderP            = orderDetail.Data.price,
                    BDate              = DateTime.Now,
                    BOrderResult       = "",
                    BState             = StateConst.Submitting,
                    BTradeP            = 0,
                    BOrderId           = orderId,
                    BFlex              = "",
                    BMemo              = "",
                    BOrderDetail       = "",
                    BOrderMatchResults = "",

                    SOrderId           = 0,
                    SOrderResult       = "",
                    SDate              = DateTime.MinValue,
                    SFlex              = "",
                    SMemo              = "",
                    SOrderDetail       = "",
                    SOrderMatchResults = "",
                    SOrderP            = 0,
                    SQuantity          = 0,
                    SState             = "",
                    STradeP            = 0,
                });
            }
        }
        public async Task <object> EmptyInfo(string userName, string symbolName, string quoteCurrency)
        {
            PlatformApi api = PlatformApi.GetInstance(userName);

            var accountInfo = api.GetAccountBalance(AccountConfigUtils.GetAccountConfig(userName).MainAccountId);
            var balanceItem = accountInfo.Data.list.Find(it => it.currency == symbolName);

            var list          = new DogEmptySellDao().ListDogEmptySellNotFinished(symbolName, userName, quoteCurrency);
            var totalQuantity = new DogMoreBuyDao().GetBuyQuantityOfDogMoreBuyIsNotFinished(userName, symbolName);

            return(new { balanceItem, list, totalQuantity });
        }
Example #5
0
        public static void SearchBuyOrder(long orderId)
        {
            var           userName = "******";
            AccountConfig account  = AccountConfigUtils.GetAccountConfig(userName);

            PlatformApi api = PlatformApi.GetInstance(userName);

            var orderDetail = api.QueryOrderDetail(orderId);

            Console.WriteLine(orderDetail.Status);
            Console.WriteLine(orderDetail.Data.state);
            if (orderDetail.Status == "ok" && orderDetail.Data.state == "filled")
            {
                Console.WriteLine(JsonConvert.SerializeObject(orderDetail));
                Console.WriteLine(orderDetail.Data.id);
                Console.WriteLine(orderDetail.Data.symbol.Replace("usdt", ""));
                Console.WriteLine(orderDetail.Data.amount);

                if (orderDetail.Data.type != "buy-limit")
                {
                    Console.WriteLine(orderDetail.Data.type);
                    Thread.Sleep(1000 * 60 * 5);
                }

                if (new DogMoreBuyDao().GetByBuyOrderId(orderId) != null)
                {
                    Console.WriteLine("订单存在");
                    return;
                }

                new DogMoreBuyDao().CreateDogMoreBuy(new DogMoreBuy()
                {
                    SymbolName = orderDetail.Data.symbol.Replace("usdt", ""),
                    //QuoteCurrency =
                    AccountId = account.MainAccountId,
                    UserName  = account.UserName,

                    BuyQuantity          = orderDetail.Data.amount,
                    BuyOrderPrice        = orderDetail.Data.price,
                    BuyDate              = DateTime.Now,
                    BuyOrderResult       = "",
                    BuyState             = StateConst.Submitting,
                    BuyTradePrice        = 0,
                    BuyOrderId           = orderId,
                    BuyMemo              = "",
                    BuyOrderDetail       = "",
                    BuyOrderMatchResults = "",
                    IsFinished           = false
                });
            }
        }
Example #6
0
        private static void RunBuy(CommonSymbol symbol, AnalyzeResult analyzeResult)
        {
            var nowPrice = analyzeResult.NowPrice;

            var userNames = UserPools.GetAllUserName();

            // 空单的自动波动收割
            foreach (var userName in userNames)
            {
                var dogEmptySellList = new DogEmptySellDao().GetNeedShougeDogEmptySell(userName, symbol.BaseCurrency, symbol.QuoteCurrency);
                if (dogEmptySellList == null || dogEmptySellList.Count == 0)
                {
                    continue;
                }

                Console.WriteLine("做空收割 " + symbol.BaseCurrency + symbol.QuoteCurrency + $", nowPrice:{nowPrice} 空单数量:" + dogEmptySellList.Count);
                foreach (var dogEmptySellItem in dogEmptySellList)
                {
                    try
                    {
                        ShouGeDogEmpty(dogEmptySellItem, symbol, analyzeResult);
                    }
                    catch (Exception ex)
                    {
                    }
                }
            }

            // 1.低于管控的购入价
            if (!JudgeBuyUtils.ControlCanBuy(symbol.BaseCurrency, symbol.QuoteCurrency, nowPrice))
            {
                return;
            }

            // 自动波动做多
            foreach (var userName in userNames)
            {
                try
                {
                    BuyWhenDoMore(symbol, AccountConfigUtils.GetAccountConfig(userName), analyzeResult);
                }
                catch (Exception ex)
                {
                }
            }
        }
Example #7
0
        public async Task <string> DoMore(string userName, string symbolName, string quoteCurrency)
        {
            try
            {
                var symbol = CoinUtils.GetCommonSymbol(symbolName, quoteCurrency);

                var ladder = (decimal)1.062;
                if (symbolName == "hb10" || symbolName == "eth" || symbolName == "ltc" || symbolName == "xrp" || symbolName == "bch" ||
                    symbolName == "etc" || symbolName == "eos" || symbolName == "ht" ||
                    symbolName == "dash" || symbolName == "zec" || symbolName == "omg" || symbolName == "ada" || symbolName == "iota")
                {
                    ladder = (decimal)1.058;
                }
                return(CoinTrade.BuyWhenDoMoreAnalyze(symbol, AccountConfigUtils.GetAccountConfig(userName), ladder));
            }
            catch (Exception ex)
            {
                logger.Error(ex.Message, ex);
                return(ex.Message);
            }
        }
        public async Task <object> DoEmpty(string userName, string symbolName, string quoteCurrency)
        {
            // 立马空单
            var symbols    = CoinUtils.GetAllCommonSymbols("usdt");
            var symbol     = symbols.Find(it => it.BaseCurrency == symbolName);
            var dao        = new KlineDao();
            var lastKlines = dao.List24HourKline(symbol.QuoteCurrency, symbol.BaseCurrency);

            if (Utils.GetDateById(lastKlines[0].Id) < DateTime.Now.AddMinutes(-3))
            {
                // 数据是3分钟前的数据, 不合理.
                return("没有拿到最近3分钟的数据");
            }
            // 大于今天最小值30%才行 or 大于24小时60%  并且大于历史最小的15%
            var control = new DogControlDao().GetDogControl(symbolName, quoteCurrency);

            if (control == null)
            {
                return("没有管控");
            }
            var nowPrice = lastKlines[0].Close;

            if (nowPrice < control.HistoryMin && nowPrice < control.HistoryMin + (control.HistoryMax - control.HistoryMin) * (decimal)0.12)
            {
                return("要大于区间12%");
            }

            var min24    = lastKlines.Min(it => it.Close);
            var minToday = lastKlines.Where(it => Utils.GetDateById(it.Id) >= DateTime.Now.Date).Min(it => it.Close);

            if (nowPrice > min24 * (decimal)1.60 || nowPrice > minToday * (decimal)1.30)
            {
                CoinTrade.DoEmpty(symbol, userName, AccountConfigUtils.GetAccountConfig(userName).MainAccountId);
                return(new { nowPrice, min24, minToday, DoEmpty = true });
            }
            return(new { nowPrice, min24, minToday });
        }
Example #9
0
        public static void DoEmpty(CommonSymbol symbol, string userName, string accountId)
        {
            AnalyzeResult analyzeResult = AnalyzeResult.GetAnalyzeResult(symbol);

            if (analyzeResult == null)
            {
                throw new ApplicationException("做空失败,分析出错");
            }
            var nowPrice = analyzeResult.NowPrice;

            if (nowPrice * (decimal)1.06 < analyzeResult.MaxPrice)
            {
                throw new ApplicationException("已经降低了6%, 不要做空,谨慎起见");
            }

            var maxSellTradePrice = new DogEmptySellDao().GetMaxSellTradePrice(userName, symbol.BaseCurrency, symbol.QuoteCurrency);

            if (maxSellTradePrice != null && nowPrice < maxSellTradePrice * (decimal)1.06)
            {
                throw new ApplicationException("有价格比这个更高得还没有收割。不能重新做空。");
            }

            PlatformApi api = PlatformApi.GetInstance(userName);

            var accountInfo = api.GetAccountBalance(AccountConfigUtils.GetAccountConfig(userName).MainAccountId);
            var balanceItem = accountInfo.Data.list.Find(it => it.currency == symbol.BaseCurrency);
            // 要减去未收割得。
            var notShougeQuantity = new DogMoreBuyDao().GetBuyQuantityNotShouge(userName, symbol.BaseCurrency);

            if (notShougeQuantity >= balanceItem.balance || notShougeQuantity <= 0)
            {
                logger.Error($"未收割得数量大于余额,有些不合理,  {symbol.BaseCurrency},, {userName},, {notShougeQuantity}, {balanceItem.balance}");
                return;
            }

            var     devide       = DogControlUtils.GetRecommendDivideForEmpty(symbol.BaseCurrency, symbol.QuoteCurrency, nowPrice, (balanceItem.balance - notShougeQuantity));
            decimal sellQuantity = (balanceItem.balance - notShougeQuantity) / devide; // 暂定每次做空1/12

            if (sellQuantity * nowPrice > 10)                                          // 一次做空不超过10usdt
            {
                sellQuantity = 10 / nowPrice;
            }
            sellQuantity = decimal.Round(sellQuantity, symbol.AmountPrecision);

            if (sellQuantity * nowPrice < 1)
            {
                sellQuantity = (balanceItem.balance - notShougeQuantity) / 10;
                if (sellQuantity * nowPrice < 1)
                {
                    sellQuantity = (balanceItem.balance - notShougeQuantity) / 5;
                    if (sellQuantity * nowPrice < 1)
                    {
                        sellQuantity = (balanceItem.balance - notShougeQuantity) / 3;
                        if (sellQuantity * nowPrice < (decimal)0.2)
                        {
                            LogNotBuy(symbol.BaseCurrency, $"收益不超过0.2usdt,, balance: {balanceItem.balance},  notShougeQuantity:{notShougeQuantity}, {nowPrice}, yu: {(balanceItem.balance - notShougeQuantity) * nowPrice}");
                            return;
                        }
                    }
                }
            }

            // 出售
            decimal sellPrice = decimal.Round(nowPrice * (decimal)0.985, symbol.PricePrecision);

            SellWhenDoEmpty(accountId, userName, symbol, sellQuantity, sellPrice);
        }
Example #10
0
        private static void RunSell(CommonSymbol symbol, AnalyzeResult analyzeResult, Ticker ticker)
        {
            if (ticker.symbol != symbol.BaseCurrency + symbol.QuoteCurrency)
            {
                Console.WriteLine("--------------------- 数据错误");
                return;
            }

            var historyKlines = analyzeResult.HistoryKlines;
            var nowPrice      = analyzeResult.NowPrice;

            var userNames = UserPools.GetAllUserName();

            // 多单的自动波动收割
            foreach (var userName in userNames)
            {
                var needSellDogMoreBuyList = new DogMoreBuyDao().GetNeedSellDogMoreBuy(userName, symbol.BaseCurrency, symbol.QuoteCurrency);

                foreach (var dogMoreBuyItem in needSellDogMoreBuyList)
                {
                    try
                    {
                        if (ticker.close < dogMoreBuyItem.BuyOrderPrice * (decimal)1.07)
                        {
                            continue;
                        }

                        ShouGeDogMore(dogMoreBuyItem, symbol, analyzeResult);
                    }
                    catch (Exception ex)
                    {
                        logger.Error($"收割出错 {ex.Message} {JsonConvert.SerializeObject(dogMoreBuyItem)}", ex);
                        continue;
                    }
                }
            }

            // 不符合管控的,则不考虑做空
            if (!JudgeBuyUtils.ControlCanSell(symbol.BaseCurrency, symbol.QuoteCurrency, historyKlines, nowPrice))
            {
                if (symbol.BaseCurrency == "xmx")
                {
                    Console.WriteLine("----------------------------------------------------------------------------------------");
                }
                return;
            }

            foreach (var userName in userNames)
            {
                try
                {
                    Console.WriteLine($"---> before doempty {userName}   {symbol.BaseCurrency},{symbol.QuoteCurrency}");

                    // 和上次做空价格要相差8%
                    var maxSellTradePrice = new DogEmptySellDao().GetMaxSellTradePrice(userName, symbol.BaseCurrency, symbol.QuoteCurrency);
                    if (maxSellTradePrice != null && nowPrice < maxSellTradePrice * ladderEmptySellPercent)
                    {
                        continue;
                    }

                    var accountConfig = AccountConfigUtils.GetAccountConfig(userName);
                    var accountId     = accountConfig.MainAccountId;

                    // 要减去未收割得。
                    var notShougeQuantity = new DogMoreBuyDao().GetBuyQuantityNotShouge(userName, symbol.BaseCurrency);

                    // 出售
                    decimal sellPrice = decimal.Round(nowPrice * (decimal)0.988, symbol.PricePrecision);

                    // 阶梯有数量差别
                    var minSellEmptyPrice = new DogEmptySellDao().GetMaxSellEmptyPrice(userName, symbol.BaseCurrency, symbol.QuoteCurrency);
                    var sellQuantity      = DogControlUtils.GetEmptySize(userName, symbol.BaseCurrency, minSellEmptyPrice, nowPrice);
                    sellQuantity = decimal.Round(sellQuantity, symbol.AmountPrecision);

                    if (
                        (symbol.QuoteCurrency == "usdt" && sellQuantity * nowPrice < (decimal)0.8) ||
                        (symbol.QuoteCurrency == "btc" && sellQuantity * nowPrice < (decimal)0.00009) ||
                        (symbol.QuoteCurrency == "eth" && sellQuantity * nowPrice < (decimal)0.003) ||
                        (symbol.QuoteCurrency == "ht" && sellQuantity * nowPrice < (decimal)0.5)
                        )
                    {
                        Console.WriteLine($"    {symbol.BaseCurrency}{symbol.QuoteCurrency},做空不超过{sellQuantity * nowPrice},, sellQuantity: {sellQuantity},  nowPrice:{nowPrice}");
                        continue;
                    }

                    Console.WriteLine($"准备做空 sellQuantity:{sellQuantity}, nowPrice:{nowPrice}");
                    SellWhenDoEmpty(accountId, userName, symbol, sellQuantity, sellPrice, $"device:");
                }
                catch (Exception ex)
                {
                    logger.Error(ex.Message, ex);
                }
            }
        }
        public async Task <object> InitAccountInfo(string userName, string quoteCurrency, string sort, bool stat)
        {
            try
            {
                PlatformApi api         = PlatformApi.GetInstance(userName);
                var         accountInfo = api.GetAccountBalance(AccountConfigUtils.GetAccountConfig(userName).MainAccountId);

                var nowPriceList = new DogNowPriceDao().ListDogNowPrice(quoteCurrency);

                var result = new List <Dictionary <string, object> >();

                foreach (var balanceItem in accountInfo.Data.list)
                {
                    try
                    {
                        if (balanceItem.balance < (decimal)0.00001 || balanceItem.type == "frozen")
                        {
                            continue;
                        }

                        var nowPriceItem = nowPriceList.Find(it => it.SymbolName == balanceItem.currency);

                        if (stat && balanceItem.currency == "usdt")
                        {
                            new DogStatSymbolDao().CreateDogStatSymbol(new DogStatSymbol
                            {
                                Amount     = balanceItem.balance,
                                CreateTime = DateTime.Now,
                                EarnAmount = balanceItem.balance,
                                StatDate   = DateTime.Now.ToString("yyyy-MM-dd"),
                                SymbolName = balanceItem.currency,
                                UserName   = userName
                            });
                        }

                        if (nowPriceItem == null)
                        {
                            continue;
                        }

                        var totalQuantity = new DogMoreBuyDao().GetBuyQuantityOfDogMoreBuyIsNotFinished(userName, balanceItem.currency);
                        var kongAmount    = new DogEmptySellDao().GetSellAmountOfDogEmptySellIsNotFinished(userName, balanceItem.currency);
                        kongAmount = Math.Round(kongAmount, 6);

                        Dictionary <string, object> item = new Dictionary <string, object>();
                        item.Add("currency", balanceItem.currency);
                        item.Add("buyQuantity", totalQuantity);
                        item.Add("balance", Math.Round(balanceItem.balance, 6));
                        item.Add("nowPrice", nowPriceItem.NowPrice);
                        item.Add("kongAmount", kongAmount);
                        if (kongAmount > 0)
                        {
                            item.Add("canEmptyQuantity", Math.Round((balanceItem.balance - totalQuantity), 6) + $"({kongAmount})");
                        }
                        else
                        {
                            item.Add("canEmptyQuantity", Math.Round((balanceItem.balance - totalQuantity), 6));
                        }
                        item.Add("canEmptyAmount", Math.Round((balanceItem.balance - totalQuantity - kongAmount) * nowPriceItem.NowPrice, 6));

                        result.Add(item);

                        if (stat)
                        {
                            new DogStatSymbolDao().CreateDogStatSymbol(new DogStatSymbol
                            {
                                Amount     = balanceItem.balance,
                                CreateTime = DateTime.Now,
                                EarnAmount = (decimal)Math.Round((balanceItem.balance - totalQuantity - kongAmount), 6),
                                StatDate   = DateTime.Now.ToString("yyyy-MM-dd"),
                                SymbolName = balanceItem.currency,
                                UserName   = userName
                            });
                        }
                    }
                    catch (Exception ex)
                    {
                        logger.Error(ex.Message, ex);
                        logger.Info(JsonConvert.SerializeObject(balanceItem));
                    }
                }

                if (sort == "canEmptyAmountasc")
                {
                    result.Sort((a, b) => decimal.Compare((decimal)a["canEmptyAmount"], (decimal)b["canEmptyAmount"]));
                }
                if (sort == "canEmptyAmountdesc")
                {
                    result.Sort((a, b) => decimal.Compare((decimal)b["canEmptyAmount"], (decimal)a["canEmptyAmount"]));
                }
                else if (sort == "currencydesc")
                {
                    result.Sort((a, b) => string.Compare(b["currency"].ToString(), a["currency"].ToString()));
                }
                else if (sort == "currencyasc")
                {
                    result.Sort((a, b) => string.Compare(a["currency"].ToString(), b["currency"].ToString()));
                }

                return(result);
            }
            catch (Exception ex)
            {
                logger.Error(ex.Message, ex);
                throw ex;
            }
        }
Example #12
0
        private static void RunBuy(CommonSymbols symbol)
        {
            var key = HistoryKlinePools.GetKey(symbol, "1min");
            var historyKlineData = HistoryKlinePools.Get(key);

            if (historyKlineData == null || historyKlineData.Data == null || historyKlineData.Data.Count == 0 || historyKlineData.Date < DateTime.Now.AddMinutes(-1))// TODO
            {
                logger.Error($"RunBuy 数据还未准备好:{symbol.BaseCurrency}");
                Thread.Sleep(1000 * 5);
                return;
            }
            var historyKlines = historyKlineData.Data;

            // 获取最近行情
            decimal lastLowPrice;
            decimal nowPrice;
            // 分析是否下跌, 下跌超过一定数据,可以考虑
            decimal flexPercent   = (decimal)1.050;
            var     flexPointList = CoinAnalyze.Analyze(historyKlines, out lastLowPrice, out nowPrice, flexPercent);

            if (flexPointList == null || flexPointList.Count == 0 || (flexPointList.Count == 1 && flexPointList[0].isHigh))
            {
                flexPercent   = (decimal)1.045;
                flexPointList = CoinAnalyze.Analyze(historyKlines, out lastLowPrice, out nowPrice, flexPercent);
            }
            if (flexPointList == null || flexPointList.Count == 0 || (flexPointList.Count == 1 && flexPointList[0].isHigh))
            {
                flexPercent   = (decimal)1.040;
                flexPointList = CoinAnalyze.Analyze(historyKlines, out lastLowPrice, out nowPrice, flexPercent);
            }
            if (flexPointList == null || flexPointList.Count == 0 || (flexPointList.Count == 1 && flexPointList[0].isHigh))
            {
                flexPercent   = (decimal)1.035;
                flexPointList = CoinAnalyze.Analyze(historyKlines, out lastLowPrice, out nowPrice, flexPercent);
            }
            if (flexPointList == null || flexPointList.Count == 0 || (flexPointList.Count == 1 && flexPointList[0].isHigh))
            {
                flexPercent   = (decimal)1.03;
                flexPointList = CoinAnalyze.Analyze(historyKlines, out lastLowPrice, out nowPrice, flexPercent);
            }
            if (flexPointList == null || flexPointList.Count == 0 || (flexPointList.Count == 1 && flexPointList[0].isHigh))
            {
                flexPercent   = (decimal)1.025;
                flexPointList = CoinAnalyze.Analyze(historyKlines, out lastLowPrice, out nowPrice, flexPercent);
            }
            if (flexPointList == null || flexPointList.Count == 0 || (flexPointList.Count == 1 && flexPointList[0].isHigh))
            {
                flexPercent   = (decimal)1.02;
                flexPointList = CoinAnalyze.Analyze(historyKlines, out lastLowPrice, out nowPrice, flexPercent);
            }
            if (flexPointList == null || flexPointList.Count == 0 || (flexPointList.Count == 1 && flexPointList[0].isHigh))
            {
                flexPercent   = (decimal)1.015;
                flexPointList = CoinAnalyze.Analyze(historyKlines, out lastLowPrice, out nowPrice, flexPercent);
            }
            if (flexPointList.Count == 0 && flexPointList.Count == 0)
            {
                logger.Error($"RunBuy--------------> 分析{symbol.BaseCurrency}的flexPoint结果数量为0 ");
                return;
            }

            if (flexPointList[0].isHigh || JudgeBuyUtils.IsQuickRise(symbol.BaseCurrency, historyKlines)
                )//|| JudgeBuyUtils.CheckCalcMaxhuoluo(historyKlines)
            {
                // 最高点 不适合购入
                // 快速升高 不适合购入
                // 大量回落 不适合购入
                return;
            }

            var userNames = UserPools.GetAllUserName();

            foreach (var userName in userNames)
            {
                AccountConfig accountConfig = AccountConfigUtils.GetAccountConfig(userName);
                var           accountId     = accountConfig.MainAccountId;

                //var noSellList = new PigMoreDao().ListPigMore(accountId, userName, symbol.BaseCurrency, new List<string> { StateConst.PartialFilled, StateConst.Submitted, StateConst.Submitting, StateConst.PreSubmitted });
                var canBuy = JudgeBuyUtils.CheckCanBuy(nowPrice, flexPointList[0].close);
                if (!canBuy)
                {
                    continue;
                }

                decimal minBuyPrice = new PigMoreDao().GetMinPriceOfNotSell(accountId, userName, symbol.BaseCurrency);
                if (minBuyPrice <= 0)
                {
                    minBuyPrice = 999999;
                }
                //noSellList.ForEach(item =>
                //{
                //    if (item.BOrderP < minBuyPrice)
                //    {
                //        minBuyPrice = item.BOrderP;
                //    }
                //});

                if (nowPrice * (decimal)1.035 > minBuyPrice)
                {
                    // 最近一次购入,没有低于3%
                    continue;
                }

                PlatformApi api             = PlatformApi.GetInstance(userName);
                var         accountInfo     = api.GetAccountBalance(accountId);
                var         usdt            = accountInfo.Data.list.Find(it => it.currency == "usdt");
                decimal     recommendAmount = usdt.balance / 200; // TODO 测试阶段,暂定低一些,
                Console.WriteLine($"RunBuy--------> 开始 {symbol.BaseCurrency}  推荐额度:{decimal.Round(recommendAmount, 2)} ");

                if (recommendAmount < (decimal)0.3)
                {
                    continue;
                }

                // 获取最近的购买记录
                // 购买的要求
                // 1. 最近一次是低点, 并且有上升的迹象。
                // 2. 快速上升的,快速下降情况(如果升的太高, 最一定要回落,或者有5个小时平稳才考虑购入,)
                // 3. 如果flexpoint 小于等于1.02,则只能考虑买少一点。
                // 4. 余额要足够,推荐购买的额度要大于0.3
                // 5.

                decimal buyQuantity = recommendAmount / nowPrice;

                buyQuantity = decimal.Round(buyQuantity, symbol.AmountPrecision);
                if (symbol.BaseCurrency == "xrp" && buyQuantity <= 1)
                {
                    buyQuantity = (decimal)1.01;
                }
                decimal orderPrice = decimal.Round(nowPrice * (decimal)1.005, symbol.PricePrecision);

                OrderPlaceRequest req = new OrderPlaceRequest();
                req.account_id = accountId;
                req.amount     = buyQuantity.ToString();
                req.price      = orderPrice.ToString();
                req.source     = "api";
                req.symbol     = symbol.BaseCurrency + symbol.QuoteCurrency;
                req.type       = "buy-limit";
                if (BuyLimitUtils.Record(userName, symbol.BaseCurrency))
                {
                    logger.Error(" --------------------- 两个小时内购买次数太多,暂停一会 --------------------- ");
                    logger.Error(" --------------------- 两个小时内购买次数太多,暂停一会 --------------------- ");
                    logger.Error(" --------------------- 两个小时内购买次数太多,暂停一会 --------------------- ");
                    Thread.Sleep(1000 * 5);
                    return;
                }
                HBResponse <long> order = api.OrderPlace(req);
                if (order.Status == "ok")
                {
                    new PigMoreDao().CreatePigMore(new PigMore()
                    {
                        Name        = symbol.BaseCurrency,
                        AccountId   = accountId,
                        UserName    = accountConfig.UserName,
                        FlexPercent = flexPercent,

                        BQuantity          = buyQuantity,
                        BOrderP            = orderPrice,
                        BDate              = DateTime.Now,
                        BOrderResult       = JsonConvert.SerializeObject(order),
                        BState             = StateConst.PreSubmitted,
                        BTradeP            = 0,
                        BOrderId           = order.Data,
                        BFlex              = JsonConvert.SerializeObject(flexPointList),
                        BMemo              = "",
                        BOrderDetail       = "",
                        BOrderMatchResults = "",

                        SOrderId           = 0,
                        SOrderResult       = "",
                        SDate              = DateTime.MinValue,
                        SFlex              = "",
                        SMemo              = "",
                        SOrderDetail       = "",
                        SOrderMatchResults = "",
                        SOrderP            = 0,
                        SQuantity          = 0,
                        SState             = "",
                        STradeP            = 0,
                    });
                    // 下单成功马上去查一次
                    QueryBuyDetailAndUpdate(userName, order.Data);
                }
                logger.Error($"下单购买结果 {JsonConvert.SerializeObject(req)}, order:{JsonConvert.SerializeObject(order)}, 上一次最低购入价位:{minBuyPrice},nowPrice:{nowPrice}, accountId:{accountId}");
                logger.Error($"下单购买结果 分析 {JsonConvert.SerializeObject(flexPointList)}");
            }
        }
Example #13
0
        private static void RunSell(CommonSymbols symbol)
        {
            var key = HistoryKlinePools.GetKey(symbol, "1min");
            var historyKlineData = HistoryKlinePools.Get(key);

            if (historyKlineData == null || historyKlineData.Data == null || historyKlineData.Data.Count == 0 ||
                historyKlineData.Date < DateTime.Now.AddMinutes(-1))   // TODO
            {
                logger.Error($"RunSell 数据还未准备好:{symbol.BaseCurrency}");
                Thread.Sleep(1000 * 5);
                return;
            }

            var historyKlines = historyKlineData.Data;

            // 获取最近行情
            decimal lastLowPrice;
            decimal nowPrice;
            // 分析是否下跌, 下跌超过一定数据,可以考虑
            decimal flexPercent   = (decimal)1.050;
            var     flexPointList = CoinAnalyze.Analyze(historyKlines, out lastLowPrice, out nowPrice, flexPercent);

            if (flexPointList == null || flexPointList.Count == 0 || (flexPointList.Count == 1 && !flexPointList[0].isHigh))
            {
                flexPercent   = (decimal)1.045;
                flexPointList = CoinAnalyze.Analyze(historyKlines, out lastLowPrice, out nowPrice, flexPercent);
            }
            if (flexPointList == null || flexPointList.Count == 0 || (flexPointList.Count == 1 && !flexPointList[0].isHigh))
            {
                flexPercent   = (decimal)1.040;
                flexPointList = CoinAnalyze.Analyze(historyKlines, out lastLowPrice, out nowPrice, flexPercent);
            }
            if (flexPointList == null || flexPointList.Count == 0 || (flexPointList.Count == 1 && !flexPointList[0].isHigh))
            {
                flexPercent   = (decimal)1.035;
                flexPointList = CoinAnalyze.Analyze(historyKlines, out lastLowPrice, out nowPrice, flexPercent);
            }
            if (flexPointList == null || flexPointList.Count == 0 || (flexPointList.Count == 1 && !flexPointList[0].isHigh))
            {
                flexPercent   = (decimal)1.03;
                flexPointList = CoinAnalyze.Analyze(historyKlines, out lastLowPrice, out nowPrice, flexPercent);
            }
            if (flexPointList == null || flexPointList.Count == 0 || (flexPointList.Count == 1 && !flexPointList[0].isHigh))
            {
                flexPercent   = (decimal)1.025;
                flexPointList = CoinAnalyze.Analyze(historyKlines, out lastLowPrice, out nowPrice, flexPercent);
            }
            if (flexPointList == null || flexPointList.Count == 0 || (flexPointList.Count == 1 && !flexPointList[0].isHigh))
            {
                flexPercent   = (decimal)1.02;
                flexPointList = CoinAnalyze.Analyze(historyKlines, out lastLowPrice, out nowPrice, flexPercent);
            }
            if (flexPointList == null || flexPointList.Count == 0 || (flexPointList.Count == 1 && !flexPointList[0].isHigh))
            {
                flexPercent   = (decimal)1.015;
                flexPointList = CoinAnalyze.Analyze(historyKlines, out lastLowPrice, out nowPrice, flexPercent);
            }
            if (flexPointList.Count == 0 && flexPointList.Count == 0)
            {
                logger.Error($"--------------> 分析{symbol.BaseCurrency}的flexPoint结果数量为0 ");
                return;
            }

            if (!flexPointList[0].isHigh)
            {
                // 最低点 不适合出售
                logger.Error($"最低点 不适合出售 {symbol.BaseCurrency}-{flexPercent},lastLowPrice:{lastLowPrice}, nowPrice:{nowPrice}, flexPointList:{JsonConvert.SerializeObject(flexPointList)}");
                return;
            }

            var userNames = UserPools.GetAllUserName();

            foreach (var userName in userNames)
            {
                var accountConfig       = AccountConfigUtils.GetAccountConfig(userName);
                var accountId           = accountConfig.MainAccountId;
                var needSellPigMoreList = new PigMoreDao().GetNeedSellPigMore(accountId, userName, symbol.BaseCurrency);

                foreach (var needSellPigMoreItem in needSellPigMoreList)
                {
                    // 分析是否 大于
                    decimal itemNowPrice = 0;
                    decimal higher       = JudgeSellUtils.AnalyzeNeedSell(needSellPigMoreItem.BOrderP, needSellPigMoreItem.BDate, symbol.BaseCurrency, symbol.QuoteCurrency, out itemNowPrice, historyKlines);

                    decimal gaoyuPercentSell = (decimal)1.045;

                    bool needHuitou = true;// 如果很久没有出售过,则要考虑不需要回头
                    if (flexPercent < (decimal)1.04)
                    {
                        gaoyuPercentSell = (decimal)1.035;
                        if (flexPointList.Count <= 2 && needSellPigMoreList.Where(it => it.BDate > DateTime.Now.AddDays(-1)).ToList().Count == 0)
                        {
                            // 1天都没有交易. 并且波动比较小. 则不需要回头
                            needHuitou = false;
                        }
                    }

                    var canSell = JudgeSellUtils.CheckCanSell(needSellPigMoreItem.BOrderP, higher, itemNowPrice, gaoyuPercentSell, needHuitou);

                    //logger.Error($"是否能够出售:  {symbol.BaseCurrency},{canSell}, price:{needSellPigMoreItem.BOrderP}, nowPrice:{nowPrice},itemNowPrice:{itemNowPrice}, {userName}, {needSellPigMoreList.Count}, {accountId}");
                    if (canSell)
                    {
                        decimal sellQuantity = needSellPigMoreItem.BQuantity * (decimal)0.99;
                        sellQuantity = decimal.Round(sellQuantity, symbol.AmountPrecision);
                        if (symbol.BaseCurrency == "xrp" && sellQuantity < 1)
                        {
                            sellQuantity = 1;
                        }
                        // 出售
                        decimal           sellPrice = decimal.Round(itemNowPrice * (decimal)0.985, symbol.PricePrecision);
                        OrderPlaceRequest req       = new OrderPlaceRequest();
                        req.account_id = accountId;
                        req.amount     = sellQuantity.ToString();
                        req.price      = sellPrice.ToString();
                        req.source     = "api";
                        req.symbol     = symbol.BaseCurrency + symbol.QuoteCurrency;;
                        req.type       = "sell-limit";
                        PlatformApi       api   = PlatformApi.GetInstance(userName);
                        HBResponse <long> order = api.OrderPlace(req);
                        if (order.Status == "ok")
                        {
                            new PigMoreDao().ChangeDataWhenSell(needSellPigMoreItem.Id, sellQuantity, sellPrice, JsonConvert.SerializeObject(order), JsonConvert.SerializeObject(flexPointList), order.Data);
                            // 下单成功马上去查一次
                            QuerySellDetailAndUpdate(userName, order.Data);
                        }

                        logger.Error($"下单出售结果 {JsonConvert.SerializeObject(req)}, order:{JsonConvert.SerializeObject(order)},itemNowPrice:{itemNowPrice} higher:{higher},accountId:{accountId}");
                        logger.Error($"下单出售结果 分析 {JsonConvert.SerializeObject(flexPointList)}");
                    }
                }
            }
        }