Example #1
0
        private decimal GetSpanPrice(decimal format = 0.1m)
        {
            if (info.SpanPrice <= 0.1m)
            {
                return(info.SpanPrice);
            }
            string kr1 = "M1";
            string kr2 = "M15";

            var kline1 = robotMarket.GetKlines(Symbol, kr1) ?? new List <Kline>();
            var kline2 = robotMarket.GetKlines(Symbol, kr2) ?? new List <Kline>();

            decimal width1  = GetKlinePriceWidth(kline1, info.OrderQty, format, 5, 1.0m);
            decimal width15 = GetKlinePriceWidth(kline2, info.OrderQty, format, 5, 0.5m);

            decimal width = Math.Max(width1, width15);

            if (Math.Abs(width - info.SpanPrice) >= info.SpanPrice / 4)
            {
                if (info.Symbol.ToLower().Contains("btcusdt") && width <= 1m)
                {
                    width = 1;
                }
                info.SpanPrice = width;
            }
            Log4NetUtility.Debug($"kline{kr1} width : {width1}  kline{kr2} width : {width15} SpanPrice:{info.SpanPrice}->{width}");
            return(info.SpanPrice);
        }
Example #2
0
        private void Timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            string reportStr = "";

            try
            {
                var account = robotTrade.CurrentAccount;
                var ticker  = robotMarket.GetTicker(info.Symbol);
                if (DateTime.Now.Minute == 0)
                {
                    //整点日志
                    reportStr = GetReport(info, account, ticker, true);
                }
                else
                {
                    //分钟日志
                    reportStr = GetReport(info, account, ticker, false);
                }

                Log4NetUtility.Info("ReportDetail ", reportStr);
            }
            catch (Exception ex)
            {
                Log4NetUtility.Error("ReportTimer", Utils.Exception2String(ex));
            }
        }
Example #3
0
        public Ticker GetTicker(string platform, string symbol)
        {
            try
            {
                switch (platform)
                {
                //case "OK":
                //    return GetTicker_OK(symbol);
                //case "BA":
                //    return GetDepth_BA(symbol, size);
                case "HB":
                //return GetTicker_OK(symbol);
                case "FC":
                    return(GetTicker_FC(symbol));

                default:
                    return(null);
                }
            }
            catch (Exception e)
            {
                Log4NetUtility.Error("GetTicker", Utils.Exception2String(e));
                DbHelper.CreateInstance().AddError("GetTicker", e);
                return(null);
            }
        }
Example #4
0
        public int ClearCurrentOrders(string symbol)
        {
            try
            {
                switch (platform)
                {
                case "OK":
                //return GetTicker_OK(symbol);
                //case "BA":
                //    return GetDepth_BA(symbol, size);
                case "HB":
                //return GetTicker_OK(symbol);
                case "FC":
                    return(ClearCurrentOrders_FC(symbol));

                default:
                    return(-1);
                }
            }
            catch (Exception e)
            {
                Log4NetUtility.Error("ClearOrders", Utils.Exception2String(e));
                DbHelper.CreateInstance().AddError("ClearOrders", e);
                return(-1);
            }
        }
Example #5
0
        public List <Kline> GetKline(string platform, string symbol, string resolution, int limit = 60)
        {
            try
            {
                switch (platform)
                {
                //case "OK":
                //    return GetTicker_OK(symbol);
                //case "BA":
                //    return GetDepth_BA(symbol, size);
                case "HB":
                //return GetTicker_OK(symbol);
                case "FC":
                    return(GetKline_FC(symbol, resolution, limit));

                default:
                    return(null);
                }
            }
            catch (Exception e)
            {
                Log4NetUtility.Error("GetKline", Utils.Exception2String(e));
                DbHelper.CreateInstance().AddError("GetKline", e);
                return(null);
            }
        }
