Example #1
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 #2
0
        public static void CheckBuyOrSellState()
        {
            try
            {
                var needChangeBuyStateDogMoreBuyList = new DogMoreBuyDao().ListNeedChangeBuyStateDogMoreBuy();
                foreach (var item in needChangeBuyStateDogMoreBuyList)
                {
                    // 如果长时间没有购买成功, 则取消订单。
                    if (item.BuyDate < DateTime.Now.AddMinutes(-30))
                    {
                        //api.
                    }
                    // TODO
                    QueryBuyDetailAndUpdate(item.UserName, item.BuyOrderId);
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.Message, ex);
            }

            try
            {
                var needChangeSellStateDogMoreSellList = new DogMoreSellDao().ListNeedChangeSellStateDogMoreSell();
                foreach (var item in needChangeSellStateDogMoreSellList)
                {
                    // 如果长时间没有出售成功, 则取消订单。
                    // TODO
                    QuerySellDetailAndUpdate(item.UserName, item.SellOrderId);
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.Message, ex);
            }

            // 空
            try
            {
                var needChangeSellStateDogEmptySellList = new DogEmptySellDao().ListNeedChangeSellStateDogEmptySell();
                foreach (var item in needChangeSellStateDogEmptySellList)
                {
                    // 如果长时间没有出售成功, 则取消订单。
                    // TODO
                    QueryEmptySellDetailAndUpdate(item.UserName, item.SellOrderId);
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.Message, ex);
            }

            try
            {
                var needChangeBuyStateDogEmptyBuyList = new DogEmptyBuyDao().ListNeedChangeBuyStateDogEmptyBuy();
                //Console.WriteLine($"needChangeBuyStateDogEmptyBuyList: {needChangeBuyStateDogEmptyBuyList.Count}");
                foreach (var item in needChangeBuyStateDogEmptyBuyList)
                {
                    // 如果长时间没有出售成功, 则取消订单。
                    // TODO
                    QueryEmptyBuyDetailAndUpdate(item.UserName, item.BuyOrderId);
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.Message, ex);
            }
        }
Example #3
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 #4
0
        public static bool Run(int index, CommonSymbol symbol, List <Ticker> tickers)
        {
            // 先获取最近的数据, 看看是否靠近购入,卖出
            var minDogMoreBuy   = new DogMoreBuyDao().GetSmallestDogMoreBuy(symbol.QuoteCurrency, symbol.BaseCurrency);
            var maxDogEmptySell = new DogEmptySellDao().GetBiggestDogEmptySell(symbol.QuoteCurrency, symbol.BaseCurrency);
            var findTicker      = tickers.Find(it => it.symbol == symbol.BaseCurrency + symbol.QuoteCurrency);

            if (findTicker == null)
            {
                //logger.Error($"{symbol.QuoteCurrency}, {symbol.BaseCurrency}");
                return(false);
            }

            if (findTicker.open <= 0 || findTicker.close <= 0 || findTicker.high <= 0 || findTicker.low <= 0)
            {
                logger.Error($"数据不对 : {JsonConvert.SerializeObject(findTicker)}");
                return(false);
            }

            var control = new DogControlDao().GetDogControl(symbol.BaseCurrency, symbol.QuoteCurrency);

            if (control == null)
            {
                return(false);
            }

            if (control.HistoryMin >= findTicker.close || control.HistoryMax <= findTicker.close)
            {
                // 初始化一下
                RefreshHistoryMaxMinAsync(control.SymbolName, control.QuoteCurrency);
            }

            new DogNowPriceDao().CreateDogNowPrice(new DogNowPrice
            {
                NowPrice      = findTicker.close,
                NowTime       = Utils.GetIdByDate(DateTime.Now),
                QuoteCurrency = symbol.QuoteCurrency,
                SymbolName    = symbol.BaseCurrency,
                TodayMaxPrice = findTicker.high,
                TodayMinPrice = findTicker.low,
                NearMaxPrice  = findTicker.high
            });

            var maySell = false;
            var mayBuy  = false;

            if ((
                    control.EmptyPrice < findTicker.close && (
                        maxDogEmptySell == null ||
                        findTicker.close / maxDogEmptySell.SellOrderPrice > (decimal)1.082)
                    )

                || (maxDogEmptySell != null &&
                    maxDogEmptySell.SellOrderPrice / findTicker.close > (decimal)1.085))
            {
                maySell = true;
            }
            if (
                (control.MaxInputPrice > findTicker.close && (
                     minDogMoreBuy == null ||
                     minDogMoreBuy.BuyOrderPrice / findTicker.close > (decimal)1.062))

                || (minDogMoreBuy != null && findTicker.close / minDogMoreBuy.BuyOrderPrice > (decimal)1.09))
            {
                mayBuy = true;
                if (symbol.QuoteCurrency == "btc" && nobtcbalanceTime > DateTime.Now.AddMinutes(-5) && (
                        minDogMoreBuy == null || minDogMoreBuy.BuyOrderPrice / findTicker.close > (decimal)1.06
                        ))
                {
                    mayBuy = false;
                }
            }

            if (symbol.BaseCurrency == "xmx")
            {
                Console.WriteLine($"{maySell}, {mayBuy}");
            }
            if (!mayBuy && !maySell)
            {
                return(false);
            }

            AnalyzeResult analyzeResult = AnalyzeResult.GetAnalyzeResult(symbol);

            if (analyzeResult == null)
            {
                return(false);
            }

            try
            {
                // 计算是否适合购买
                RunBuy(symbol, analyzeResult);
            }
            catch (Exception ex)
            {
                logger.Error($"---> 购买异常: {JsonConvert.SerializeObject(symbol)}" + ex.Message, ex);
            }

            try
            {
                // 计算是否适合出售
                RunSell(symbol, analyzeResult, findTicker);

                RunCount++;
            }
            catch (Exception ex)
            {
                logger.Error($"---> 出售异常: {JsonConvert.SerializeObject(symbol)}" + ex.Message, ex);
            }

            return(true);
        }
