Beispiel #1
0
        /// <summary>
        /// 当购买或者出售时候,需要一个分析结果, 供判断是否做多,或者做空
        /// </summary>
        /// <param name="symbol"></param>
        /// <param name="isBuy"></param>
        /// <returns></returns>
        public static AnalyzeResult GetAnalyzeResult(CommonSymbol symbol)
        {
            var now           = DateTime.Now;
            var historyKlines = KlineUtils.ListKlines(symbol);

            if (historyKlines == null || historyKlines.Count < 100)
            {
                return(null);
            }

            var minute30Klines = historyKlines.FindAll(it => it.Id > Utils.GetIdByDate(DateTime.Now.AddMinutes(-30)));

            AnalyzeResult analyzeResult = new AnalyzeResult()
            {
                NowPrice      = historyKlines[0].Close,
                MaxPrice      = historyKlines.Max(it => it.Close),
                MinPrice      = historyKlines.Min(it => it.Close),
                HistoryKlines = historyKlines,
            };
            var milSecond = (DateTime.Now - now).TotalMilliseconds;

            if (milSecond > 1000)
            {
                Console.WriteLine($"GetAnalyzeResult: 花费时间:{milSecond}");
            }
            return(analyzeResult);
        }
Beispiel #2
0
        public static void InitMarketInDB(int index, CommonSymbol symbol, bool forceUpdate = false)
        {
            try
            {
                PlatformApi api    = PlatformApi.GetInstance("xx"); // 下面api和角色无关. 随便指定一个xx
                var         period = "1min";
                var         count  = 12;
                var         klines = api.GetHistoryKline(symbol.BaseCurrency + symbol.QuoteCurrency, period, count);
                if (klines == null || klines.Count == 0)
                {
                    return;
                }

                var         client = new RestClient("http://118.31.44.235/api/Control/newSymbolData");
                RestRequest req    = new RestRequest(Method.POST);
                req.AddHeader("content-type", "application/json");
                req.AddHeader("cache-type", "no-cache");
                req.AddJsonBody(new
                {
                    BaseCurrency  = symbol.BaseCurrency,
                    QuoteCurrency = symbol.QuoteCurrency,
                    HistoryKlines = klines
                });
                var response = client.ExecuteTaskAsync(req).Result;
            }
            catch (Exception ex)
            {
                logger.Error("InitMarketInDB --> " + ex.Message, ex);
            }
        }
Beispiel #3
0
        public async Task <string> shouge(long orderId)
        {
            try
            {
                var dogMoreBuy = new DogMoreBuyDao().GetDogMoreBuyByBuyOrderId(orderId);
                if (dogMoreBuy.IsFinished)
                {
                    return("已完成出售");
                }

                var dogMoreSellList = new DogMoreSellDao().ListDogMoreSellByBuyOrderId(orderId);
                if (dogMoreSellList.Count > 0 &&
                    dogMoreSellList.Find(it =>
                                         it.SellState != StateConst.Canceled.ToString() &&
                                         it.SellState != StateConst.PartialFilled.ToString() &&
                                         it.SellState != StateConst.Filled.ToString()
                                         ) != null)
                {
                    // 存在操作中的,则不操作
                    return("存在出售中的");
                }

                var          symbols = CoinUtils.GetAllCommonSymbols(dogMoreBuy.QuoteCurrency);
                CommonSymbol symbol  = symbols.Find(it => it.BaseCurrency == dogMoreBuy.SymbolName);

                CoinTrade.ShouGeDogMore(dogMoreBuy, symbol);

                return("操作结束");
            }
            catch (Exception ex)
            {
                logger.Error(ex.Message, ex);
                return(ex.Message);
            }
        }
