Ejemplo n.º 1
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);
                }
            }
        }
Ejemplo n.º 2
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);
                }
            });
        }
Ejemplo n.º 3
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);
         }
     });
 }
Ejemplo n.º 4
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);
            }
        }
Ejemplo n.º 5
0
        private static void QueryBuyDetailAndUpdate(string userName, long orderId)
        {
            try
            {
                PlatformApi api = PlatformApi.GetInstance(userName);

                var orderDetail = api.QueryOrderDetail(orderId);
                if (orderDetail.Status == "ok" && orderDetail.Data.state == "filled")
                {
                    var orderMatchResult = api.QueryOrderMatchResult(orderId);
                    if (orderMatchResult == null || orderMatchResult.Data == null)
                    {
                        return;
                    }
                    decimal maxPrice = 0;
                    foreach (var item in orderMatchResult.Data)
                    {
                        if (maxPrice < item.price)
                        {
                            maxPrice = item.price;
                        }
                    }
                    if (orderMatchResult.Status == "ok" && maxPrice > 0)
                    {
                        new DogMoreBuyDao().UpdateDogMoreBuySuccess(orderId, orderDetail, orderMatchResult, maxPrice);
                    }
                }

                if (orderDetail.Status == "ok" && orderDetail.Data.state == StateConst.PartialCanceled)
                {
                    var     orderMatchResult = api.QueryOrderMatchResult(orderId);
                    decimal maxPrice         = 0;
                    decimal buyQuantity      = 0;
                    foreach (var item in orderMatchResult.Data)
                    {
                        if (maxPrice < item.price)
                        {
                            maxPrice = item.price;
                        }
                        buyQuantity += item.FilledAmount;
                    }
                    if (orderMatchResult.Status == "ok")
                    {
                        new DogMoreBuyDao().UpdateDogMoreBuySuccess(orderId, buyQuantity, orderDetail, orderMatchResult, maxPrice);
                    }
                }

                if (orderDetail.Status == "ok" && orderDetail.Data.state == StateConst.Canceled)
                {
                    // 完成
                    new DogMoreBuyDao().UpdateDogMoreBuyWhenCancel(orderId);
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.Message, ex);
                logger.Error($"QueryBuyDetailAndUpdate, orderId:{orderId}  查询数据出错");
            }
        }
Ejemplo n.º 6
0
        public async Task <object> List(string quoteCurrency)
        {
            try
            {
                var res = await new DogControlDao().ListDogControl(quoteCurrency);
                res = res.OrderBy(it => it.SymbolName).ToList();
                var nowPriceList = new DogNowPriceDao().ListDogNowPrice(quoteCurrency);
                Dictionary <string, decimal> closeDic = new Dictionary <string, decimal>();
                foreach (var item in nowPriceList)
                {
                    if (item.QuoteCurrency != quoteCurrency)
                    {
                        continue;
                    }
                    closeDic.Add(item.SymbolName, item.NowPrice);
                }

                //var outList = new List<string> { "mtl", "ncash", "phx", "sbtc", "adx", "mtl", "mtl", "mtl", "mtl", "mtl" };
                PlatformApi api     = PlatformApi.GetInstance("xx");
                var         tickers = api.GetTickers();

                var notInControl = new List <string>();
                foreach (var ticker in tickers)
                {
                    if (ticker.symbol.EndsWith(quoteCurrency))
                    {
                        var find = res.Find(it => ticker.symbol.StartsWith(it.SymbolName));
                        if (find == null)
                        {
                            notInControl.Add(ticker.symbol);
                        }
                    }
                }

                return(new
                {
                    list = res.Select(it => new
                    {
                        it.HistoryMin,
                        it.HistoryMax,
                        it.EmptyPrice,
                        it.MaxInputPrice,
                        it.QuoteCurrency,
                        it.SymbolName,
                        AvgPrice = decimal.Round(it.AvgPrice, 9).ToString() + (it.MaxInputPrice > it.AvgPrice ? " 大于加权平均 " : "") + " -- " + decimal.Round(it.Min8, 9).ToString() + (it.MaxInputPrice > it.Min8 ? " 大于8阶层" : ""),
                        it.WillDelist,
                    }).ToList(),
                    closeDic,
                    notInControl,
                    allItems = res.Select(it => it.SymbolName).ToList()
                });
            }
            catch (Exception ex)
            {
                logger.Error(ex.Message, ex);
                throw ex;
            }
        }
