Example #1
0
        public override void OnRspUserLogin(ThostFtdcRspUserLoginField pRspUserLogin, ThostFtdcRspInfoField pRspInfo, int nRequestID, bool bIsLast)
        {
            if (pRspInfo.ErrorID != 0)
            {
                LogCenter.Error("交易登录失败:" + pRspInfo.ErrorMsg);
                return;
            }
            LogCenter.Log("交易登录成功");
            AccountCenter.Instance.IsTDLogin = true;
            this.instruments.Clear();
            LogCenter.Log("请求查询合约");
            int i = this.ReqQryInstrument(new ThostFtdcQryInstrumentField(), 0);

            if (i != 0)
            {
                LogCenter.Error("请求查询合约错误:" + CTPErrorHelper.GetError(i));
            }
            var field = new ThostFtdcSettlementInfoConfirmField
            {
                BrokerID    = AccountCenter.Instance.Account.BrokerID,
                InvestorID  = AccountCenter.Instance.Account.InvestorID,
                ConfirmDate = DateTime.Today.ToString(),
                ConfirmTime = DateTime.Now.ToLongTimeString()
            };

            LogCenter.Log("投资者结算结果确认");
            i = this.ReqSettlementInfoConfirm(field, 0);
            if (i != 0)
            {
                LogCenter.Error("投资者结算结果确认错误:" + CTPErrorHelper.GetError(i));
            }
        }
Example #2
0
        public override SiteCookie GetCookie()
        {
            if (string.IsNullOrEmpty(Pattern))
            {
                throw new Exception("Fiddler CookieTrapper: Pattern cannot be null!");
            }

            string cookie;

            using (FiddlerClient fiddlerWrapper = new FiddlerClient(ProxyPort, Pattern))
            {
                fiddlerWrapper.StartCapture(true);
                try
                {
                    base.GetCookie();
                    var          header         = fiddlerWrapper.Headers;
                    const string cookiesPattern = @"Cookie: (.*?)\r\n";
                    cookie = Regex.Match(header, cookiesPattern).Groups[1].Value;
                }
                catch (Exception e)
                {
                    LogCenter.Log(null, "Get cookie failed.", LogLevel.Error, e);
                    return(null);
                }
                fiddlerWrapper.StopCapture();
            }

            return(new SiteCookie {
                CookiesStringPart = cookie
            });
        }
Example #3
0
        private void UpdateProxy()
        {
            var result = _supplier.GetProxies();

            Parallel.ForEach(result, new ParallelOptions
            {
                MaxDegreeOfParallelism = 10
            }, proxy =>
            {
                var key   = proxy.Key;
                var value = proxy.Value;
                if (_allProxy.ContainsKey(key))
                {
                    return;
                }

                if (ProxyUtil.ValidateProxy(proxy.Value.HttpHost.Uri.Host, proxy.Value.HttpHost.Uri.Port))
                {
                    LogCenter.Log(null, $"Detect one usefull proxy: {key}", LogLevel.Debug);
                    value.SetFailedNum(0);
                    value.SetReuseTime(_reuseInterval);

                    _proxyQueue.Add(value);
                    _allProxy.GetOrAdd(key, value);
                }
            });
        }
Example #4
0
        void  CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            Exception exception = e.ExceptionObject as Exception;

            MessageBox.Show("程序出现异常,请联系开发者!", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            LogCenter.Log(exception);
        }
Example #5
0
        public static bool ValidateProxy(string ip, int port)
        {
            bool isReachable = false;

            string http = $"http://{ip}:{port}";

            try
            {
                HttpClient client = new HttpClient(new HttpClientHandler
                {
                    AllowAutoRedirect = true,
                    UseProxy          = true,
                    Proxy             = new UseSpecifiedUriWebProxy(new Uri(http))
                })
                {
                    Timeout = new TimeSpan(0, 0, 0, 5)
                };
                var result = client.GetStringAsync("http://www.baidu.com").Result;
                if (result.Contains("百度"))
                {
                    isReachable = true;
                }
            }
            catch (Exception e)
            {
                LogCenter.Log(null, "FAILRE - CAN not connect! Proxy: " + http, Infrastructure.LogLevel.Error, e);
            }

            return(isReachable);
        }