Example #5
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);
                }
            }
        }
Example #6
0
        /// <summary>
        /// 购买,做多的时候
        /// </summary>
        /// <param name="symbol"></param>
        /// <param name="userName"></param>
        /// <param name="accountId"></param>
        public static void BuyWhenDoMore(CommonSymbol symbol, AccountConfig account, AnalyzeResult analyzeResult)
        {
            var accountId = account.MainAccountId;
            var userName  = account.UserName;
            var nowPrice  = analyzeResult.NowPrice;

            var dogMoreBuy          = new DogMoreBuyDao().GetMinBuyPriceDataOfNotSellFinished(accountId, userName, symbol.QuoteCurrency, symbol.BaseCurrency);
            var ladderBuyWhenDoMore = ladderMoreBuyPercent;

            if (symbol.QuoteCurrency == "usdt")
            {
                ladderBuyWhenDoMore = (decimal)1.06;
            }
            if (dogMoreBuy != null && (nowPrice * ladderBuyWhenDoMore > Math.Min(dogMoreBuy.BuyTradePrice, dogMoreBuy.BuyOrderPrice)))
            {
                throw new ApplicationException("有价格比这个更低得还没有收割。不能重新做多。");
            }

            PlatformApi api           = PlatformApi.GetInstance(userName);
            var         accountInfo   = api.GetAccountBalance(accountId);
            var         quoteCurrency = accountInfo.Data.list.Find(it => it.currency == symbol.QuoteCurrency);
            // 要减去空单未收割得额度总和
            var notShougeEmptySellAmount = new DogEmptySellDao().GetSumNotShougeDogEmptySell(userName, symbol.QuoteCurrency);

            if (!CommonHelper.CheckBalanceForDoMore(symbol.QuoteCurrency, quoteCurrency.balance, notShougeEmptySellAmount))
            {
                Console.WriteLine($"{symbol.BaseCurrency}{symbol.QuoteCurrency}余额不足notShougeEmptySellAmount:{notShougeEmptySellAmount},balance:{quoteCurrency.balance}");
                if (symbol.QuoteCurrency == "btc" && account.MainAccountId == "529880")
                {
                    nobtcbalanceTime = DateTime.Now;
                }
                throw new ApplicationException($"余额不足notShougeEmptySellAmount:{notShougeEmptySellAmount},balance:{quoteCurrency.balance}");
            }

            decimal recommendAmount = DogControlUtils.GetRecommendBuyAmount(symbol);
            var     maxBuyPrice     = new DogMoreBuyDao().GetMaxBuyPrice(accountId, userName, symbol.QuoteCurrency, symbol.BaseCurrency);

            recommendAmount = DogControlUtils.GetMoreSize(recommendAmount, maxBuyPrice, nowPrice);

            // 购买的要求
            decimal buyQuantity = recommendAmount / nowPrice;

            buyQuantity = CoinUtils.CalcTradeQuantity(symbol, buyQuantity);

            // 判断是否满足最小购买数量
            if (!CoinUtils.IsBiggerThenLeastBuyForDoMore(symbol.BaseCurrency, symbol.QuoteCurrency, buyQuantity))
            {
                Console.WriteLine($"    {symbol.BaseCurrency}{symbol.QuoteCurrency},做多数量太少,不符合最小交易额度");
                return;
            }

            buyQuantity = decimal.Round(buyQuantity, symbol.AmountPrecision);
            decimal orderPrice = decimal.Round(nowPrice * (decimal)1.006, 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 + symbol.QuoteCurrency))
            {
                logger.Error(" --------------------- 两个小时内购买次数太多,暂停一会 --------------------- ");
                Thread.Sleep(1000 * 10);
                return;
            }

            HBResponse <long> order = null;

            try
            {
                logger.Error($"");
                logger.Error($"1: 开始下单 -----------------------------{JsonConvert.SerializeObject(req)}");
                order = api.OrderPlace(req);
                logger.Error($"2: 下单结束 -----------------------------{JsonConvert.SerializeObject(order)}");

                if (order.Status == "ok")
                {
                    new DogMoreBuyDao().CreateDogMoreBuy(new DogMoreBuy()
                    {
                        SymbolName    = symbol.BaseCurrency,
                        QuoteCurrency = symbol.QuoteCurrency,
                        AccountId     = accountId,
                        UserName      = userName,

                        BuyQuantity          = buyQuantity,
                        BuyOrderPrice        = orderPrice,
                        BuyDate              = DateTime.Now,
                        BuyOrderResult       = JsonConvert.SerializeObject(order),
                        BuyState             = StateConst.PreSubmitted,
                        BuyTradePrice        = 0,
                        BuyOrderId           = order.Data,
                        BuyMemo              = "",
                        BuyOrderDetail       = "",
                        BuyOrderMatchResults = "",
                        IsFinished           = false
                    });

                    // 下单成功马上去查一次
                    QueryBuyDetailAndUpdate(userName, order.Data);
                }
                logger.Error($"3: 入库结束 -----------------------------做多  下单购买结果 {JsonConvert.SerializeObject(req)}, notShougeEmptySellAmount:{notShougeEmptySellAmount}, order:{JsonConvert.SerializeObject(order)}, nowPrice:{nowPrice}, accountId:{accountId},");
                logger.Error($"");
            }
            catch (Exception ex)
            {
                logger.Error($"严重严重 ---------------  下的出错  --------------{JsonConvert.SerializeObject(req)}");
                Thread.Sleep(1000 * 60 * 5);
                throw 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;
            }
        }
        private async Task <DogEmptyFinishedDTO> GetDogEmptyFinishedDTO(long sellOrderId)
        {
            var dogEmptySell     = new DogEmptySellDao().GetDogEmptySellBySellOrderId(sellOrderId);
            var orderMatchResult = JsonConvert.DeserializeObject <HBResponse <List <OrderMatchResult> > >(dogEmptySell.SellOrderMatchResults);
            var sellQuantity     = (decimal)0;
            var sellAmount       = (decimal)0;
            var sellFees         = (decimal)0;

            foreach (var item in orderMatchResult.Data)
            {
                sellAmount   += item.FilledAmount * item.price;
                sellQuantity += item.FilledAmount;
                sellFees     += item.FilledFees;
            }

            // 交易量,交易总额,  出售总额 出售数量,
            var buyQuantity     = (decimal)0;
            var buyAmount       = (decimal)0;
            var buyFees         = (decimal)0;
            var buyTradePrice   = (decimal)0;
            var buyDate         = DateTime.MaxValue;
            var dogEmptyBuyList = new DogEmptyBuyDao().ListDogEmptyBuyBySellOrderId(sellOrderId);

            foreach (var buy in dogEmptyBuyList)
            {
                var buyOrderMatchResult = JsonConvert.DeserializeObject <HBResponse <List <OrderMatchResult> > >(buy.BuyOrderMatchResults);
                foreach (var item in buyOrderMatchResult.Data)
                {
                    buyAmount   += item.FilledAmount * item.price;
                    buyQuantity += item.FilledAmount;
                    buyFees     += item.FilledFees;
                    if (buyTradePrice < item.price)
                    {
                        buyTradePrice = item.price;
                    }
                }
                if (buy.BuyDate < buyDate)
                {
                    buyDate = buy.BuyDate;
                }
            }
            return(new DogEmptyFinishedDTO
            {
                SellOrderId = sellOrderId,
                SymbolName = dogEmptySell.SymbolName,
                UserName = dogEmptySell.UserName,
                SellTradePrice = dogEmptySell.SellTradePrice,
                SellDate = dogEmptySell.SellDate,
                SellState = dogEmptySell.SellState,
                BuyQuantity = buyQuantity,
                BuyTradePrice = buyTradePrice,
                BuyDate = buyDate,
                BuyAmount = buyAmount,
                BuyFees = buyFees,
                SellAmount = sellAmount,
                SellQuantity = sellQuantity,
                SellFees = sellFees,
                Usdt = sellAmount - buyAmount - sellFees,
                BaseSymbol = buyQuantity - sellQuantity - buyFees
            });
        }