Beispiel #4
0
        public static void RunAlert(CommonSymbol symbol, decimal big, decimal small)
        {
            Task.Run(() =>
            {
                while (true)
                {
                    try
                    {
                        PlatformApi api = PlatformApi.GetInstance("xx");
                        var period      = "1min";
                        var klines      = api.GetHistoryKline(symbol.BaseCurrency + symbol.QuoteCurrency, period);

                        var nowPrice = klines[0].Close;
                        Console.WriteLine(klines[0].Close);

                        if (nowPrice > big)
                        {
                            System.Diagnostics.Process.Start("explorer.exe", "http://blog.csdn.net/testcs_dn");
                        }

                        if (nowPrice < small)
                        {
                            System.Diagnostics.Process.Start("explorer.exe", "http://blog.csdn.net/testcs_dn");
                        }
                    }
                    catch (Exception ex)
                    {
                    }
                    Thread.Sleep(1000 * 5);
                }
            });
        }
Beispiel #5
0
 private static void RunHistoryKline(CommonSymbol symbol)
 {
     Task.Run(() =>
     {
         var countSuccess = 0;
         var countError   = 0;
         PlatformApi api  = PlatformApi.GetInstance("xx"); // 下面api和角色无关. 随便指定一个xx
         var begin        = DateTime.Now;
         while (true)
         {
             try
             {
                 var period = "1min";
                 var klines = api.GetHistoryKline(symbol.BaseCurrency + symbol.QuoteCurrency, period);
                 var key    = HistoryKlinePools.GetKey(symbol, period);
                 HistoryKlinePools.Init(key, klines);
                 countSuccess++;
             }
             catch (Exception ex)
             {
                 countError++;
             }
             if (countSuccess % 20 == 0)
             {
                 Console.WriteLine($"RunHistoryKline -> {symbol.BaseCurrency}, Success:{countSuccess}, Error:{countError}, AvageSecond:{(DateTime.Now - begin).TotalSeconds / (countSuccess + countError)}");
             }
             Thread.Sleep(1000 * 6);
         }
     });
 }
        public async Task <string> shouge(long orderId)
        {
            try
            {
                var dogEmptySell = new DogEmptySellDao().GetDogEmptySellBySellOrderId(orderId);
                if (dogEmptySell.IsFinished)
                {
                    return("已经完成的不操作");
                }

                var dogEmptyBuyList = new DogEmptyBuyDao().ListDogEmptyBuyBySellOrderId(orderId);
                if (dogEmptyBuyList.Count > 0 && dogEmptyBuyList.Find(it => it.BuyState != StateConst.Canceled.ToString() && it.BuyState != StateConst.PartialFilled.ToString() && it.BuyState != StateConst.Filled.ToString()) != null)
                {
                    // 存在操作中的,则不操作
                    return("存在操作中的,则不操作");
                }

                CommonSymbol symbol = CoinUtils.GetCommonSymbol(dogEmptySell.SymbolName, dogEmptySell.QuoteCurrency);

                // 先初始化一下
                AnalyzeResult analyzeResult = AnalyzeResult.GetAnalyzeResult(symbol);
                if (analyzeResult == null)
                {
                    return("分析结果未null");
                }
                return(CoinTrade.ShouGeDogEmpty(dogEmptySell, symbol, analyzeResult, true));
            }
            catch (Exception ex)
            {
                logger.Error($"严重 orderId:{orderId}- {ex.Message}", ex);
                return(ex.Message);
            }
        }
Beispiel #7
0
        public static List <HistoryKline> ListKlines(CommonSymbol symbol)
        {
            var         now    = DateTime.Now;
            PlatformApi api    = PlatformApi.GetInstance("xx");
            var         period = "1min";
            var         count  = 200;
            var         klines = api.GetHistoryKline(symbol.BaseCurrency + symbol.QuoteCurrency, period, count);

            if (klines == null || klines.Count == 0)
            {
                return(null);
            }
            Console.WriteLine($"listklines: 花费时间:{(DateTime.Now - now).TotalMilliseconds}, {klines[0].Id} {klines[klines.Count - 1].Id}");
            return(klines);
        }
Beispiel #8
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)
                {
                }
            }
        }