Ejemplo n.º 7
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,
                });
            }
        }
Ejemplo n.º 8
0
        private static void RunCoin(List <CommonSymbol> symbols)
        {
            Task.Run(() =>
            {
                while (true)
                {
                    var begin          = DateTime.Now;
                    CoinTrade.RunCount = 0;
                    try
                    {
                        var tickers = PlatformApi.GetInstance("xx").GetTickers();
                        for (var i = 0; i < symbols.Count; i++)
                        {
                            var symbol = symbols[i];
                            try
                            {
                                DateTime now = DateTime.Now;
                                var bl       = CoinTrade.Run(i, symbol, tickers);
                                var mis      = (DateTime.Now - now).TotalMilliseconds;
                                if (mis > 1000)
                                {
                                    Console.WriteLine("每轮------------------------>" + mis);
                                }
                                if (bl)
                                {
                                    Thread.Sleep(150);
                                }
                            }
                            catch (Exception ex)
                            {
                                logger.Error("RunCoin:  " + ex.Message, ex);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        logger.Error(ex.Message, ex);
                    }
                    var useTime = (DateTime.Now - begin).TotalSeconds;
                    logger.Error("一轮总共耗时:" + (DateTime.Now - begin).TotalSeconds + ", 执行次数:" + CoinTrade.RunCount);


                    Thread.Sleep(1000);

                    if (DateTime.Now.Hour == 0 || DateTime.Now.Hour == 4 || DateTime.Now.Hour == 8 ||
                        DateTime.Now.Hour == 12 || DateTime.Now.Hour == 16 || DateTime.Now.Hour == 20)
                    {
                        if (DateTime.Now.Minute < 25)
                        {
                            new DogOrderStatDao().AddStatRecord();
                        }
                    }
                }
            });
        }
Ejemplo n.º 9
0
        public static void RefreshHistoryMaxMinAsync(string symbolName, string quoteCurrency)
        {
            try
            {
                // 先计算最近500天的数据, 如果数据量少, 则计算4小时数据1000天
                PlatformApi api    = PlatformApi.GetInstance("xx");
                var         klines = api.GetHistoryKline(symbolName + quoteCurrency, "1day", 500);
                if (klines.Count < 180)
                {
                    klines = api.GetHistoryKline(symbolName + quoteCurrency, "4hour", 1000);
                }
                var min = decimal.MinValue;
                var max = decimal.MaxValue;

                min = klines.Where(it => it.Low > min).Min(it => it.Low);
                min = klines.Where(it => it.Low > min).Min(it => it.Low);
                min = klines.Where(it => it.Low > min).Min(it => it.Low);

                max = klines.Where(it => it.High < max).Max(it => it.High);
                max = klines.Where(it => it.High < max).Max(it => it.High);
                max = klines.Where(it => it.High < max).Max(it => it.High);

                // 判断max
                var maxNotSell = new DogMoreBuyDao().GetMaxPriceOfNotSellFinished(quoteCurrency, symbolName);
                if (maxNotSell > max)
                {
                    max = maxNotSell;
                }

                var avgPrice = (decimal)0;
                foreach (var item in klines)
                {
                    avgPrice += (item.Open + item.Close) / 2;
                }
                avgPrice = avgPrice / klines.Count;

                var dogControl = new DogControl()
                {
                    HistoryMax    = max,
                    HistoryMin    = min,
                    SymbolName    = symbolName,
                    QuoteCurrency = quoteCurrency,
                    AvgPrice      = avgPrice
                };

                new DogControlDao().UpdateDogControlMaxAndMin(dogControl);
            }
            catch (Exception ex)
            {
                logger.Error(ex.Message, ex);
                throw ex;
            }
        }
Ejemplo n.º 10
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 });
        }
Ejemplo n.º 11
0
        public static void GetAccount()
        {
            var         userName = "******";
            PlatformApi api      = PlatformApi.GetInstance(userName);

            var accounts = api.GetAllAccount();

            Console.WriteLine(JsonConvert.SerializeObject(accounts));

            var account = api.GetAccountBalance("529880");

            Console.WriteLine(JsonConvert.SerializeObject(account));
        }
Ejemplo n.º 12
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
                });
            }
        }
Ejemplo n.º 13
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);
        }