Example #6
0
        public void InsertOrder(InputOrder order)
        {
            LogCenter.Log("下单:" + order.ToString());
            var field = new ThostFtdcInputOrderField
            {
                BrokerID            = order.BrokerID,
                InvestorID          = order.InvestorID,
                Direction           = (EnumDirectionType)order.Direction,
                CombOffsetFlag_0    = (EnumOffsetFlagType)order.OffsetFlag,
                InstrumentID        = order.InstrumentID,
                LimitPrice          = order.Price,
                VolumeTotalOriginal = order.Volume,
                UserID = order.GroupID,

                CombHedgeFlag_0     = EnumHedgeFlagType.Speculation,
                ForceCloseReason    = EnumForceCloseReasonType.NotForceClose,
                ContingentCondition = EnumContingentConditionType.Immediately,
                TimeCondition       = EnumTimeConditionType.GFD,
                VolumeCondition     = EnumVolumeConditionType.AV,
                OrderPriceType      = EnumOrderPriceTypeType.LimitPrice,
                MinVolume           = 1,
                IsAutoSuspend       = 1,
            };
            int i = this.ReqOrderInsert(field, 0);

            if (i != 0)
            {
                LogCenter.Error("输入报单错误:" + CTPErrorHelper.GetError(i));
            }
        }
        public RedialResult Redial(Action action = null)
        {
            if (CheckIsRedialing())
            {
                while (true)
                {
                    Thread.Sleep(50);
                    if (!CheckIsRedialing())
                    {
                        //ReleaseRedialLocker();
                        return(RedialResult.OtherRedialed);
                    }
                }
            }
            else
            {
                try
                {
                    LogCenter.Log(null, "Wait all atomic action...", LogLevel.Warn);
                    // 等待数据库等操作完成
                    WaitAll();
                    LogCenter.Log(null, "Start redial...", LogLevel.Warn);

                    Redialer.Redial();

                    InternetDetector.Detect();

                    Thread.Sleep(2000);
                    LogCenter.Log(null, "Redial finished.", LogLevel.Warn);

                    action?.Invoke();

                    return(RedialResult.Sucess);
                }
                catch (IOException)
                {
                    // 有极小可能同时调用File.Open时抛出异常
                    return(Redial(action));
                }
                catch (Exception)
                {
                    return(RedialResult.Failed);
                }
                finally
                {
                    ReleaseRedialLocker();
                    if (AfterRedialWaitTime > 0)
                    {
                        Console.WriteLine($"Going to sleep for {AfterRedialWaitTime} after redial.");
                        Thread.Sleep(AfterRedialWaitTime);
                    }
                }
            }
        }
Example #8
0
        public override void OnRspUserLogin(ThostFtdcRspUserLoginField pRspUserLogin, ThostFtdcRspInfoField pRspInfo, int nRequestID, bool bIsLast)
        {
            if (pRspInfo.ErrorID != 0)
            {
                LogCenter.Error("行情登录失败:" + pRspInfo.ErrorMsg);
                return;
            }
            LogCenter.Log("行情登录成功");
            AccountCenter.Instance.IsMDLogin = true;
            int i = this.SubscribeMarketData(subscribeSet.ToArray());

            if (i != 0)
            {
                LogCenter.Error("订阅行情错误:" + CTPErrorHelper.GetError(i));
            }
        }
Example #9
0
        public override void OnFrontConnected()
        {
            LogCenter.Log("行情连接成功");
            var loginField = new ThostFtdcReqUserLoginField
            {
                BrokerID = AccountCenter.Instance.Account.BrokerID,
                UserID   = AccountCenter.Instance.Account.InvestorID,
                Password = AccountCenter.Instance.Account.Password
            };
            int i = this.ReqUserLogin(loginField, 0);

            if (i != 0)
            {
                LogCenter.Error("行情登录失败:" + CTPErrorHelper.GetError(i));
            }
        }
Example #10
0
        private void DoArbiOrder()
        {
            if (!this.VerifyLogin())
            {
                return;
            }
            LogCenter.Log("套利单发送,价差:" + this.Spread);
            string groupID = Guid.NewGuid().ToString();

            foreach (var item in this.InstrumentModels)
            {
                var order = this.GenerateOrder(item, groupID);
                TradeAdapter.Instance.InsertOrder(order);
            }
            SpeechHelper.Speak("Order");
        }
Example #11
0
 public override void OnRspQryInstrument(ThostFtdcInstrumentField pInstrument, ThostFtdcRspInfoField pRspInfo, int nRequestID, bool bIsLast)
 {
     if (pRspInfo != null && pRspInfo.ErrorID != 0)
     {
         LogCenter.Error("请求查询合约错误:" + pRspInfo.ErrorMsg);
         return;
     }
     if (pInstrument.ProductClass == EnumProductClassType.Futures)
     {
         this.instruments.Add(new Instrument(pInstrument));
     }
     if (bIsLast)
     {
         LogCenter.Log("收到期货合约数量:" + this.instruments.Count);
         InstrumentCenter.Instance.SetInstruments(this.instruments.OrderBy(p => p.InstrumentID).ToArray());
     }
 }