Beispiel #9
0
 public static decimal GetRecommendBuyAmount(CommonSymbol symbol)
 {
     if (symbol.QuoteCurrency == "usdt")
     {
         return((decimal)2);
     }
     else if (symbol.QuoteCurrency == "btc")
     {
         return((decimal)0.00019);
     }
     else if (symbol.QuoteCurrency == "eth")
     {
         return((decimal)0.007);
     }
     else if (symbol.QuoteCurrency == "ht")
     {
         return((decimal)1.3);
     }
     throw new ApplicationException("不合理的数据");
 }
Beispiel #10
0
        public static void ForceShouge(CommonSymbol symbol, decimal price, string orderId)
        {
            try
            {
                PlatformApi api    = PlatformApi.GetInstance("xx");
                var         period = "1min";
                var         klines = api.GetHistoryKline(symbol.BaseCurrency + symbol.QuoteCurrency, period);

                var nowPrice = klines[0].Close;
                Console.WriteLine(klines[0].Close);

                if (nowPrice < price)
                {
                    System.Diagnostics.Process.Start("explorer.exe", "http://118.31.44.235/api/empty/forceShouge?orderid=" + orderId);
                }
            }
            catch (Exception ex)
            {
            }
            Thread.Sleep(1000 * 5);
        }
Beispiel #11
0
        public static string BuyWhenDoMoreAnalyze(CommonSymbol symbol, AccountConfig account, decimal ladderBuyPercent)
        {
            AnalyzeResult analyzeResult = AnalyzeResult.GetAnalyzeResult(symbol);

            if (analyzeResult == null)
            {
                // 初始化数据, 再次拿去
                analyzeResult = AnalyzeResult.GetAnalyzeResult(symbol);
                if (analyzeResult == null)
                {
                    throw new ApplicationException("做多失败,分析出错");
                }
            }

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

            // 1.低于管控的购入价
            var controlCanBuy = JudgeBuyUtils.ControlCanBuy(symbol.BaseCurrency, symbol.QuoteCurrency, nowPrice);

            if (!controlCanBuy)
            {
                return($"判断 发现不适合 controlCanBuy:{controlCanBuy}");
            }

            try
            {
                BuyWhenDoMore(symbol, account, analyzeResult);
            }
            catch (Exception ex)
            {
                //logger.Error($"{userName} {JsonConvert.SerializeObject(symbol)} {ex.Message}", ex);
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex);
                return(ex.Message);
            }
            return("----");
        }