Example #9
0
        public static void InitMarketInDBFromOut(CommonSymbol symbol, List <HistoryKline> klines)
        {
            try
            {
                var dogControl = DogControlUtils.GetDogControl(symbol.BaseCurrency, symbol.QuoteCurrency);
                if (dogControl == null)
                {
                    Console.WriteLine("InitMarketInDBFromOut dogControl is null");
                    return;
                }

                var dao             = new KlineDao();
                var dogMoreBuyDao   = new DogMoreBuyDao();
                var dogEmptySellDao = new DogEmptySellDao();

                // 去数据库中拉取数据, 判断是否超过5分钟,  或者是否离目标差4%,
                var lastKlines = dao.ListKlines(symbol.QuoteCurrency, symbol.BaseCurrency, 20);

                var findList = lastKlines.FindAll(it => klines.Find(item => item.Id == it.Id) != null).ToList();

                klines.Sort((a, b) => (int)(a.Id - b.Id));
                foreach (var kline in klines)
                {
                    var finds = findList.FindAll(it => it.Id == kline.Id);
                    if (finds.Count > 1)
                    {
                        //Console.WriteLine("新增数据 finds.Count > 1");
                        // 删除,新增
                        dao.DeleteAndRecordKlines(symbol.QuoteCurrency, symbol.BaseCurrency, kline);
                    }
                    else if (finds.Count == 1)
                    {
                        if (finds[0].Low != kline.Low || finds[0].High != kline.High || finds[0].Open != kline.Open || finds[0].Close != kline.Close)
                        {
                            // 删除新增  从外面来的数据, 如果不一致, 不插入
                            dao.DeleteAndRecordKlines(symbol.QuoteCurrency, symbol.BaseCurrency, kline);
                        }
                    }
                    else
                    {
                        // 新增
                        //Console.WriteLine($"新增数据 {symbol.BaseCurrency} {symbol.QuoteCurrency}");
                        dao.DeleteAndRecordKlines(symbol.QuoteCurrency, symbol.BaseCurrency, kline);
                    }
                }

                {
                    var last24Klines  = dao.List24HourKline(symbol.QuoteCurrency, symbol.BaseCurrency);
                    var todayKlines   = last24Klines.FindAll(it => Utils.GetDateById(it.Id) > DateTime.Now.Date).ToList();
                    var minutesKlines = last24Klines.FindAll(it => Utils.GetDateById(it.Id) > DateTime.Now.Date.AddMinutes(-30)).ToList();
                    var nearMaxPrice  = (decimal)0;
                    var todayMinPrice = (decimal)0;
                    var todayMaxPrice = (decimal)0;
                    if (todayKlines.Count > 0)
                    {
                        todayMaxPrice = todayKlines.Max(it => it.Close);
                        todayMinPrice = todayKlines.Min(it => it.Close);
                    }
                    if (minutesKlines.Count > 0)
                    {
                        nearMaxPrice = minutesKlines.Max(it => it.Close);
                    }
                    var lastKline = klines[klines.Count - 1];
                    new DogNowPriceDao().CreateDogNowPrice(new DogNowPrice
                    {
                        NowPrice      = lastKline.Close,
                        NowTime       = lastKline.Id,
                        QuoteCurrency = symbol.QuoteCurrency,
                        SymbolName    = symbol.BaseCurrency,
                        TodayMaxPrice = todayMaxPrice,
                        TodayMinPrice = todayMinPrice,
                        NearMaxPrice  = nearMaxPrice
                    });
                }
            }
            catch (Exception ex)
            {
                logger.Error("InitMarketInDB --> " + ex.Message, ex);
            }
        }