Ejemplo n.º 14
0
        public static void InitOneKine(CommonSymbols symbol)
        {
            try
            {
                PlatformApi api    = PlatformApi.GetInstance("xx"); // 下面api和角色无关. 随便指定一个xx
                var         period = "1min";
                var         klines = api.GetHistoryKline(symbol.BaseCurrency + symbol.QuoteCurrency, period);
                var         key    = HistoryKlinePools.GetKey(symbol, period);
                HistoryKlinePools.Init(key, klines);

                // 记录到数据库
                Record(symbol.BaseCurrency, klines[0]);
            }
            catch (Exception ex)
            {
                logger.Error("InitOneKine --> " + ex.Message, ex);
            }
        }
Ejemplo n.º 15
0
        public static void RunAlert()
        {
            var symbols = CoinUtils.GetAllCommonSymbols("usdt");

            Task.Run(() =>
            {
                while (true)
                {
                    try
                    {
                        foreach (var symbol in symbols)
                        {
                            PlatformApi api = PlatformApi.GetInstance("xx");
                            var period      = "1min";
                            var klines      = api.GetHistoryKline(symbol.BaseCurrency + symbol.QuoteCurrency, period);

                            var nowPrice = klines[0].Close;
                            // 5分钟内有5%, 或者 15分钟内有10%
                            foreach (var item in klines)
                            {
                                if (Utils.GetDateById(item.Id) > DateTime.Now.AddMinutes(-5) && (
                                        item.Close / nowPrice > (decimal)1.05 || nowPrice / item.Close > (decimal)1.05))
                                {
                                    Console.WriteLine($"{symbol.BaseCurrency}, now:{nowPrice} ->{ item.Close} ");
                                    OpenUrlUtils.Open();
                                }

                                if (Utils.GetDateById(item.Id) > DateTime.Now.AddMinutes(-15) && (
                                        item.Close / nowPrice > (decimal)1.10 || nowPrice / item.Close > (decimal)1.10))
                                {
                                    Console.WriteLine($"{symbol.BaseCurrency}, now:{nowPrice} ->{ item.Close} ");
                                    OpenUrlUtils.Open();
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                    }
                }
            });
        }
Ejemplo n.º 16
0
        private static void QuerySellDetailAndUpdate(string userName, long orderId)
        {
            PlatformApi api = PlatformApi.GetInstance(userName);

            var orderDetail = api.QueryOrderDetail(orderId);

            if (orderDetail.Status == "ok" && orderDetail.Data.state == "filled")
            {
                var     orderMatchResult = api.QueryOrderMatchResult(orderId);
                decimal minPrice         = 99999999;
                foreach (var item in orderMatchResult.Data)
                {
                    if (minPrice > item.price)
                    {
                        minPrice = item.price;
                    }
                }
                // 完成
                new PigMoreDao().UpdateTradeRecordSellSuccess(orderId, orderDetail, orderMatchResult, minPrice);
            }
        }
Ejemplo n.º 17
0
        public void OrderPlaceTest()
        {
            PlatformApi api           = PlatformApi.GetInstance("xx");
            var         accounts      = api.GetAllAccount();
            var         spotAccountId = accounts.FirstOrDefault(a => a.Type == "spot" && a.State == "working")?.Id;

            if (spotAccountId <= 0)
            {
                throw new ArgumentException("spot account unavailable");
            }
            OrderPlaceRequest req = new OrderPlaceRequest();

            req.account_id = spotAccountId.ToString();
            req.amount     = "0.1";
            req.price      = "800";
            req.source     = "api";
            req.symbol     = "ethusdt";
            req.type       = "buy-limit";
            var result = api.OrderPlace(req);
            //Assert.AreEqual(result.Status, "ok");
        }
Ejemplo n.º 18
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);
        }
Ejemplo n.º 19
0
        private static void QueryBuyDetailAndUpdate(string userName, long orderId)
        {
            PlatformApi api = PlatformApi.GetInstance(userName);

            var orderDetail = api.QueryOrderDetail(orderId);

            if (orderDetail.Status == "ok" && orderDetail.Data.state == "filled")
            {
                var     matchResult = api.QueryOrderMatchResult(orderId);
                decimal maxPrice    = 0;
                foreach (var item in matchResult.Data)
                {
                    if (maxPrice < item.price)
                    {
                        maxPrice = item.price;
                    }
                }
                if (matchResult.Status == "ok")
                {
                    new PigMoreDao().UpdatePigMoreBuySuccess(orderId, orderDetail, matchResult, maxPrice);
                }
            }
        }
Ejemplo n.º 20
0
        private static void QuerySellDetailAndUpdate(string userName, long orderId)
        {
            try
            {
                PlatformApi api = PlatformApi.GetInstance(userName);

                var orderDetail = api.QueryOrderDetail(orderId);
                if (orderDetail.Status == "ok" && orderDetail.Data.state == "filled")
                {
                    var     orderMatchResult = api.QueryOrderMatchResult(orderId);
                    decimal minPrice         = 25000;
                    foreach (var item in orderMatchResult.Data)
                    {
                        if (minPrice > item.price)
                        {
                            minPrice = item.price;
                        }
                    }
                    if (orderMatchResult.Status == "ok" && minPrice > 0)
                    {
                        // 完成
                        new DogMoreSellDao().UpdateDogMoreSellWhenSuccess(orderId, orderDetail, orderMatchResult, minPrice);
                    }
                }

                if (orderDetail.Status == "ok" && orderDetail.Data.state == StateConst.Canceled)
                {
                    // 完成
                    new DogMoreSellDao().UpdateDogMoreSellWhenCancel(orderId);
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.Message, ex);
                logger.Error("QuerySellDetailAndUpdate 查询结果时候出错");
            }
        }
Ejemplo n.º 21
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);
        }