Beispiel #12
0
        public static void InitKlineInToPool(CommonSymbol symbol)
        {
            try
            {
                var period = "1min";
                var key    = HistoryKlinePools.GetKey(symbol, period);

                var dao        = new KlineDao();
                var lastKlines = dao.List24HourKline(symbol.QuoteCurrency, symbol.BaseCurrency);
                if (lastKlines.Count < 900)
                {
                    logger.Error($"{symbol.BaseCurrency},{symbol.QuoteCurrency}数据量太少{lastKlines.Count},无法分析啊:");
                }
                if (lastKlines.Count > 600)
                {
                    HistoryKlinePools.Init(key, lastKlines);
                }
            }
            catch (Exception ex)
            {
                logger.Error("InitOneKine --> " + ex.Message, ex);
            }
        }
        /// <summary>
        /// 计算多单收割的数量
        /// </summary>
        /// <param name="buyQuantity"></param>
        /// <param name="buyTradePrice"></param>
        /// <param name="nowPrice"></param>
        /// <param name="symbol"></param>
        /// <returns></returns>
        public static decimal CalcSellQuantityForMoreShouge(decimal buyQuantity, decimal buyTradePrice, decimal nowPrice, CommonSymbol symbol)
        {
            if (nowPrice <= buyTradePrice * (decimal)1.03)
            {
                throw new Exception("收割多价格不合理");
            }

            // 作用是,价格越高,则收割的量越多
            var position = (decimal)0.66;

            // 作用是,价格越高,则收割的量越多
            decimal sellQuantity = buyQuantity * buyTradePrice / nowPrice;

            sellQuantity = sellQuantity + (buyQuantity - sellQuantity) * position;
            sellQuantity = decimal.Round(sellQuantity, symbol.AmountPrecision);

            var newSellQuantity = sellQuantity;

            if (newSellQuantity == buyQuantity)
            {
                if (symbol.AmountPrecision == 4)
                {
                    newSellQuantity -= (decimal)0.0001;
                }
                else if (symbol.AmountPrecision == 3)
                {
                    newSellQuantity -= (decimal)0.001;
                }
                else if (symbol.AmountPrecision == 2)
                {
                    newSellQuantity -= (decimal)0.01;
                }
                else if (symbol.AmountPrecision == 1)
                {
                    newSellQuantity -= (decimal)0.1;
                }
                else if (symbol.AmountPrecision == 0)
                {
                    newSellQuantity -= (decimal)1;
                }
            }

            // 是否满足最小出售数量
            if (!CoinUtils.IsBiggerThenLeast(symbol.BaseCurrency, symbol.QuoteCurrency, sellQuantity))
            {
                newSellQuantity = CoinUtils.GetLeast(symbol.BaseCurrency, symbol.QuoteCurrency);
            }

            if (buyQuantity > newSellQuantity && buyQuantity * buyTradePrice < newSellQuantity * nowPrice)
            {
                return(newSellQuantity);
            }

            throw new Exception($"计算sellquantity不合理, buyQuantity:{buyQuantity},newSellQuantity:{newSellQuantity}, 没有赚头");
        }
Beispiel #14
0
 public static string GetKey(CommonSymbol symbol, string period)
 {
     return(symbol.BaseCurrency + "-" + symbol.QuoteCurrency + "-" + period);
 }
Beispiel #15
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);
        }