Example #6
0
        public bool Connnet()
        {
            try
            {
                websocket = new WebSocketSharp.WebSocket(WEBSOCKET_API);

                websocket.OnError += (sender, e) =>
                {
                    Console.WriteLine("Error:" + e.Exception.Message.ToString());
                    Log4NetUtility.Debug("OnError", e.Exception.Message);
                };
                websocket.OnOpen    += OnOpened;
                websocket.OnClose   += Websocket_Closed;;
                websocket.OnMessage += ReceviedMsg;
                websocket.ConnectAsync();
                while (!websocket.IsAlive)
                {
                    Console.WriteLine("Waiting WebSocket connnet......");
                    Thread.Sleep(1000);
                }
                heartBeatTimer.Elapsed += new System.Timers.ElapsedEventHandler(heatBeat);
                //heartBeatTimer.Start();
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception:" + ex.Message);
                Log4NetUtility.Error("WebSocketApi_OK", Utils.Exception2String(ex));
            }
            return(true);
        }
Example #7
0
        //private void SetTradeQty(bool firststart = false)
        //{
        //    if (firststart && config.TradeQty != null && config.TradeQty != 0)
        //    {
        //        info.TradeQty = (decimal)config.TradeQty;
        //    }
        //    else
        //    {
        //        var info = coinConfigs.FirstOrDefault(a => a.Platform == Platform && a.Symbol == Symbol);
        //        var ticker = GetTicker();
        //        var account = GetAccount();

        //        decimal price_now = ticker.last;
        //        decimal net = account.GetNet(this.info.Symbol, price_now);
        //        int packetNum = (this.info.OrderQty + 3) * 2;
        //        decimal newTradeQTY = info.FormatAmount2D(net / price_now / packetNum);
        //        this.info.TradeQty = newTradeQTY;
        //    }
        //}
        private void resetAccount(string side, decimal resetAmt)
        {
            Stopwatch stopwatch_market = new Stopwatch();

            stopwatch_market.Start();
            bool result_market = false;

            for (int i = 0; i < 3 && !result_market; i++)
            {
                var ticker = GetTicker();

                decimal price = side == "buy" ? ticker.sell : ticker.buy;
                //Trade trade = robotTrade.Trade(Symbol, side, price, resetAmt);
                Trade trade = robotTrade.MarketTrade(Symbol, side, price, resetAmt);
                result_market = trade.result;
                if (result_market)
                {
                    stopwatch_market.Stop();
                    //UpdateMarketFee(trade.order_id);

                    Log4NetUtility.Info("初始资源", $"《市价{side}》,当前Price:{ticker.last.ToString("#0.00")},Deal数量:{resetAmt.ToString("#0.0000")},市价用时:{stopwatch_market.ElapsedMilliseconds}");
                    Thread.Sleep(3000);
                    break;
                }
                else
                {
                    Thread.Sleep(1000);
                    if (trade.error_code.Contains("1002"))
                    {
                        Thread.Sleep(2000 * i);
                        //i -= 1;
                    }
                }
            }
        }
Example #8
0
        public Trade PostMarketTrade_FC(string symbol, string side, decimal price, decimal amount)
        {
            var coinInfo = CoinConfigs.FirstOrDefault(a => a.Symbol == symbol);

            if (coinInfo == null || coinInfo.AmountLimit == 0 || coinInfo.PriceLimit == 0)
            {
                throw (new Exception());
            }
            decimal rate = 1;

            if (side == "buy")
            {
                rate = 1.08m;
            }
            else
            {
                rate = 0.92m;
            }
            string priceStr  = coinInfo.FormatPrice2S(price * rate);
            string amountStr = coinInfo.FormatAmount2S(amount);

            Log4NetUtility.Debug("Trade", $"MarketTrade. price:{price} priceStr:{priceStr} amount:{amount} amountStr:{amountStr}");
            string JsonStr = restApi_FC.trade(symbol, side, "limit", priceStr, amountStr);

            Log4NetUtility.Debug("Trade", JsonStr);
            var data = ModelHelper <API.Rest.FCoin.trade> .Json2Model(JsonStr);

            return(new Trade(data));
        }
Example #9
0
        public string userinfo()
        {
            string result = "";

            try
            {
                var method = "GET";
                //string timeSpamt = GetDateTime();
                //var sign = CreateSign(method, USERINFO_URL, secret_key, timeSpamt, null);
                //WebHeaderCollection header = new WebHeaderCollection();
                //header.Add("FC-ACCESS-KEY", api_key);
                //header.Add("FC-ACCESS-SIGNATURE", sign);
                //header.Add("FC-ACCESS-TIMESTAMP", timeSpamt);
                Dictionary <string, object> paras = new Dictionary <string, object>();
                paras.Add("AccessKey", api_key);
                paras.Add("SignatureMethod", "HmacSHA256");
                paras.Add("SignatureVersion", "V1.0");
                paras.Add("Timestamp", DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss"));
                paras.Add("Signature", null);
                int statusCode;
                result = RequestDataSync($"{url_prex}{USERINFO_URL}", method, paras, null, out statusCode);
            }
            catch (Exception e)
            {
                Log4NetUtility.Error("userinfo", Utils.Exception2String(e));
                Log4NetUtility.Error("userinfo", result);
                DbHelper.CreateInstance().AddError("userinfo", e);
            }
            return(result);
        }
Example #10
0
        public string order_info(string order_id)
        {
            string result = "";

            try
            {
                var    method    = "GET";
                string timeSpamt = GetDateTime();
                // 构造参数签名
                //Dictionary<string, object> paras = new Dictionary<string, object>();
                //if (!string.IsNullOrEmpty(order_id))
                //{
                //    paras.Add("order_id", order_id);
                //}
                var sign = CreateSign(method, ORDERS_INFO_URL + "/" + order_id, secret_key, timeSpamt, null);
                WebHeaderCollection header = new WebHeaderCollection();
                header.Add("FC-ACCESS-KEY", api_key);
                header.Add("FC-ACCESS-SIGNATURE", sign);
                header.Add("FC-ACCESS-TIMESTAMP", timeSpamt);

                int statusCode;
                result = RequestDataSync($"{url_prex}{ORDERS_INFO_URL}/{order_id}", method, null, header, out statusCode);
                return(result);
            }
            catch (Exception e)
            {
                Log4NetUtility.Error("order_info", result);
                throw e;
            }
        }
Example #11
0
        private void CancelOrder(Order order)
        {
            CancelOrder cancel = robotTrade.CancelOrder(Symbol, order.order_id);

            if (cancel.result)
            {
                robotSession.RemoveSessionOrder(order);
                //DbHelper.DBSaveChange(doubleorder, "UpDate");
                Log4NetUtility.Info("RobotHFT", "Canceled Order Success. id:" + Utils.ShortID(order.order_id) + " Price:" + order.price);
            }
            else
            {
                string errmsg = cancel.error_code + "  " + cancel.msg;
                if (cancel.error_code.Contains("3008"))
                {
                    robotSession.RemoveSessionOrder(order);
                    //sessionOrders.Remove(doubleorder);
                    ////DbHelper.CreateInstance().RemoveOrder(doubleorder);
                    errmsg = "已清除脏数据Order。id:" + Utils.ShortID(order.order_id) + " Price:" + order.price;
                }
                else
                {
                    //errmsg = "撤销重复Order失败。id:" + Utils.ShortID(doubleorder.order_id) + " msg:" + cancel.error_code + cancel.msg;
                }
                Log4NetUtility.Info("CancelOrder", errmsg);
                //DbHelper.CreateInstance().AddErrInfo("缓存单验证", errmsg);
            }
        }
Example #12
0
 public static List <CoinConfig> Load()
 {
     try
     {
         string conFilePath = AppDomain.CurrentDomain.BaseDirectory + "CoinConfigs.json";
         if (!File.Exists(conFilePath))
         {
             throw (new Exception("CoinConfigs配置文件不存在"));
         }
         StreamReader sr      = new StreamReader(conFilePath, Encoding.Default);
         string       jsonStr = sr.ReadToEnd();
         var          list    = JsonConvert.DeserializeObject <List <CoinConfig> >(jsonStr);
         if (list != null && list.Count > 0)
         {
             Log4NetUtility.Info("加载系统配置", "已成功加载系统配置CoinConfigs");
             return(list);
         }
         else
         {
             throw (new Exception("CoinConfigs配置文件异常"));
         }
     }
     catch (Exception e)
     {
         Log4NetUtility.Error("加载系统配置CoinConfigs", "加载配置异常:" + Utils.Exception2String(e));
         throw (e);
     }
 }
Example #13
0
 private void CurrentLostOrders(List <Order> lostOrders)
 {
     foreach (var lost in lostOrders)
     {
         robotSession.AddUpdateSessionOrder(lost);
         Log4NetUtility.Debug($"CurrentEvent,Add lostOrders Price:{lost.price.ToString("#0.00")} Id:{Utils.ShortID(lost.order_id)}");
     }
 }
Example #14
0
        public string trade(string symbol, string side, string type, string price, string amount)
        {
            string result = "";

            try
            {
                var    method    = "POST";
                string timeSpamt = GetDateTime();
                // 构造参数签名
                Dictionary <string, object> paras = new Dictionary <string, object>();
                if (!string.IsNullOrEmpty(amount))
                {
                    paras.Add("amount", amount);
                }
                if (!string.IsNullOrEmpty(price))
                {
                    paras.Add("price", price);
                }
                if (!string.IsNullOrEmpty(side))
                {
                    paras.Add("side", side);
                }
                if (!string.IsNullOrEmpty(symbol))
                {
                    paras.Add("symbol", symbol);
                }
                if (!string.IsNullOrEmpty(type))
                {
                    paras.Add("type", type);
                }

                if (type == "market")
                {
                    paras.Remove("price");
                }

                var sign = CreateSign(method, TRADE_URL, secret_key, timeSpamt, paras);
                WebHeaderCollection header = new WebHeaderCollection();
                header.Add("FC-ACCESS-KEY", api_key);
                header.Add("FC-ACCESS-SIGNATURE", sign);
                header.Add("FC-ACCESS-TIMESTAMP", timeSpamt);

                int statusCode;
                result = RequestDataSync($"{url_prex}{TRADE_URL}", method, paras, header, out statusCode);
                return(result);
            }
            catch (Exception e)
            {
                Log4NetUtility.Error("userinfo", Utils.Exception2String(e));
                Log4NetUtility.Error("userinfo", result);
                DbHelper.CreateInstance().AddError("userinfo", e);
            }

            return(result);
        }
Example #15
0
 private void Websocket_OnError(object sender, ErrorEventArgs e)
 {
     Console.WriteLine("Error:" + e.Exception.Message.ToString());
     Console.WriteLine("websocket.IsAlive:" + websocket.IsAlive);
     Log4NetUtility.Debug("OnError", "websocket.IsAlive:" + websocket.IsAlive);
     Log4NetUtility.Debug("OnError", e.Exception.Message);
     if (!websocket.IsAlive)
     {
         websocket.Close();
     }
 }
Example #16
0
        /// <summary>
        /// 全仓挂单
        /// </summary>
        private void HangOrders()
        {
            try
            {
                #region 新缓存列表 newSessionOrders
                List <Order> newSessionOrders = new List <Order>();
                decimal      newFloatPrice    = GetStandardPrice(GetTicker().last);
                info.floatPrice    = newFloatPrice;
                info.buyOrderCount = info.sellOrderCount = info.OrderQty;
                //info.ShockCount_tmp = info.UpCount_tmp = info.DownCount_tmp = 0;
                for (int i = 1; i <= info.buyOrderCount; i++)
                {
                    decimal orderprice = newFloatPrice - i * info.SpanPrice;
                    Order   order      = new Order()
                    {
                        price = orderprice, amount = info.TradeQty, type = "buy"
                    };
                    newSessionOrders.Add(order);
                }
                for (int i = 1; i <= info.sellOrderCount; i++)
                {
                    decimal orderprice = newFloatPrice + i * info.SpanPrice;
                    Order   order      = new Order()
                    {
                        price = orderprice, amount = info.TradeQty, type = "sell"
                    };
                    newSessionOrders.Add(order);
                }

                #endregion
                #region 挂单、缓存
                Stopwatch stopwatch = new Stopwatch();
                stopwatch.Start();
                robotSession.ClearSessionAllOrders();
                foreach (var addOrder in newSessionOrders)
                {
                    TradeOrder(addOrder);
                    Thread.Sleep(250);
                }
                //Parallel.ForEach(newSessionOrders, addOrder =>
                //{
                //    TradeOrder(addOrder);
                //});
                stopwatch.Stop();
                Log4NetUtility.Info("HangOrders", robotSession.LogSring());
                Log4NetUtility.Info("HangOrders", $"Order中间价:{newFloatPrice}。交易总用时(毫秒):{stopwatch.ElapsedMilliseconds}");
                #endregion
            }
            catch (Exception e)
            {
                Log4NetUtility.Error("HangOrders", Utils.Exception2String(e));
                DbHelper.CreateInstance().AddError("HangOrders", e);
            }
        }
Example #17
0
        public void CheckLostOrders(List <Order> currentOrder)
        {
            var lostOrders = currentOrder.Where(a => !SessionOrders.Exists(b => b.order_id == a.order_id)).ToList();

            if (lostOrders.Count > 0)
            {
                foreach (var lost in lostOrders)
                {
                    AddUpdateSessionOrder(lost);
                    Log4NetUtility.Debug($"CurrentEvent,Add lostOrders Price:{lost.price.ToString("#0.00")} Id:{Utils.ShortID(lost.order_id)}");
                }
            }
        }
Example #18
0
        private Trade TradeOrder(Order order)
        {
            if (order == null)
            {
                return(null);
            }
            Trade trade = robotTrade.Trade(Symbol, order.type, order.price, order.amount);

            for (int i = 0; i < 3; i++)
            {
                if (trade.result && !string.IsNullOrEmpty(trade.order_id))
                {
                    order.order_id    = trade.order_id;
                    order.create_date = Utils.GetUtcTimeDec();
                    robotSession.AddUpdateSessionOrder(order);
                    Log4NetUtility.Debug($"New 《{order.type}》 Price:{order.price.ToString("#0.0000")} id:{Utils.ShortID(order.order_id)}");

                    break;
                }
                else
                {
                    string type = order.type == "buy" ? "-S" : "+B";
                    Log4NetUtility.Info("RobotHFT", $"《{type}》委托失败,P:《{order.price.ToString("#0.00")}》A:《{order.amount.ToString("#0.0000")}》,第{i + 1}次返回:{trade.error_code} {trade.msg}");
                    Thread.Sleep(1000);
                    if (trade.error_code.Contains("1002"))
                    {
                        Thread.Sleep(2000 * i);
                        //i -= 1;
                    }
                    if (trade.error_code.Contains("1016"))
                    {
                        var     side   = order.type == "buy" ? "sell" : "buy";
                        var     ticker = robotMarket.GetTicker(Symbol);
                        decimal price  = side == "buy" ? ticker.sell : ticker.buy;

                        Trade tradeM = robotTrade.MarketTrade(Symbol, side, price, order.amount);
                        if (tradeM.result)
                        {
                            Log4NetUtility.Info("RobotHFT", $"《{side}》市价调整,P:《{price.ToString("#0.00")}》A:《{order.amount.ToString("#0.0000")}》 ");
                        }
                        else
                        {
                            Log4NetUtility.Info("RobotHFT", $"《{side}》市价失败,P:《{price.ToString("#0.00")}》A:《{order.amount.ToString("#0.0000")}》 {tradeM.error_code} {tradeM.msg}");
                        }
                        Thread.Sleep(2000 * i);
                    }
                }
            }
            return(trade);
        }
Example #19
0
        /// <summary>
        /// 批量获取用户订单
        /// </summary>
        /// <param name="type">查询类型 0:未成交,未成交 1:完全成交,已撤销</param>
        /// <param name="symbol">btc_usd: 比特币 ltc_usd: 莱特币</param>
        /// <param name="order_id">订单ID(多个订单ID中间以","分隔,一次最多允许查询50个订单)</param>
        /// limit=20&states=submitted,partial_filled&symbol=ethusdt
        /// <returns></returns>
        public string orders_info(string limit, string states, string symbol, string after, string before)
        {
            string result = "";

            try
            {
                var    method    = "GET";
                string timeSpamt = GetDateTime();
                // 构造参数签名
                Dictionary <string, object> paras = new Dictionary <string, object>();
                if (!string.IsNullOrEmpty(after))
                {
                    paras.Add("after", after);
                }
                if (!string.IsNullOrEmpty(before))
                {
                    paras.Add("before", before);
                }

                if (!string.IsNullOrEmpty(limit))
                {
                    paras.Add("limit", limit);
                }
                if (!string.IsNullOrEmpty(states))
                {
                    paras.Add("states", states);
                }
                if (!string.IsNullOrEmpty(symbol))
                {
                    paras.Add("symbol", symbol);
                }
                var sign = CreateSign(method, ORDERS_INFO_URL, secret_key, timeSpamt, paras);
                //var sign = CreateSign(method, "/v2/orders?limit=20&states=submitted&symbol=ethusdt", secret_key, timeSpamt, null);
                WebHeaderCollection header = new WebHeaderCollection();
                header.Add("FC-ACCESS-KEY", api_key);
                header.Add("FC-ACCESS-SIGNATURE", sign);
                header.Add("FC-ACCESS-TIMESTAMP", timeSpamt);

                int statusCode;
                result = RequestDataSync($"{url_prex}{ORDERS_INFO_URL}?{ConvertQueryString(paras, true)}", method, null, header, out statusCode);
                //result = RequestDataSync("https://api.fcoin.com/v2/orders?limit=20&states=submitted&symbol=ethusdt", method, null, header, out statusCode);
                return(result);
            }
            catch (Exception e)
            {
                Log4NetUtility.Error("orders_info", result);

                throw e;
            }
        }
Example #20
0
 public static string Model2Json(T model)
 {
     try
     {
         return(JsonConvert.SerializeObject(model));
     }
     catch (Exception e)
     {
         Log4NetUtility.Error("ModelHelper", Utils.Exception2String(e));
         //Log4NetUtility.Error("ModelHelper", str);
         DbHelper.CreateInstance().AddError("ModelHelper", e);
         return("");
     }
 }
Example #21
0
        /// <summary>
        /// 成交挂单
        /// </summary>
        /// <param name="filledOrder"></param>
        /// <param name="newOrder"></param>
        private void CurrentOrderFilled(Order filledOrder, Order newOrder)
        {
            var trade = TradeOrder(newOrder);

            if (trade.result && !string.IsNullOrEmpty(trade.order_id))
            {
                #region 反向挂单成功,处理缓存
                newOrder.order_id    = trade.order_id;
                newOrder.create_date = Utils.GetUtcTimeDec();
                robotSession.AddUpdateSessionOrder(newOrder);
                filledOrder.status = "2";
                robotSession.RemoveSessionOrder(filledOrder);
                #endregion
                #region 统计震荡
                if (filledOrder.type == "buy")//买成交,行情下降
                {
                    info.dealDCount += 1;
                    //info.DownCount_tmp += 1;
                    info.floatPrice -= info.SpanPrice;
                }
                else//卖成交,行情上升
                {
                    info.dealUCount += 1;
                    //info.UpCount_tmp += 1;
                    info.floatPrice += info.SpanPrice;
                }
                long shockCount = Math.Min(info.dealDCount, info.dealUCount);
                if (info.dealCount != shockCount)
                {
                    //string timeStr = DateTime.Now.ToString("yyyyMMddHHmmss");
                    info.ShockTimes.Add(Utils.GetUtcTimeDec());
                    info.dealCount = shockCount;
                }
                //int shockCount_tmp = Math.Min(info.DownCount_tmp, info.UpCount_tmp);

                //if (info.ShockCount_tmp != shockCount_tmp)
                //{
                //    info.ShockCount_tmp += 1;
                //    //info.EarnAmt = info.EarnAmt + info.SpanPrice * info.TradeQty;
                //}
                #endregion
                #region log
                int    buynum  = robotSession.CountOrder(true);
                int    sellnum = robotSession.CountOrder(false);
                string type    = filledOrder.type == "sell" ? "+B" : "-S";
                Log4NetUtility.Debug($"OrderFilled {type} [{newOrder.price.ToString("#0.00")}] ID: {Utils.ShortID(trade.order_id)} S:[{sellnum}] B:[{buynum}] ");
                #endregion
            }
        }
Example #22
0
 public void AddDepth(depth depth)
 {
     try
     {
         using (var db = new MarkeDBEntities())
         {
             db.depth.Add(depth);
             db.SaveChanges();
         }
     }
     catch (Exception e)
     {
         Log4NetUtility.Error("AddDepth", e.Message);
     }
 }
Example #23
0
 private void AddOrUpdateOrders2DB(List <Order> orders)
 {
     try
     {
         List <order> list = new List <order>();
         foreach (var order in orders)
         {
             AddOrUpdateOrder2DB(order);
         }
     }
     catch (Exception e)
     {
         Log4NetUtility.Error("AddOrUpdateOrders2DB", Utils.Exception2String(e));
         DbHelper.CreateInstance().AddError("AddOrUpdateOrders2DB", e);
     }
 }
Example #24
0
 private void CurrentDirtyOrders(List <Order> dirtyOrders)
 {
     foreach (var dirtyOrder in dirtyOrders)
     {
         var order = robotTrade.GetOrders(Symbol, dirtyOrder.order_id);
         if (order.result && order.orders.Count != 0)
         {
             Order o = order.orders.FirstOrDefault();
             if (o.status == "filled")
             {
                 robotSession.RemoveSessionOrder(dirtyOrder);
                 Log4NetUtility.Debug($"CurrentEvent,Remove dirtyOrders {dirtyOrder.type} Price:{dirtyOrder.price.ToString("#0.00")} Id:{Utils.ShortID(dirtyOrder.order_id)} status:{o.status}");
             }
         }
     }
 }
Example #25
0
        private decimal GetKlinePriceWidth(List <Kline> klines, int orderQty, decimal format, int count = 5, decimal rTimes = 1)
        {
            var     list = klines.OrderBy(a => a.id).Skip(klines.Count - count).ToList();
            decimal max  = list.Max(a => a.high);
            decimal min  = list.Min(a => a.low);

            var priceWidth = max - min;

            Log4NetUtility.Debug($"max : {max} min : {min} width: {priceWidth}");
            var width = priceWidth / orderQty * rTimes;
            int f     = (int)(1 / format);

            f     = f < 1 ? 1 : f;
            width = Math.Round(width * f) / f;
            return(width < format ? format : width);
        }
Example #26
0
        public Orders GetOrders_FC(string order_id)
        {
            try
            {
                string JsonStr = restApi_FC.order_info(order_id);
                var    data    = ModelHelper <API.Rest.FCoin.orderInfo> .Json2Model(JsonStr);

                Orders order = new Orders(data);
                return(order);
            }
            catch (Exception e)
            {
                Log4NetUtility.Error("GetOrderInfo_FC", Utils.Exception2String(e));
                return(new Orders());
            }
        }
Example #27
0
 private void DoPlan(long dotime)
 {
     #region ObjectLock
     if (planDoTime == -1)
     {
         lock (planObjectLock)
         {
             if (planDoTime == -1)
             {
                 planDoTime = dotime;
             }
         }
     }
     #endregion
     if (planDoTime == dotime)
     {
         try
         {
             GetData();
             // 当前订单不在缓存中
             robotSession.CheckLostOrders(currentOrder);
             //遍历缓存订单对比当前订单,处理成交订单
             if (filledOrders.Count != 0)
             {
                 UpdateFilledSessionOrders();
                 robotSession.FilledSessionOrders(FilledSessionOrders, currentOrder);
             }
             if (CheckLittleTrade(info.ResetTimes, info.ShockTimes))
             {
                 CurrentEvent?.Invoke(null, new CurrentEventArgs(CurrentEventType.LittleTrade, null, null));
             }
             LimitFilledSessionOrders();
         }
         #region catch finally
         catch (Exception e)
         {
             ////DbHelper.CreateInstance().AddErrInfo("DoPlan", e);
             Log4NetUtility.Error("DoPlan", Utils.Exception2String(e));
             DbHelper.CreateInstance().AddError("DoPlan", e);
         }
         finally
         {
             planDoTime = -1;
         }
         #endregion
     }
 }
Example #28
0
        public string candles(string symbol, string resolution, int limit)
        {
            string result = "";

            try
            {
                HttpUtilManager httpUtil = HttpUtilManager.getInstance();
                string          url      = $"{CANDLES_URL}/{resolution}/{symbol}";
                result = httpUtil.requestHttpGet(url_prex, url, "limit = " + limit);
            }
            catch (Exception e)
            {
                Log4NetUtility.Error("RestApi_BC", result);
                throw e;
            }
            return(result);
        }
Example #29
0
        public Orders GetOrders_FC(string limit, string states, string symbol, string after = null, string before = null)
        {
            try
            {
                string JsonStr = restApi_FC.orders_info(limit, states, symbol, after, before);
                var    data    = ModelHelper <API.Rest.FCoin.ordersInfo> .Json2Model(JsonStr);

                Orders order = new Orders(data);
                return(order);
            }
            catch (Exception e)
            {
                Log4NetUtility.Error("GetOrderInfo_FC", Utils.Exception2String(e));
                DbHelper.CreateInstance().AddError("GetOrderInfo_FC", e);
                return(new Orders());
            }
        }
Example #30
0
        /// <summary>
        /// 发送get请求得到响应内容
        /// </summary>
        /// <param name="url_prex">url前缀</param>
        /// <param name="url">请求路径url</param>
        /// <param name="param">请求参数键值对</param>
        /// <returns>响应字符串</returns>
        public String requestHttpGet(String url_prex, String url, String param)
        {
            String          responseContent = "";
            HttpWebResponse httpWebResponse = null;
            StreamReader    streamReader    = null;

            try
            {
                url = url_prex + url;
                if (param != null && !param.Equals(""))
                {
                    url = url + "?" + param;
                }
                HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
                httpWebRequest.Method = "GET";
                httpWebResponse       = (HttpWebResponse)httpWebRequest.GetResponse();
                streamReader          = new StreamReader(httpWebResponse.GetResponseStream());
                if (streamReader == null)
                {
                    return("");
                }
                responseContent = streamReader.ReadToEnd();
                if (responseContent == null || "".Equals(responseContent))
                {
                    return("");
                }
            }
            catch (Exception e)
            {
                Log4NetUtility.Error("requestHttpGet", responseContent);

                throw e;
            }
            finally
            {
                if (httpWebResponse != null)
                {
                    httpWebResponse.Close();
                }
                if (streamReader != null)
                {
                    streamReader.Close();
                }
            }
            return(responseContent);
        }