Ejemplo n.º 22
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;
            }
        }
Ejemplo n.º 23
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);
            }
        }
Ejemplo n.º 24
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;
            }
        }
Ejemplo n.º 25
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;
            }
        }
Ejemplo n.º 26
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)}");
                    }
                }
            }
        }
Ejemplo n.º 27
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)}");
            }
        }
Ejemplo n.º 28
0
 public void GetAllAccountTest()
 {
     PlatformApi api    = PlatformApi.GetInstance("xx");
     var         result = api.GetAllAccount();
 }
Ejemplo n.º 29
0
        private async Task <Dictionary <string, decimal> > GetUsdtPrice()
        {
            // 获取btc价格
            var         btcPrice = new decimal(1000);
            PlatformApi api      = PlatformApi.GetInstance("xx"); // 下面api和角色无关. 随便指定一个xx
            var         period   = "1min";
            var         count    = 3;
            var         klines   = api.GetHistoryKline("btcusdt", period, count);

            btcPrice = klines[0].Close;

            Dictionary <string, decimal> closeDic = new Dictionary <string, decimal>();

            closeDic.Add("usdt", (decimal)1);

            {
                var nowPriceList = new DogNowPriceDao().ListDogNowPrice("usdt");
                foreach (var item in nowPriceList)
                {
                    if (item.QuoteCurrency != "usdt")
                    {
                        continue;
                    }

                    closeDic.Add(item.SymbolName, item.NowPrice);
                }
            }

            {
                var nowPriceList = new DogNowPriceDao().ListDogNowPrice("btc");
                foreach (var item in nowPriceList)
                {
                    if (item.QuoteCurrency != "btc")
                    {
                        continue;
                    }

                    if (closeDic.ContainsKey(item.SymbolName))
                    {
                        continue;
                    }

                    closeDic.Add(item.SymbolName, item.NowPrice * btcPrice);
                }
            }


            {
                var nowPriceList = new DogNowPriceDao().ListDogNowPrice("eth");
                foreach (var item in nowPriceList)
                {
                    if (item.QuoteCurrency != "eth")
                    {
                        continue;
                    }

                    if (closeDic.ContainsKey(item.SymbolName))
                    {
                        continue;
                    }

                    closeDic.Add(item.SymbolName, item.NowPrice * closeDic["eth"]);
                }
            }


            {
                var nowPriceList = new DogNowPriceDao().ListDogNowPrice("ht");
                foreach (var item in nowPriceList)
                {
                    if (item.QuoteCurrency != "ht")
                    {
                        continue;
                    }

                    if (closeDic.ContainsKey(item.SymbolName))
                    {
                        continue;
                    }

                    closeDic.Add(item.SymbolName, item.NowPrice * closeDic["ht"]);
                }
            }

            return(closeDic);
        }
Ejemplo n.º 30
0
        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;
            }
        }