Beispiel #16
0
        public static void ShouGeDogMore(DogMoreBuy dogMoreBuy, CommonSymbol symbol, AnalyzeResult analyzeResult = null)
        {
            if (analyzeResult == null)
            {
                analyzeResult = AnalyzeResult.GetAnalyzeResult(symbol);
            }
            if (analyzeResult == null)
            {
                return;
            }

            var nowPrice = analyzeResult.NowPrice;

            var thisLadderMoreSellPercent = ladderMoreSellPercent;

            if (analyzeResult.NowPrice / analyzeResult.MinPrice > (decimal)1.20)
            {
                thisLadderMoreSellPercent = (decimal)1.085;
            }
            else if (analyzeResult.NowPrice / analyzeResult.MinPrice > (decimal)1.30)
            {
                thisLadderMoreSellPercent = (decimal)1.08;
            }
            else if (analyzeResult.NowPrice / analyzeResult.MinPrice > (decimal)1.40)
            {
                thisLadderMoreSellPercent = (decimal)1.075;
            }
            else if (analyzeResult.NowPrice / analyzeResult.MinPrice > (decimal)1.50)
            {
                thisLadderMoreSellPercent = (decimal)1.07;
            }
            else if (analyzeResult.NowPrice / analyzeResult.MinPrice > (decimal)1.60)
            {
                thisLadderMoreSellPercent = (decimal)1.065;
            }
            thisLadderMoreSellPercent = Math.Max(thisLadderMoreSellPercent, (decimal)1.065);

            // 没有大于预期, 也不能收割
            if (nowPrice < dogMoreBuy.BuyTradePrice * thisLadderMoreSellPercent)
            {
                return;
            }

            if (!analyzeResult.CheckCanSellForHuiDiao(dogMoreBuy))
            {
                Console.WriteLine("不满足回调");
                // 判断是否有回掉
                return;
            }

            // 计算要出的数量
            decimal sellQuantity = JudgeSellUtils.CalcSellQuantityForMoreShouge(dogMoreBuy.BuyQuantity, dogMoreBuy.BuyTradePrice, nowPrice, symbol);
            // 计算要出的价格
            decimal sellPrice = decimal.Round(nowPrice * (decimal)0.988, symbol.PricePrecision);

            if (sellQuantity >= dogMoreBuy.BuyQuantity)
            {
                Console.WriteLine("出售的量过多");
                return;
            }
            if (sellQuantity * sellPrice <= dogMoreBuy.BuyQuantity * dogMoreBuy.BuyTradePrice)
            {
                //logger.Error($"{dogMoreBuy.SymbolName}{dogMoreBuy.QuoteCurrency} 未实现双向收益 sellQuantity:{sellQuantity}, BuyQuantity:{dogMoreBuy.BuyQuantity},sellQuantity * nowPrice:{sellQuantity * nowPrice},dogMoreBuy.BuyQuantity * dogMoreBuy.BuyTradePrice:{dogMoreBuy.BuyQuantity * dogMoreBuy.BuyTradePrice}");
                return;
            }

            OrderPlaceRequest req = new OrderPlaceRequest();

            req.account_id = dogMoreBuy.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(dogMoreBuy.UserName);
            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")
                {
                    DogMoreSell dogMoreSell = new DogMoreSell()
                    {
                        AccountId             = dogMoreBuy.AccountId,
                        UserName              = dogMoreBuy.UserName,
                        BuyOrderId            = dogMoreBuy.BuyOrderId,
                        SellOrderId           = order.Data,
                        SellOrderResult       = JsonConvert.SerializeObject(order),
                        SellDate              = DateTime.Now,
                        SellQuantity          = sellQuantity,
                        SellOrderPrice        = sellPrice,
                        SellState             = StateConst.Submitted,
                        SellTradePrice        = 0,
                        SymbolName            = symbol.BaseCurrency,
                        QuoteCurrency         = symbol.QuoteCurrency,
                        SellMemo              = "",
                        SellOrderDetail       = "",
                        SellOrderMatchResults = ""
                    };
                    new DogMoreSellDao().CreateDogMoreSell(dogMoreSell);

                    // 下单成功马上去查一次
                    QuerySellDetailAndUpdate(dogMoreBuy.UserName, order.Data);
                }
                logger.Error($"3:入库结束 ----------------------------- 多单收割 --> {JsonConvert.SerializeObject(dogMoreBuy)}");
                logger.Error($"");
            }
            catch (Exception ex)
            {
                logger.Error($"严重严重111111 -----------------------------  多单收割出错");
                Thread.Sleep(1000 * 60 * 5);
                throw ex;
            }
        }
Beispiel #17
0
        private static void SellWhenDoEmpty(string accountId, string userName, CommonSymbol symbol, decimal sellQuantity, decimal sellPrice, string sellMemo = "")
        {
            try
            {
                if ((symbol.AmountPrecision == 0 && sellQuantity < (decimal)20) ||
                    (symbol.AmountPrecision == 1 && sellQuantity < (decimal)2) ||
                    (symbol.AmountPrecision == 2 && sellQuantity < (decimal)0.2) ||
                    (symbol.AmountPrecision == 3 && sellQuantity < (decimal)0.02) ||
                    (symbol.AmountPrecision == 4 && sellQuantity < (decimal)0.002))
                {
                    LogNotBuy(symbol.BaseCurrency + "-empty-sell", $"sell userName:{userName} 出错,{symbol.BaseCurrency} 的精度为 {symbol.AmountPrecision}, 但是却要出售{sellQuantity}  ");
                    return;
                }

                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 = null;
                try
                {
                    logger.Error($"");
                    logger.Error($"1: 开始下单 -----------------------------{JsonConvert.SerializeObject(req)}");
                    order = api.OrderPlace(req);
                    logger.Error($"2: 下单结束 -----------------------------{JsonConvert.SerializeObject(req)}");

                    if (order.Status == "ok")
                    {
                        DogEmptySell dogEmptySell = new DogEmptySell()
                        {
                            AccountId             = accountId,
                            UserName              = userName,
                            SellOrderId           = order.Data,
                            SellOrderResult       = JsonConvert.SerializeObject(order),
                            SellDate              = DateTime.Now,
                            SellQuantity          = sellQuantity,
                            SellOrderPrice        = sellPrice,
                            SellState             = StateConst.Submitted,
                            SellTradePrice        = 0,
                            SymbolName            = symbol.BaseCurrency,
                            QuoteCurrency         = symbol.QuoteCurrency,
                            SellMemo              = sellMemo,
                            SellOrderDetail       = "",
                            SellOrderMatchResults = "",
                            IsFinished            = false
                        };
                        new DogEmptySellDao().CreateDogEmptySell(dogEmptySell);

                        // 下单成功马上去查一次
                        QueryEmptySellDetailAndUpdate(userName, order.Data);
                    }
                    logger.Error($"3: 入库结束 -----------------------------做空 {JsonConvert.SerializeObject(req)}下单出售结果:" + JsonConvert.SerializeObject(order));
                    logger.Error($"");
                }
                catch (Exception ex)
                {
                    logger.Error($"严重 ---------------  做空出错  --------------{JsonConvert.SerializeObject(req)}");
                    Thread.Sleep(1000 * 60 * 5);
                    throw ex;
                }
            }
            catch (Exception ex)
            {
                logger.Error($"SellWhenDoEmpty  {ex.Message}", ex);
            }
        }
