/// <summary> /// 程序初始化。 /// </summary> /// <returns></returns> private bool Init() { Debug.Assert(!String.IsNullOrEmpty(m_appName)); Console.Title = m_appName; FileInfo fileInfo = new FileInfo(Process.GetCurrentProcess().MainModule.FileName); System.Environment.CurrentDirectory = fileInfo.DirectoryName; IAppLogger logger = null; try { logger = AppLogger.InitInstance(); } catch (Exception ex) { USeConsole.WriteLine(string.Format("初始化日志失败,错误:{0}.", ex.Message)); return(false); } AppDomain.CurrentDomain.UnhandledException += OnUnhandledException; logger.LineFeed(); logger.WriteInformation(m_appName + " 启动。"); return(true); }
static void Main() { FileInfo fileInfo = new FileInfo(Process.GetCurrentProcess().MainModule.FileName); Environment.CurrentDirectory = fileInfo.DirectoryName; AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(OnDomainUnhandledException); Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(OnAppThreadException); if (!InitAppLoggers()) { return; } IAppLogger logger = AppLogger.SingleInstance; Debug.Assert(logger != null); logger.LineFeed(); logger.WriteInformation(AppName + " started."); if (!InitUseManager()) { goto End; } try { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); LoginForm loginForm = new LoginForm(); Application.Run(loginForm); if (USeManager.Instance.LoginUser != null) { if (USeManager.Instance.ProcessBeforStartWork() == false) { goto End; } USeManager.Instance.Start(); MainForm form = new MainForm(); Application.Run(form); } } catch (Exception ex) { MessageBox.Show("Run Application failed, Error: " + ex.Message, AppTitle, MessageBoxButtons.OK, MessageBoxIcon.Error); } End: USeManager.Instance.Close(); logger.WriteInformation(AppName + " shutdown."); logger.Flush(); }
static int Main(string[] args) { FileInfo fileInfo = new FileInfo(Process.GetCurrentProcess().MainModule.FileName); Environment.CurrentDirectory = fileInfo.DirectoryName; AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(OnDomainUnhandledException); Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(OnAppThreadException); if (!InitAppLoggers()) { return(-1); } IAppLogger logger = AppLogger.SingleInstance; Debug.Assert(logger != null); logger.LineFeed(); logger.WriteInformation(AppName + " started."); DayNightType dayNightType = DayNightType.Day; if (args != null && args.Length > 0) { if (Enum.TryParse(args[0], out dayNightType) == false) { logger.WriteError(string.Format("日夜盘类型参数[{0}]错误", args[0])); return(-1); } } if (!InitUseManager()) { goto End; } USeManager.Instance.DayNightType = dayNightType; try { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new MainForm()); } catch (Exception ex) { MessageBox.Show("Run Application failed, Error: " + ex.Message, AppTitle, MessageBoxButtons.OK, MessageBoxIcon.Error); } End: USeManager.Instance.Close(); logger.WriteInformation(AppName + " shutdown."); logger.Flush(); return(0); }
public int Start() { try { m_eventLogger = AppLogger.InitInstance(); } catch { m_eventLogger = new NullLogger("DownloadProcessor_DefaultLogger"); } m_eventLogger.LineFeed(); string text = string.Format("本地时间:{0},开始更新午盘数据", DateTime.Now); m_eventLogger.WriteInformation(text); if (ReadConfig() == false) { return(-1); } while (true) { if (DateTime.Now.TimeOfDay < m_queryNoonBeginTime || DateTime.Now.TimeOfDay > m_queryNoonEndTime) { Console.WriteLine(string.Format("当前本地时间:{0} 不在午盘开始查询时间{1} 和午盘查询结束时间{2}之间,继续等待...", DateTime.Now, m_queryNoonBeginTime, m_queryNoonEndTime)); System.Threading.Thread.Sleep(5000); continue; } try { UpdateNoonClosePriceToDB(); } catch (Exception ex) { string exInfo = string.Format("本地时间:{0},更新午盘数据发生异常:", ex.Message); m_eventLogger.WriteInformation(exInfo); return(-1); } } }
private TimeSpan m_nextDayRange = new TimeSpan(18, 0, 0); // 下一交易日的时间分界点 #endregion // member #region methods /// <summary> /// 启动结算价下载。 /// </summary> public int Start() { //确定更新结算价成功之后,需要再次计算资金沉淀,盘中的时候用的是最新价计算,有结算价之后,就改为结算价重新刷新一遍计算 //计算公式:资金沉淀=品种持仓量*结算价*合约规模*交易所多头保证金比例 //计算资金总沉淀(盘中就用最新价计算资金沉淀,待下午结算价出来之后,按照结算价再更新一次) //int perSharesContract = GetInstrumentPerSharesContract(marketData.Instrument.InstrumentCode);//合约规模 //decimal exchangeLongMarginRatio = GetExchangeLongMarginRatio(marketData.Instrument.InstrumentCode);//保证金 //m_kLine.SendimentaryMoney = marketData.OpenInterest * marketData.LastPrice * perSharesContract * exchangeLongMarginRatio;//资金沉淀 //取出UseinstrumentDetail品种合约信息取出合约规模和保证金额比例,再次执行SQL语句 try { m_eventLogger = AppLogger.InitInstance(); } catch { m_eventLogger = new NullLogger("DownloadProcessor_DefaultLogger"); } m_eventLogger.LineFeed(); string text = "开始下载结算价服务"; m_eventLogger.WriteInformation(text); WriteConsoleLog(text); if (ReadConfig() == false) { return(-1); } //下载所有合约详情,失败直接退出因为后面需要基础数据 try { USeTradingInstrumentManager tradingInsManager = CreateInstrumentManager(); m_insDetailList = tradingInsManager.GetAllInstrumentDetails(); Debug.Assert(m_insDetailList != null); } catch (Exception ex) { text = "下载数据库所有合约详情InstrumentDetail失败," + ex.Message; WriteConsoleLog(text); m_eventLogger.WriteError(text); return(-1); } CtpOrderQuerier ctpApp = new CtpOrderQuerier(); try { ctpApp.Connect(m_ctpDriverConfig.Address, m_ctpDriverConfig.Port, m_ctpDriverConfig.LoginTimeOut, m_ctpDriverConfig.QueryTimeOut); text = "连接CTP交易服务器成功"; WriteConsoleLog(text); m_eventLogger.WriteInformation(text); } catch (Exception ex) { text = "连接CTP交易服务器失败," + ex.Message; WriteConsoleLog(text); m_eventLogger.WriteError(text); ctpApp.Disconnect(); return(-1); } try { ctpApp.Login(m_ctpAccountConfig.ID, m_ctpAccountConfig.Password, m_ctpAccountConfig.BrokerID); text = "登陆CTP交易服务器成功"; WriteConsoleLog(text); m_eventLogger.WriteInformation(text); } catch (Exception ex) { text = "登陆CTP交易服务器失败," + ex.Message; WriteConsoleLog(text); m_eventLogger.WriteError(text); ctpApp.Disconnect(); return(-1); } try { List <InstrumentField> instrumentList = ctpApp.QueryInstument(); foreach (InstrumentField item in instrumentList) { if (item.ProductClass != ProductClass.Futures) { continue; } USeInstrumentDetail entity = InsturmentFiledToUSeInstrumentDetail(item); instrumentDic.Add(entity.Instrument.InstrumentCode, entity); } text = string.Format("查询期货合约数据完成,共计{0}个合约", instrumentDic.Count); WriteConsoleLog(text); m_eventLogger.WriteInformation(text); } catch (Exception ex) { text = "查询期货合约数据失败," + ex.Message; WriteConsoleLog(text); m_eventLogger.WriteError(text); ctpApp.Disconnect(); return(-1); } DateTime tradingDate = GetTradingDay(); if (m_refrashDate == QueryDay.Today) { int queryNum = m_queryNum; while (queryNum > 0) { try { List <DepthMarketDataField> tempDepthMarketDataFieldList = ctpApp.QueryDepthMarketData(); Debug.Assert(tempDepthMarketDataFieldList != null); foreach (DepthMarketDataField marketData in tempDepthMarketDataFieldList) { if (marketData.SettlementPrice <= 0d || marketData.SettlementPrice == double.MaxValue) { continue; } if (instrumentDic.ContainsKey(marketData.InstrumentID)) { //[hanyu]未防返回的MarketData没有ExchangeID,改用查询回来的合约交易所信息 USeMarket market = instrumentDic[marketData.InstrumentID].Instrument.Market; SaveInstumentsSettlementPriceToDB(marketData, marketData.InstrumentID, market, tradingDate, marketData.SettlementPrice); //保存完一笔的同时刷新一次资金沉淀[暂时不在这里处理,改用直接在特定时间执行SQL语句,因为涉及到8888指数和9999主力合约也需要刷新资金沉淀的问题] //RefreashSendimentaryMoney(marketData, marketData.InstrumentID, market, tradingDate,marketData.SettlementPrice); instrumentDic.Remove(marketData.InstrumentID); USeConsole.WriteLine(string.Format("保存{0}成功", marketData.InstrumentID)); } } if (instrumentDic.Count <= 0) { //所有合约存储完毕,退出 break; } queryNum--; if (queryNum > 0) { Thread.Sleep(m_queryFrequence); } } catch (Exception ex) { text = string.Format("查询,保存当日结算价异常:{0}", ex.Message); WriteConsoleLog(text); m_eventLogger.WriteInformation(text); ctpApp.Disconnect(); return(-1); } } } else { try { List <DepthMarketDataField> tempDepthMarketDataFieldList = ctpApp.QueryDepthMarketData(); Debug.Assert(tempDepthMarketDataFieldList != null); foreach (DepthMarketDataField marketData in tempDepthMarketDataFieldList) { if (marketData.PreSettlementPrice <= 0d || marketData.PreSettlementPrice == double.MaxValue) { continue; } if (instrumentDic.ContainsKey(marketData.InstrumentID)) { //[hanyu]未防返回的MarketData没有ExchangeID,改用查询回来的合约交易所信息 USeMarket market = instrumentDic[marketData.InstrumentID].Instrument.Market; //保存结算价 SaveInstumentsSettlementPriceToDB(marketData, marketData.InstrumentID, market, tradingDate, marketData.PreSettlementPrice); //RefreashSendimentaryMoney(marketData, marketData.InstrumentID, market, tradingDate,marketData.PreSettlementPrice); instrumentDic.Remove(marketData.InstrumentID); USeConsole.WriteLine(string.Format("保存{0}成功", marketData.InstrumentID)); } } } catch (Exception ex) { text = string.Format("保存昨日结算价异常:{0}", ex.Message); WriteConsoleLog(text); m_eventLogger.WriteInformation(text); ctpApp.Disconnect(); return(-1); } } if (ctpApp != null) { ctpApp.Disconnect(); } if (instrumentDic.Count > 0) { //未查询到的合约写入文件 foreach (USeInstrumentDetail field in instrumentDic.Values) { text = string.Format("[{0}]结算价查询失败", field.Instrument.InstrumentCode); WriteConsoleLog(text); m_eventLogger.WriteInformation(text); } } else { try { #if DEBUG bool iDownLoadResult = VerifyDBSettlementPrice(tradingDate); Debug.Assert(iDownLoadResult == true); #endif RefreshDBSettlementDownLoad(tradingDate, true); } catch (Exception ex) { text = string.Format("更新结算状态失败,错误:{0}", ex.Message); WriteConsoleLog(text); m_eventLogger.WriteInformation(text); } } return(0); }
/// <summary> /// 运行。 /// </summary> public int Start() { try { m_serverLogger = AppLogger.InitInstance(); } catch (Exception ex) { throw new ApplicationException("Initialize applogger failed," + ex.Message); } m_serverLogger.LineFeed(); string message = string.Empty; TradingDaySection config = ConfigurationManager.GetSection("TradingDayManager") as TradingDaySection; if (config == null) { message = "Not found [TradingDayManager] config."; WriteConsoleLog(message); m_serverLogger.WriteError(message); return(-1); } try { m_dbConn = ConfigurationManager.ConnectionStrings["KLineDB"].ConnectionString; if (string.IsNullOrEmpty(m_dbConn)) { throw new ApplicationException("KLineDB connection string is null"); } } catch (Exception ex) { message = "Read db connection string failed," + ex.Message; WriteConsoleLog(message); m_serverLogger.WriteError(message); return(-1); } message = "Begin process trading day."; WriteConsoleLog(message); m_serverLogger.WriteInformation(message); DateTime startDate; DateTime endDate; startDate = config.BeginDay; endDate = config.EndDay; List <string> commands = new List <string>(); DateTime currDate = startDate; List <TradeCalendar> calendarList = new List <TradeCalendar>(); while (currDate <= endDate) { bool isTradingDay = false; switch (currDate.DayOfWeek) { case DayOfWeek.Monday: case DayOfWeek.Tuesday: case DayOfWeek.Wednesday: case DayOfWeek.Thursday: case DayOfWeek.Friday: isTradingDay = !IsHoliday(config, currDate); break; default: isTradingDay = false; break; } TradeCalendar calendar = new TradeCalendar() { Today = currDate, IsTradeDay = isTradingDay, PreTradeDay = DateTime.MinValue, NextTradeDay = DateTime.MinValue }; calendarList.Add(calendar); currDate = currDate.AddDays(1); } for (int i = 0; i < calendarList.Count; i++) { TradeCalendar calendar = calendarList[i]; //补前一交易日 for (int j = i - 1; j >= 0; j--) { if (calendarList[j].IsTradeDay) { calendar.PreTradeDay = calendarList[j].Today; break; } } if (calendar.PreTradeDay == DateTime.MinValue) { calendar.PreTradeDay = config.BeginDayPreTradeDay; } //补下一交易日 for (int j = i + 1; j < calendarList.Count; j++) { if (calendarList[j].IsTradeDay) { calendar.NextTradeDay = calendarList[j].Today; break; } } if (calendar.NextTradeDay == DateTime.MinValue) { calendar.NextTradeDay = config.EndDayNextTradeDay; } } try { SaveToMySqlDB(calendarList, config.BeginDay, config.EndDay); } catch (Exception ex) { message = string.Format("Save data to db failed,Error:{0}.", ex.Message); WriteConsoleLog(message); m_serverLogger.WriteError(message); return(-2); } message = "End process trading day."; WriteConsoleLog(message); m_serverLogger.WriteInformation(message); return(0); }
/// <summary> /// 启动结算价下载。 /// </summary> public int Start() { try { m_eventLogger = AppLogger.InitInstance(); } catch { m_eventLogger = new NullLogger("DownloadProcessor_DefaultLogger"); } m_eventLogger.LineFeed(); string text = "启动下载合约服务"; m_eventLogger.WriteInformation(text); WriteConsoleLog(text); if (ReadConfig() == false) { return(-1); } CtpOrderQuerier ctpApp = new CtpOrderQuerier(); try { ctpApp.Connect(m_ctpDriverConfig.Address, m_ctpDriverConfig.Port, m_ctpDriverConfig.LoginTimeOut, m_ctpDriverConfig.QueryTimeOut); text = "连接CTP交易服务器成功"; WriteConsoleLog(text); m_eventLogger.WriteInformation(text); } catch (Exception ex) { text = "连接CTP交易服务器失败," + ex.Message; WriteConsoleLog(text); m_eventLogger.WriteError(text); return(-1); } try { ctpApp.Login(m_ctpAccountConfig.ID, m_ctpAccountConfig.Password, m_ctpAccountConfig.BrokerID); text = "登陆CTP交易服务器成功"; WriteConsoleLog(text); m_eventLogger.WriteInformation(text); } catch (Exception ex) { text = "登陆CTP交易服务器失败," + ex.Message; WriteConsoleLog(text); m_eventLogger.WriteError(text); return(-1); } List <USeInstrumentDetail> entityList = new List <USeInstrumentDetail>(); try { List <InstrumentField> instrumentList = ctpApp.QueryInstument(); foreach (InstrumentField item in instrumentList) { if (item.ProductClass != ProductClass.Futures) { continue; } try { USeInstrumentDetail entity = InsturmentFiledToUSeInstrumentDetail(item); entityList.Add(entity); } catch (Exception eee) { Debug.Assert(false, eee.Message); } } text = string.Format("查询期货合约数据完成,共计{0}个合约", entityList.Count); WriteConsoleLog(text); m_eventLogger.WriteInformation(text); ctpApp.Disconnect(); } catch (Exception ex) { text = "查询期货合约数据失败," + ex.Message; WriteConsoleLog(text); m_eventLogger.WriteError(text); ctpApp.Disconnect(); return(-1); } try { SaveInstumentsToDB(entityList); text = string.Format("保存期货合约信息完成,共计{0}个合约", entityList.Count); WriteConsoleLog(text); m_eventLogger.WriteInformation(text); } catch (Exception ex) { text = "保存期货合约信息失败," + ex.Message; WriteConsoleLog(text); m_eventLogger.WriteError(text); return(-1); } return(0); }
/// <summary> /// 启动午盘休盘价下载。 /// </summary> public int Start() { try { m_eventLogger = AppLogger.InitInstance(); } catch { m_eventLogger = new NullLogger("DownloadProcessor_DefaultLogger"); } m_eventLogger.LineFeed(); string text = "开始下载午盘收盘价服务"; m_eventLogger.WriteInformation(text); USeConsole.WriteLine(text); if (ReadConfig() == false) { return(-1); } CtpOrderQuerier ctpApp = new CtpOrderQuerier(); try { ctpApp.Connect(m_ctpDriverConfig.Address, m_ctpDriverConfig.Port, m_ctpDriverConfig.LoginTimeOut, m_ctpDriverConfig.QueryTimeOut); text = "连接CTP交易服务器成功"; USeConsole.WriteLine(text); m_eventLogger.WriteInformation(text); } catch (Exception ex) { text = "连接CTP交易服务器失败," + ex.Message; USeConsole.WriteLine(text); m_eventLogger.WriteError(text); ctpApp.Disconnect(); return(-1); } try { ctpApp.Login(m_ctpAccountConfig.ID, m_ctpAccountConfig.Password, m_ctpAccountConfig.BrokerID); text = "登陆CTP交易服务器成功"; USeConsole.WriteLine(text); m_eventLogger.WriteInformation(text); } catch (Exception ex) { text = "登陆CTP交易服务器失败," + ex.Message; USeConsole.WriteLine(text); m_eventLogger.WriteError(text); ctpApp.Disconnect(); return(-1); } try { List <InstrumentField> instrumentList = ctpApp.QueryInstument(); foreach (InstrumentField item in instrumentList) { if (item.ProductClass != ProductClass.Futures) { continue; } USeInstrumentDetail entity = InsturmentFiledToUSeInstrumentDetail(item); instrumentDic.Add(entity.Instrument.InstrumentCode, entity); } text = string.Format("查询期货合约数据完成,共计{0}个合约", instrumentDic.Count); USeConsole.WriteLine(text); m_eventLogger.WriteInformation(text); } catch (Exception ex) { text = "查询期货合约数据失败," + ex.Message; USeConsole.WriteLine(text); m_eventLogger.WriteError(text); ctpApp.Disconnect(); return(-1); } List <DepthMarketDataField> depthMarketDataFieldList = new List <DepthMarketDataField>(); depthMarketDataFieldList = ctpApp.QueryDepthMarketData(); //while (true) //{ // depthMarketDataFieldList = ctpApp.QueryDepthMarketData(); // //返回大于下午开盘的行情时间 // if (VerfiyIsNoonBeginTime(depthMarketDataFieldList) == true) // { // text = string.Format("[{0}]行情已经进入下午开盘时间不在午盘时间内", DateTime.Now); // USeConsole.WriteLine(text); // m_eventLogger.WriteError(text); // ctpApp.Disconnect(); // return -1; // } // //未找到大于11:30:00。 // if (VerfiyIsNoonEndTime(depthMarketDataFieldList) == false) // { // Thread.Sleep(m_queryFrequence); // continue; // } // else // { // break; // } //} ctpApp.Disconnect(); try { foreach (DepthMarketDataField marketData in depthMarketDataFieldList) { if (instrumentDic.ContainsKey(marketData.InstrumentID)) { USeMarket market = instrumentDic[marketData.InstrumentID].Instrument.Market; //保存收盘价 SaveClosePriceToDB(marketData, marketData.InstrumentID, market, DateTime.Today, marketData.LastPrice); instrumentDic.Remove(marketData.InstrumentID); USeConsole.WriteLine(string.Format("保存{0}成功", marketData.InstrumentID)); } } RefrashPriceCloseDownLoad(DateTime.Today, 1); } catch (Exception ex) { text = string.Format("查询,保存当日午盘数据异常:{0}", ex.Message); USeConsole.WriteLine(text); m_eventLogger.WriteInformation(text); return(-1); } return(0); }
/// <summary> /// 开始启动 /// </summary> public int Start() { //获取配置文件 { try { if (false == ReadConfig()) { return(-1); } } catch (Exception ex) { string info = "基础数据:配置文件加载失败" + ex.Message; m_eventLogger.WriteInformation(info); WriteConsoleLog(info); return(-1); } } //加载交易日历 try { TradeCalendarManager tradeCalendarManager = new TradeCalendarManager(m_dbConnStr, m_alphaDBName); tradeCalendarManager.Initialize(DateTime.Today.AddDays(-150), DateTime.Today); m_tradeCalendarManager = tradeCalendarManager; } catch (Exception ex) { throw new ArgumentException("初始化交易日历失败," + ex.Message); } //加载log日志 { try { m_eventLogger = AppLogger.InitInstance(); } catch { m_eventLogger = new NullLogger("DownloadProcessor_DefaultLogger"); } m_eventLogger.LineFeed(); string text = "开始用结算价更新资金沉淀任务服务"; m_eventLogger.WriteInformation(text); WriteConsoleLog(text); } //获取合约列表详情 { try { m_insDetailList = GetInsDetailList(); } catch (Exception ex) { string info = "基础数据:获取合约详情列表失败" + ex.Message; m_eventLogger.WriteInformation(info); WriteConsoleLog(info); return(-1); } } { try { List <USeKLine> klineList = GetTodayDayKlineList(DateTime.Today.AddDays(-20)); RefreashSendimentaryMoney(klineList); } catch (Exception ex) { string info = "服务:获取当天交易日K线数据,更新资金沉淀失败" + ex.Message; m_eventLogger.WriteInformation(info); WriteConsoleLog(info); return(-1); } } return(0); }