using Muchinfo.MTPClient.Data.Enums; using Muchinfo.MTPClient.Infrastructure.LinkProxy; using Muchinfo.MTPClient.Infrastructure.LinkProxy.Enum; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.NetworkInformation; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using System.Windows; using System.Xml.Linq; using GalaSoft.MvvmLight.Ioc; using Muchinfo.MTPClient.Data.Model; using Muchinfo.MTPClient.Data.Model.Account; using Muchinfo.MTPClient.Infrastructure.Cache; using Muchinfo.MTPClient.Infrastructure.Helpers; using Muchinfo.MTPClient.Infrastructure.MessageBox; using Muchinfo.MTPClient.IService; namespace Muchinfo.MTPClient.Infrastructure.Utilities { /// /// ApplicationParameter类 /// public class ApplicationParameter { #region 私有字段 private static DateTime _serverTimeNow; private static int _showChart = 0; private static System.Timers.Timer _serverTimer; /// /// 基础时间 1970/01/01 00:00:00 /// private static DateTime _basicDateTime = new DateTime(1970, 1, 1, 0, 0, 0); #endregion #region 公有静态属性 /// /// 获取服务器当前时间 /// public static DateTime ServerTimeNow { get { return _serverTimeNow; } set { _serverTimeNow = value; } } /// /// 获取基础时间 1970/01/01 00:00:00 /// public static DateTime BasicDateTime { get { return _basicDateTime; } } /// /// 配置是否显示图表 /// public static int ShowChart { get { return _showChart; } set { _showChart = value; } } /// /// 配置是否显示报表 /// public static string ReportAddress { get; set; } /// /// 配置F10地址 /// public static string FtenAddress { get; set; } private static string _isShowIdentifyingCode; /// /// 是否显示验证码【 0:不显示,1:显示,2:错误后显示】 /// public static string IsShowIdentifyingCode { get { return _isShowIdentifyingCode; } set { _isShowIdentifyingCode = value; } } private static int _MarketTradeDefaultPriceMode = -1; /// /// 做市模式默认价格类型:若商品为做市模式,则默认成交的价格类型为“市价”【备注:0为市价,1为限价】 /// public static int MarketTradeDefaultPriceMode { get { return _MarketTradeDefaultPriceMode; } set { _MarketTradeDefaultPriceMode = value; } } private static int _BidTradeDefaultPriceMode = -1; /// /// 竞价模式默认价格类型: 若商品为竞价模式,则默认成交的价格类型为“限价”【备注:0为市价,1为限价】 /// public static int BidTradeDefaultPriceMode { get { return _BidTradeDefaultPriceMode; } set { _BidTradeDefaultPriceMode = value; } } /// /// 是否显示总浮动盈亏 /// public static int IsShowSumPL { get; set; } /// /// 会员风控间隔时间 /// public static int MemberMonitorTick { get; set; } /// /// 取历史Tick数据量 /// public static short QuoteTickCount { get; set; } /// /// 是否显示风险提示 /// public static int IsShowRateTips { get; set; } /// /// 是否显示托管计划 /// public static bool IsShowDepositPlanMarket { get; set; } /// /// 服务超时时间 /// public static int ServerTimeOut { get; set; } /// /// 交易地址 /// public static string BizAddress { get; set; } /// /// 行情地址 /// public static string QuoteAddress { get; set; } /// /// 游客行情地址 /// public static string GuestQuoteAddress { get; set; } /// /// 开户注册地址 /// public static string RegAccountAddress { get; set; } /// /// 是否显示预埋单功能 /// public static int IsPrePostVisible { get; set; } /// /// 是否限制预埋单数量:【是否限制预埋单数量(不限制:0,限制数量:1)】 /// public static decimal MaxPrePostOrderLot { get; set; } /// /// 默认下单数量 /// public static decimal DefaultOrderLot { get; set; } private static int _defaultOpenMode = 1; //edit by dk 默认为1 建仓方式,枚举值发生变化20171128 /// /// 设置下单默认建仓模式(1:建仓 2平仓;先平后建:3) /// public static int DefaultOpenMode { get { return _defaultOpenMode; } set { _defaultOpenMode = value; } } /// /// 提货单打印地址 /// public static string TakeOrderPrintAdress { get; set; } #endregion #region 系统参数属性 /// /// 官网 /// public static string WebSite { get; set; } /// /// 系统布局样色 /// public static string LayoutStyle { get; set; } /// /// 系统颜色主题 /// public static string ColorStyle { get; set; } /// /// 应用程序版本 /// public static string Version { get; set; } /// /// 显示表格的样式 /// public static string DataGridColor { get; set; } /// /// 显示登录界面提示信息 /// public static string LoginRemark { get; set; } /// /// 免责条款文件路径 /// public static string EscapeClauseFilePath { get { return Path.Combine(UserManager.SysConfigFolderPath, "EscapeClause.rtf"); } } /// /// 应用程序默认升级文件夹 /// public static string UpdateFolderName { get; set; } /// /// 发送邮件地址 /// public static string ToAddress { get; set; } /// /// 应用程序升级地址 /// public static string UpdateAddress { get; set; } public static string TradeSystemName { get; set; } public static string ExchangeName { get; set; } public static string MarketName { get; set; } /// /// 登录Guid /// public static string LoginGuid { get; set; } /// /// 图片扩展名 /// public static string ImageExtension { get; set; } /// /// 锁屏时间(0时不锁屏) /// public static int LockSreenTime { get; set; } /// /// 是否显示锁屏背景图片【0:不显示,1显示】 /// private static int _IsShowBGLockSreen = 0; public static int IsShowBGLockSreen { get { return _IsShowBGLockSreen; } set { _IsShowBGLockSreen = value; } } /// /// 同步账号信息周期 /// public static int SyncAccountCycle { get; set; } private static string _cusBankNetSign = string.Empty; /// /// 网银端签约的银行 /// public static string CusBankNetSign { get { return _cusBankNetSign; } set { _cusBankNetSign = value; } } /// /// 配置是否显示银行绑卡解绑功能 /// public static int IsConfigShowBingCard { get; set; } /// /// 网银端签约的提示信息 /// public static string CusBankNetSignTipsInfo { get; set; } public static int DayQuoteInterval { get; set; } /// /// 订单在市 /// public static string OrderOnMarket { get; set; } /// /// 已成交 /// public static string OrderTraded { get; set; } /// /// 单据是否显示买卖方向 /// public static int IsShowDirection { get; set; } /// /// 抬头保存的版本1.1.1.1 (自选.即期.竞价.混合) /// public static string ConfigHeadersVer { get; set; } /// /// 是否为对接新银行 /// public static int NewBankPlatform { get; set; } /// /// 是否显示交割信息 /// public static int IsDeliveryVisible { get; set; } /// /// 是否显示大字报价 /// //public static int IsShowQuoteBoard //{ // get; set; //} private static int _IsShowQuoteBoard = 0; /// /// 是否显示大字报价【默认不显示】 /// public static int IsShowQuoteBoard { get { return _IsShowQuoteBoard; } set { _IsShowQuoteBoard = value; } } /// /// 发售列表头(1,2,) /// public static string SaleQuoteHeaders { get; set; } /// /// 是否显示五档委托量(大利市) /// public static int QuoteQueueInfo { get; set; } /// /// 竞价市场显示的字段 /// public static string BidQuoteHeaders { get; set; } /// /// 混合市场显示的字段 /// public static string BidMarketQuoteHeaders { get; set; } /// /// 做市市场显示的字段 /// public static string MakeMarketQuoteHeaders { get; set; } /// /// 若商品为混合模式,则默认成交的价格类型为“限价”【备注:0为市价,1为限价】 /// public static int XMarketDefaultPriceMode { get; set; } /// /// 若商品为混合模式,则默认不显示”【备注:0为不显示,1为显示】 /// public static int XMarketShowMarketPrice { get; set; } /// /// 通道交易市场显示的字段 /// public static string ChannelQuoteHeaders { get; set; } public static string Copyright { get; set; } /// /// 是否显示所有商品 /// /// true if [show all goods]; otherwise, false. public static bool ShowAllGoods { get; set; } /// /// 是否显示我的自选 /// /// true if [show my selected goods]; otherwise, false. public static bool ShowMySelectedGoods { get; set; } /// /// 是否显示外部交易所 /// /// true if [show external exchage]; otherwise, false. public static bool ShowExternalExchage { get; set; } /// /// 是否显示平仓 /// /// true if [show close order]; otherwise, false. public static bool ShowCloseOrder { get; set; } public static bool ShowOpenCloseOrder { get; set; } /// /// 是否显示下单界面的买卖价,来源config.xml /// public static bool ShowBuyOrSellPrice { get; set; } public static bool CanUseAllCloseOrder { get;set; } public static bool CanUseQuickClose { get;set; } public static bool CanUseBackHandOpen { get;set; } public static bool CanUseQuickLockOrder { get;set; } public static string PublishNetIpAddress { get; set; } #endregion #region 风管云平台 /// /// 风管云平台服务地址 /// public static string ErmcpAddress { get; set; } /// /// 风管云平台WEB端地址 /// public static string ErmcpWebUrl { get; set; } #endregion #region 公有静态方法 /// /// 从Config.xml读取系统配置 /// public static void InitializeSystemConfig() { try { LoginGuid = Guid.NewGuid().ToString(); var path = Path.Combine(UserManager.SysConfigFolderPath, "Config.xml"); var xdoc = XDocument.Load(path); if (xdoc.Root == null) return; var config = (from e in xdoc.Root.Elements("Config") select new { QuoteAddress = (string)e.Element("QuoteAddress"), BizAddress = (string)e.Element("BizAddress"), UpdateAddress = (string)e.Element("UpdateAddress"), UpdateFolderName = (string)e.Element("UpdateFolderName"), LoginRemark = (string)e.Element("LoginRemark"), TradeSystemName = (string)e.Element("TradeSystemName"), GuestQuoteAddress = (string)e.Element("GuestQuoteAddress"), DayQuoteInterval = (string)e.Element("DayQuoteInterval"), RegAccountAddress = (string)e.Element("RegAccountAddress"), IsShowIdentifyingCode = (string)e.Element("IsShowIdentifyingCode"), ConfigHeadersVer = (string)e.Element("ConfigHeadersVer"), FtenAddress = (string)e.Element("FtenAddress"), ExchangeName = (string)e.Element("ExchangeName"), WebSite = (string)e.Element("WebSite"), LayoutStyle = (string)e.Element("LayoutStyle"), Copyright = (e.Element("Copyright") == null) ? "Copyright © 2020" : (string)e.Element("Copyright"), ShowAllGoods =e.Element("ShowAllGoods") == null || (bool)e.Element("ShowAllGoods"), ShowMySelectedGoods = e.Element("ShowMySelectedGoods") != null && (bool)e.Element("ShowMySelectedGoods"), ShowExternalExchage = e.Element("ShowExternalExchage") != null && (bool)e.Element("ShowExternalExchage"), ShowCloseOrder = e.Element("ShowCloseOrder") != null && (bool)e.Element("ShowCloseOrder"), ShowOpenCloseOrder = e.Element("ShowOpenCloseOrder") != null && (bool)e.Element("ShowOpenCloseOrder"), ShowBuyOrSellPrice = e.Element("ShowBuyOrSellPrice") != null && (bool)e.Element("ShowBuyOrSellPrice"), CanUseAllCloseOrder = e.Element("CanUseAllCloseOrder") != null && (bool)e.Element("CanUseAllCloseOrder"), CanUseQuickClose = e.Element("CanUseQuickClose") != null && (bool)e.Element("CanUseQuickClose"), CanUseBackHandOpen = e.Element("CanUseBackHandOpen") != null && (bool)e.Element("CanUseBackHandOpen"), CanUseQuickLockOrder = e.Element("CanUseQuickLockOrder") != null && (bool)e.Element("CanUseQuickLockOrder"), PublishNetIpAddress = (string)e.Element("PublishNetIpAddress"), ErmcpAddress = (string)e.Element("ErmcpAddress"), ErmcpWebUrl = (string)e.Element("ErmcpWebUrl"), }).FirstOrDefault(); if (config == null) return; QuoteAddress = config.QuoteAddress; BizAddress = config.BizAddress; UpdateAddress = config.UpdateAddress; UpdateFolderName = config.UpdateFolderName; Version = Application.ResourceAssembly.GetName().Version.ToString(); LoginRemark = config.LoginRemark; TradeSystemName = config.TradeSystemName; GuestQuoteAddress = config.GuestQuoteAddress; RegAccountAddress = config.RegAccountAddress; ConfigHeadersVer = config.ConfigHeadersVer; FtenAddress = config.FtenAddress; IsShowIdentifyingCode = config.IsShowIdentifyingCode; int interval = 0; int.TryParse(config.DayQuoteInterval, out interval); DayQuoteInterval = interval; ExchangeName = config.ExchangeName; WebSite = config.WebSite; LayoutStyle = config.LayoutStyle; Copyright = config.Copyright; ShowAllGoods = config.ShowAllGoods; ShowMySelectedGoods = config.ShowMySelectedGoods; ShowExternalExchage = config.ShowExternalExchage; ShowCloseOrder = config.ShowCloseOrder; ShowOpenCloseOrder = config.ShowOpenCloseOrder; ShowBuyOrSellPrice = config.ShowBuyOrSellPrice; CanUseAllCloseOrder = config.CanUseAllCloseOrder; CanUseQuickClose = config.CanUseQuickClose; CanUseBackHandOpen = config.CanUseBackHandOpen; CanUseQuickLockOrder = config.CanUseQuickLockOrder; PublishNetIpAddress = config.PublishNetIpAddress; ErmcpAddress = config.ErmcpAddress; ErmcpWebUrl = config.ErmcpWebUrl; ////初始化链路 InitializeLink(); } catch (Exception e) { throw e; } } /// /// 设置系统时间s /// /// public static void SetSystemTime(ulong seconds) { seconds -= 60 * 60 * 8; long lTime = long.Parse(seconds + "0000000"); TimeSpan toNow = new TimeSpan(lTime); var timeNow = TimeZone.CurrentTimeZone.ToLocalTime(_basicDateTime.Add(toNow)); SetServerTime(timeNow); } /// /// 设置系统时间s /// /// public static void SetSystemTime(int seconds) { seconds -= 60 * 60 * 8; var timeNow = TimeZone.CurrentTimeZone.ToLocalTime(_basicDateTime.AddMilliseconds(seconds)); SetServerTime(timeNow); } /// /// 设置服务器时间 /// /// 服务器时间 public static void SetServerTime(DateTime serverTime) { if (_serverTimer == null) { _serverTimer = new System.Timers.Timer(1000); _serverTimer.Elapsed += new System.Timers.ElapsedEventHandler(m_ServerTimer_Elapsed); } _serverTimer.Stop(); _serverTimeNow = serverTime; _serverTimer.Start(); } #endregion /// /// 判断是否显示市价 /// public static bool CanMarketPrice(QuoteGoods currentGoods) { var external = CacheManager.CacheExchanges; var groups = CacheManager.CacheGoodsGroups; var isMarketPrice = ""; if (groups != null && groups.Any()) { groups.ForEach((group) => { if (group.GoodsGroupid == currentGoods.GroupID)// 先用商品中的groupId 去 商品组中查找,找出ExchangeId { var exchangeId = group.ExChangeId; if (external != null && external.Any()) { var exchaneInfo = external.Find((externalExchange) => exchangeId == externalExchange.ExchangeId); if (exchaneInfo != null) { isMarketPrice = exchaneInfo.IsMarketPrice; } } } }); } if ("0".Equals(isMarketPrice)) // 不支持 { return false; } else if ("1".Equals(isMarketPrice)) // 支持 { return true; } return false; } #region 私有静态方法 /// /// Handles the Elapsed event of the m_ServerTimer control. /// /// The source of the event. /// The instance containing the event data. private static void m_ServerTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) { _serverTimeNow = _serverTimeNow.AddSeconds(1); } /// /// 初始化链路 /// private static void InitializeLink() { var quotationAddress = QuoteAddress.Split(':'); var tradeAddress = BizAddress.Split(':'); string quotationHost = string.Empty; string guestQuoteHost = string.Empty; string tradeHost = string.Empty; int quotationPort = 0, tradePort = 0, guestQuotePort = 0; if (quotationAddress.Length == 2) { quotationHost = quotationAddress[0]; int.TryParse(quotationAddress[1], out quotationPort); } if (tradeAddress.Length == 2) { tradeHost = tradeAddress[0]; int.TryParse(tradeAddress[1], out tradePort); } if (!string.IsNullOrWhiteSpace(GuestQuoteAddress)) { var guestQuoteAdd = GuestQuoteAddress.Split(':'); if (quotationAddress.Length == 2) { guestQuoteHost = guestQuoteAdd[0]; int.TryParse(guestQuoteAdd[1], out guestQuotePort); } } LinkManager.Instance.Initialize(new LinkManagerParameters() { QuotationHost = quotationHost, QuotationPort = quotationPort, TradeHost = tradeHost, TradePort = tradePort, GuestQuotationHost = guestQuoteHost, GuestQuotationPort = guestQuotePort, TradeLinkeType = LinkType.TCP, TradeDatagramType = DatagramType.Protobuf }); } #endregion #region 风管云平台 /// /// 风管云平台参数更新方法,主要是通过GO服务更新相关配置信息 /// public static bool UpdateErmcpParamete() { // 获取交易与行情 Host var jsonString = HttpUtility.HttpGet(ErmcpAddress); if (jsonString != null) { Dictionary dicJson = Newtonsoft.Json.JsonConvert.DeserializeObject>(jsonString); Dictionary dataJson = Newtonsoft.Json.JsonConvert.DeserializeObject>(dicJson["data"].ToString()); LinkManager.Instance.Parameters.TradeHost = dataJson["tradeHost"]; LinkManager.Instance.Parameters.TradePort = int.Parse(dataJson["tradePort"]); LinkManager.Instance.Parameters.QuotationHost = dataJson["quoteHost"]; LinkManager.Instance.Parameters.QuotationPort = int.Parse(dataJson["quotePort"]); LinkManager.Instance.Parameters.GoCommonSearchUrl = dataJson["goCommonSearchUrl"]; return true; } return false; } #endregion public static LockType _LockType = LockType.UnLock;// 锁定商品 /// /// 适配自动止损止盈的功能-将本地设置的止盈止损上传到服务端去。由服务端处理 /// /// /// public static void MakeSpsl(NewEntrustOrder newOrder) { if (newOrder == null) { return; } var userInfo = UserManager.GetCurrentUserInfo(); if (userInfo != null && userInfo.TradeParams != null) { var goodsParams = userInfo.TradeParams.AllGoodsForAutoEntrust; if (goodsParams != null && goodsParams.Count > 0) { var _params = goodsParams.FirstOrDefault(item => newOrder.GoodsId == item.GoodsId && newOrder.BuyOrSell == (Direction)item.Direction);// 在匹配商品的同时,还需要匹配买卖方向 if (_params != null && newOrder.BuildType == OpenCloseMode.BUILDTYPE_OPEN) // 只有建仓时候才会考虑上传止盈止损 { newOrder.SPPoint = _params.Profit; newOrder.SLPoint = _params.Loss; } } } } /// /// 交易所下商品组、商品的关系 /// 1、交易所下有多个商品组,商品组下有多个商品。 /// /// public static void MakeExChangeGroupGoodsMap() { // uint是商品组的groupId ,商品的数量 ExChangeCheckModel changeCheckModel = new ExChangeCheckModel(); var allGoods = CacheManager.CacheGoodsBaseInfos;// 所有的商品 foreach (QuoteGoods item in allGoods) { if (changeCheckModel.Group.ContainsKey(item.GroupID)) { changeCheckModel.Group[item.GroupID].Add(item.GoodsId); } else { List goodsIds = new List {item.GoodsId}; changeCheckModel.Group.Add(item.GroupID, goodsIds); } } // 查找交易所和商品组的关系 var groups = CacheManager.CacheGoodsGroups; foreach (GoodsGroup goodsGroup in groups) { if (changeCheckModel.ExChangeGroup.ContainsKey(goodsGroup.ExChangeId)) { changeCheckModel.ExChangeGroup[goodsGroup.ExChangeId].Add(goodsGroup.GoodsGroupid); } else { List groupIds = new List() {goodsGroup.GoodsGroupid}; changeCheckModel.ExChangeGroup.Add(goodsGroup.ExChangeId, groupIds); } } CacheManager.LoadExChangeGroupGoods(changeCheckModel); } #region 获取ip地址 private static string _publisgNetIp = ""; public static string PublisgNetIp { get { return _publisgNetIp ?? HttpGetPublishNetIp(); } set { _publisgNetIp = value; } } /// /// 获取公网ip地址 --如果机器是局域网的,获取到的地址就是本机地址,如果电脑是拨号上网或者具有独立的公网IP的情况下,获取到的是公网地址 /// /// "" 表示本地所有ip,InterNetWork表示ipv类型的网络ip,InterNetworkV6 表示获取ipv6类型的网络ip地址 /// private static string GetIp(string netType) { string hostName = Dns.GetHostName(); IPAddress[] addresses = Dns.GetHostAddresses(hostName); List ipsList = new List(); if (netType == string.Empty) { for (int i = 0; i < addresses.Length; i++) { ipsList.Add(addresses[i].ToString()); } } else { for (int i = 0; i < addresses.Length; i++) { if (addresses[i].AddressFamily.ToString() == netType) { ipsList.Add(addresses[i].ToString()); } } } for (int i = 0; i < ipsList.Count; i++) { if (ipsList[i].Equals("::1")) { continue; } return ipsList[i]; } return ""; } private static string GetNetIp() { //试试这个 NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces(); foreach (NetworkInterface ni in interfaces) { if (ni.NetworkInterfaceType == NetworkInterfaceType.Ethernet) { foreach (UnicastIPAddressInformation ip in ni.GetIPProperties().UnicastAddresses) { if (ip.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) { return ip.Address.ToString(); } } } } return GetIp(""); } public static void MakePublishNetIp() { _publisgNetIp = ""; Task.Factory.StartNew(() => { PublisgNetIp = HttpGetPublishNetIp(); }); } private static string HttpGetPublishNetIp() { if (_publisgNetIp != string.Empty) { return _publisgNetIp; } string ret = ""; try { if (ApplicationParameter.PublishNetIpAddress == null || ApplicationParameter.PublishNetIpAddress.Equals("")) { return GetNetIp(); } else { string url = ""; string encoding = ""; if (ApplicationParameter.PublishNetIpAddress.Contains(@"|")) { string[] datas = ApplicationParameter.PublishNetIpAddress.Split(Convert.ToChar(@"|")); if (datas.Length > 1) { url = datas[0]; encoding = datas[1]; } } else { url = ApplicationParameter.PublishNetIpAddress; } if (encoding == string.Empty) { encoding = "gbk"; } Encoding encode = Encoding.GetEncoding(encoding); MyWebClient MyWebClient = new MyWebClient(3*1000); MyWebClient.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.84 Safari/537.36"); MyWebClient.Credentials = CredentialCache.DefaultCredentials; //获取或设置用于向Internet资源的请求进行身份验证的网络凭据 Byte[] pageData = MyWebClient.DownloadData(url); //从指定网站下载数据 string pageHtml = encode.GetString(pageData); //如果获取网站页面采用的是GB2312,则 使用这句 ret = parseHtml(pageHtml); if (ret != String.Empty) { return ret; } return GetNetIp(); } } catch (Exception e) { if (ret == String.Empty) { GetNetIp(); } } finally { if (ret == String.Empty) { GetNetIp(); } } return GetNetIp(); } private static string parseHtml(String pageHtml) { string ip = ""; //Match m = Regex.Match(pageHtml, @"\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}"); Match m = Regex.Match(pageHtml, @"((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)"); if (m.Success) { return m.Value; } ip = pageHtml; return ip; } #endregion } }