Beispiel #18
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);
        }
Beispiel #19
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);
                }
            }
        }
Beispiel #20
0
        public static string ShouGeDogEmpty(DogEmptySell dogEmptySell, CommonSymbol symbol, AnalyzeResult analyzeResult, bool isShouge = false)
        {
            var nowPrice = analyzeResult.NowPrice;
            var ladderEmptyWhenShouGe = ladderEmptyBuyPercent;

            if (isShouge)
            {
                ladderEmptyWhenShouGe = (decimal)1.05;
            }
            if (nowPrice * ladderEmptyWhenShouGe > dogEmptySell.SellTradePrice)
            {
                Console.WriteLine("没有收益,不能收割");
                return("没有收益,不能收割");
            }

            if (!analyzeResult.CheckCanBuyForHuiDiao(dogEmptySell))
            {
                return("没有回调");
            }

            decimal buyQuantity = CommonHelper.CalcBuyQuantityForEmptyShouge(dogEmptySell.SellQuantity, dogEmptySell.SellTradePrice, nowPrice, symbol);

            if (buyQuantity <= dogEmptySell.SellQuantity || nowPrice * buyQuantity >= dogEmptySell.SellQuantity * dogEmptySell.SellTradePrice)
            {
                Console.WriteLine($"     {symbol.BaseCurrency}{symbol.QuoteCurrency}没有实现双向收益, 不能收割空单");
                return("没有实现双向收益, 不能收割空单");
            }
            decimal orderPrice = decimal.Round(nowPrice * (decimal)1.01, symbol.PricePrecision);

            OrderPlaceRequest req = new OrderPlaceRequest();

            req.account_id = dogEmptySell.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(dogEmptySell.UserName, symbol.BaseCurrency + symbol.QuoteCurrency))
            {
                logger.Error(" --------------------- 两个小时内购买次数太多,暂停一会 --------------------- ");
                Thread.Sleep(1000 * 5);
                return(" 两个小时内购买次数太多,暂停一会");
            }

            PlatformApi       api   = PlatformApi.GetInstance(dogEmptySell.UserName);
            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 DogEmptyBuyDao().CreateDogEmptyBuy(new DogEmptyBuy()
                    {
                        SymbolName    = symbol.BaseCurrency,
                        QuoteCurrency = symbol.QuoteCurrency,
                        AccountId     = dogEmptySell.AccountId,
                        UserName      = dogEmptySell.UserName,
                        SellOrderId   = dogEmptySell.SellOrderId,

                        BuyQuantity          = buyQuantity,
                        BuyOrderPrice        = orderPrice,
                        BuyDate              = DateTime.Now,
                        BuyOrderResult       = JsonConvert.SerializeObject(order),
                        BuyState             = StateConst.PreSubmitted,
                        BuyTradePrice        = 0,
                        BuyOrderId           = order.Data,
                        BuyMemo              = "",
                        BuyOrderDetail       = "",
                        BuyOrderMatchResults = "",
                    });
                    // 下单成功马上去查一次
                    QueryEmptyBuyDetailAndUpdate(dogEmptySell.UserName, order.Data);
                }
                logger.Error($"3: 入库结束 ----------------------------- 空单收割");
                logger.Error($"");
                return("运行结束");
            }
            catch (Exception ex)
            {
                logger.Error($"严重严重 --------------- 空单收割出错");
                Thread.Sleep(1000 * 60 * 5);
                throw ex;
            }
        }