Example #12
0
        public RedialResult Redial()
        {
            if (CheckIsRedialing())
            {
                while (true)
                {
                    Thread.Sleep(50);
                    if (!CheckIsRedialing())
                    {
                        return(RedialResult.OtherRedialed);
                    }
                }
            }
            else
            {
                try
                {
                    LogCenter.Log(null, "Wait all atomic action...", LogLevel.Warn);
                    // 等待数据库等操作完成
                    WaitAll();
                    LogCenter.Log(null, "Start redial...", LogLevel.Warn);

                    Redialer.Redial();

                    InternetDetector.Detect();

                    Thread.Sleep(2000);
                    LogCenter.Log(null, "Redial finished.", LogLevel.Warn);
                    return(RedialResult.Sucess);
                }
                catch (IOException)
                {
                    // 有极小可能同时调用File.Open时抛出异常
                    return(Redial());
                }
                catch (Exception)
                {
                    return(RedialResult.Failed);
                }
                finally
                {
                    ReleaseRedialLocker();
                }
            }
        }
Example #13
0
 private static void PublishQuotation()
 {
     while (true)
     {
         if (marketDataFieldQueue.Count == 0)
         {
             Thread.Sleep(1);
             continue;
         }
         ThostFtdcDepthMarketDataField field = marketDataFieldQueue.Dequeue();
         if (field.LastPrice == 0)
         {
             LogCenter.Log("过滤价格为0的数据:" + field.InstrumentID);
             continue;
         }
         ArbitrageViewModel.Instance.ProcessQuotation(new Quotation(field));
     }
 }
Example #14
0
    public void LogHandler(string message, string stacktrace, UnityEngine.LogType type)
    {
        StringBuilder s = new StringBuilder();

        s.Append(message);
        s.Append("\r\n");
        if (type == UnityEngine.LogType.Error || type == UnityEngine.LogType.Exception)
        {
            s.Append(stacktrace);
            LogCenter.LogError(s.ToString());
        }
        else if (type == UnityEngine.LogType.Log)
        {
            LogCenter.Log(s.ToString());
        }
        else if (type == UnityEngine.LogType.Warning)
        {
            LogCenter.LogWarning(s.ToString());
        }
    }
        public static bool ValidateProxy(string ip, int port)
        {
            bool isReachable = false;

            try
            {
                TcpClient tcp    = new TcpClient();
                IPAddress ipAddr = IPAddress.Parse(ip);
                tcp.ReceiveTimeout = 5000;
                Stopwatch watch = new Stopwatch();
                watch.Start();
                tcp.ConnectAsync(ipAddr, port).Wait();
                watch.Stop();
                LogCenter.Log(null, $"Detect one usefull proxy: {ip}:{port}, cost {watch.ElapsedMilliseconds}ms.", LogLevel.Debug);
                isReachable = true;
            }
            catch (Exception e)
            {
                LogCenter.Log(null, $"FAILRE - CAN not connect! Proxy: {ip}:{port}.", LogLevel.Error, e);
            }

            return(isReachable);
        }
Example #16
0
        public override SiteCookie GetCookie()
        {
            var cookies = new Dictionary <string, string>();

            var webDriver = GetWebDriver();

            try
            {
                webDriver.Navigate().GoToUrl(Url);
                Thread.Sleep(10000);

                if (LoginAreaSelector != null)
                {
                    var loginArea = FindElement(webDriver, LoginAreaSelector);
                    loginArea.Click();
                    Thread.Sleep(1000);
                }

                if (UserSelector != null)
                {
                    var user = FindElement(webDriver, UserSelector);
                    user.Clear();
                    user.SendKeys(User);
                    Thread.Sleep(1500);
                }

                if (PassSelector != null)
                {
                    var pass = FindElement(webDriver, PassSelector);
                    pass.Clear();
                    pass.SendKeys(Pass);
                    Thread.Sleep(1500);
                }

                var submit = FindElement(webDriver, SubmitSelector);
                submit.Click();
                Thread.Sleep(10000);

                if (!string.IsNullOrEmpty(AfterLoginUrl))
                {
                    webDriver.Navigate().GoToUrl(AfterLoginUrl);
                    Thread.Sleep(10000);
                }

                var cookieList = webDriver.Manage().Cookies.AllCookies.ToList();
                if (cookieList.Count > 0)
                {
                    foreach (var cookieItem in cookieList)
                    {
                        cookies.Add(cookieItem.Name, cookieItem.Value);
                    }
                }

                webDriver.Dispose();
            }
            catch (Exception e)
            {
                LogCenter.Log(null, "Get cookie failed.", LogLevel.Error, e);
                webDriver.Dispose();
                return(null);
            }

            return(new SiteCookie {
                CookiesDictionary = cookies
            });
        }
Example #17
0
 void App_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
 {
     LogCenter.Log(e.Exception);
 }