Beispiel #21
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;
            }
        }
Beispiel #22
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);
            }
        }
Beispiel #23
0
 public static void CheckTableExistAndCreate(CommonSymbol symbol)
 {
     new KlineDao().CheckTableExistsAndCreate(symbol.QuoteCurrency, symbol.BaseCurrency);
 }
Beispiel #24
0
        /// <summary>
        /// 获取行情数据
        /// </summary>
        /// <param name="symbol"></param>
        public static void InitOneKine(CommonSymbol symbol)
        {
            try
            {
                var         begin  = DateTime.Now;
                PlatformApi api    = PlatformApi.GetInstance("xx"); // 下面api和角色无关. 随便指定一个xx
                var         period = "1min";
                var         klines = api.GetHistoryKline(symbol.BaseCurrency + symbol.QuoteCurrency, period, 10);
                var         key    = HistoryKlinePools.GetKey(symbol, period);
                //HistoryKlinePools.Init(key, klines);

                var totalMilliseconds = (DateTime.Now - begin).TotalMilliseconds;
                if ((DateTime.Now - begin).TotalSeconds > 5)
                {
                    logger.Error("一次请求时间太长,达到:" + totalMilliseconds);
                }
                // 记录到数据库, 记录最近得数据。
                Record(symbol.BaseCurrency, klines[0]);

                var dao        = new KlineDao();
                var lastKlines = dao.List24HourKline(symbol.QuoteCurrency, symbol.BaseCurrency);
                var findList   = lastKlines.FindAll(it => klines.Find(item => item.Id == it.Id) != null).ToList();
                foreach (var kline in klines)
                {
                    var finds = findList.FindAll(it => it.Id == kline.Id);
                    if (finds.Count > 1)
                    {
                        // 删除,新增
                        new KlineDao().DeleteAndRecordKlines(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)
                        {
                            // 删除新增
                            new KlineDao().DeleteAndRecordKlines(symbol.BaseCurrency, kline);
                        }
                    }
                    else
                    {
                        // 直接新增
                        Record(symbol.BaseCurrency, kline);
                    }
                }

                if (lastKlines.Count < 900)
                {
                    logger.Error($"{symbol.BaseCurrency}数据量太少{lastKlines.Count},无法分析啊:" + totalMilliseconds);
                }
                if (lastKlines.Count > 600)
                {
                    HistoryKlinePools.Init(key, lastKlines);
                }

                totalMilliseconds = (DateTime.Now - begin).TotalMilliseconds;
                if ((DateTime.Now - begin).TotalSeconds > 9)
                {
                    logger.Error("一次请求时间太长 含插入数据库,达到:" + totalMilliseconds);
                }
            }
            catch (Exception ex)
            {
                logger.Error("InitOneKine --> " + ex.Message, ex);
            }
        }
Beispiel #25
0
        /// <summary>
        /// 空单收割时候,计算收割购入的数量
        /// </summary>
        /// <param name="sellQuantity"></param>
        /// <param name="sellTradePrice"></param>
        /// <param name="nowPrice"></param>
        /// <returns></returns>
        public static decimal CalcBuyQuantityForEmptyShouge(decimal sellQuantity, decimal sellTradePrice, decimal nowPrice, CommonSymbol symbol)
        {
            if (nowPrice >= sellTradePrice * (decimal)0.99)
            {
                throw new Exception("收割空价格不合理");
            }
            var position = DogControlUtils.GetLadderPosition(symbol.BaseCurrency, symbol.QuoteCurrency, nowPrice);

            position += (decimal)0.16;
            if (position <= (decimal)0.42)
            {
                position = (decimal)0.42;
            }
            if (position >= (decimal)0.82)
            {
                position = (decimal)0.82;
            }

            decimal buyQuantity = sellQuantity * sellTradePrice / nowPrice;

            buyQuantity = buyQuantity - (buyQuantity - sellQuantity) * position;
            buyQuantity = decimal.Round(buyQuantity, symbol.AmountPrecision);
            if (buyQuantity > sellQuantity && buyQuantity * nowPrice < sellQuantity * sellTradePrice)
            {
                return(buyQuantity);
            }

            var newBuyQuantity = buyQuantity;

            if (newBuyQuantity == sellQuantity)
            {
                if (symbol.AmountPrecision == 1)
                {
                    newBuyQuantity += (decimal)0.1;
                }
                if (symbol.AmountPrecision == 2)
                {
                    newBuyQuantity += (decimal)0.01;
                }
                if (symbol.AmountPrecision == 3)
                {
                    newBuyQuantity += (decimal)0.001;
                }
                if (symbol.AmountPrecision == 4)
                {
                    newBuyQuantity += (decimal)0.0001;
                }
            }
            if (newBuyQuantity > sellQuantity && newBuyQuantity * nowPrice <= sellQuantity * sellTradePrice)
            {
                return(newBuyQuantity);
            }
            throw new Exception("计算buyQuantity不合理");
        }
Beispiel #26
0
        public static decimal CalcTradeQuantity(CommonSymbol symbol, decimal quantity)
        {
            string symbolName    = symbol.BaseCurrency;
            string quoteCurrency = symbol.QuoteCurrency;
            var    leastBy       = (decimal)0;

            if (quoteCurrency == "usdt" && usdtLeastBuy.ContainsKey(symbolName))
            {
                leastBy = usdtLeastBuy[symbolName];
            }
            if (quoteCurrency == "btc" && btcLeastBuy.ContainsKey(symbolName))
            {
                leastBy = btcLeastBuy[symbolName];
            }
            if (quoteCurrency == "eth" && ethLeastBuy.ContainsKey(symbolName))
            {
                leastBy = ethLeastBuy[symbolName];
            }
            if (quoteCurrency == "ht" && htLeastBuy.ContainsKey(symbolName))
            {
                leastBy = htLeastBuy[symbolName];
            }
            if (leastBy <= 0)
            {
                // 如果没有设置, 则原值返回
                return(quantity);
            }
            var amountPrecisionValue = GetPrecisionValue(symbol.AmountPrecision);

            if (leastBy == amountPrecisionValue)
            {
                if (quantity >= leastBy * 12)
                {
                    return(quantity);
                }

                if (leastBy * 4 > quantity)
                {
                    Console.WriteLine($"最小购买数量不对啊{leastBy}, {symbol.BaseCurrency} {symbol.QuoteCurrency}");
                    throw new ApplicationException("----");
                }
                else
                {
                    return(leastBy * 12);
                }
            }
            else if (leastBy > amountPrecisionValue)
            {
                if (quantity > leastBy * (decimal)1.6)
                {
                    return(quantity);
                }
                else if (quantity * 4 >= leastBy)
                {
                    return(leastBy * (decimal)1.6);
                }
                else
                {
                    Console.WriteLine($"最小购买数量不对啊{leastBy}, {symbol.BaseCurrency} {symbol.QuoteCurrency}");
                    throw new ApplicationException("----");
                }
            }
            else
            {
                throw new ApplicationException("--222--");
            }
        }