/** * 向文件中追加内容 * * @param logFile * 日志文件的名称 * @param content * 内容 * @return 是否成功 */ protected virtual bool append(String logFile, String content) { try { if (logFile == null || logFile.Length == 0) { return(false); } FCFile.append(logFile, content); return(true); } catch (Exception e) { return(false); } }
/** * 向文件中追加内容 */ protected override bool append(String logFile, String content) { try { if (logFile == null || logFile.Length == 0) { return(false); } adjustFileBeforeAppend(logFile); FCFile.append(logFile, content); return(true); } catch (Exception e) { return(false); } }
/// <summary> /// 文件放下方法 /// </summary> /// <param name="e">参数</param> protected override void OnDragDrop(DragEventArgs e) { base.OnDragDrop(e); StringBuilder filesName = new StringBuilder(""); Array files = (System.Array)e.Data.GetData(DataFormats.FileDrop);//将拖来的数据转化为数组存储 foreach (object i in files) { String str = i.ToString(); if (FCFile.isFileExist(str)) { m_designer.openFile(str); } } }
/// <summary> /// 创建用户状态服务 /// </summary> public UserCookieService() { String dataDir = DataCenter.GetUserPath() + "\\data"; if (!FCFile.isDirectoryExist(dataDir)) { FCFile.createDirectory(dataDir); } String dataBasePath = DataCenter.GetUserPath() + "\\data\\usercookies.db"; m_connectStr = "Data Source = " + dataBasePath; if (!FCFile.isFileExist(dataBasePath)) { CreateTable(); } }
/// <summary> /// 启动监听 /// </summary> public void start() { m_useScript = FCFile.isFileExist(m_fileName); if (m_useScript) { m_native = new FCNative(); FCFile.read(m_fileName, ref m_script); m_indicator = CFunctionEx.CreateScript(m_script, m_native); Console.WriteLine(m_script); } try { //string host = "127.0.0.1"; //IPAddress ip = IPAddress.Parse(host); if (m_indicator != null) { m_indicator.callFunction("ONHTTPSERVERSTARTING('" + m_fileName + "');"); } IPEndPoint ipe = new IPEndPoint(IPAddress.Any, m_port); m_listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); m_listener.Bind(ipe); m_listener.Listen(0); } catch (Exception ex) { if (m_indicator != null) { m_indicator.callFunction("ONHTTPSERVERSTARTFAIL('" + ex.Message + "\r\n" + ex.StackTrace + "');"); } return; } int minThreadNum = 0, portThreadNum = 0, maxThreadNum = 0; ThreadPool.GetMaxThreads(out maxThreadNum, out portThreadNum); ThreadPool.GetMinThreads(out minThreadNum, out portThreadNum); if (m_indicator != null) { m_indicator.callFunction("ONHTTPSERVERSTART(" + FCStr.convertIntToStr(maxThreadNum) + "," + FCStr.convertIntToStr(minThreadNum) + ");"); } while (true) { Socket socket = m_listener.Accept(); ThreadPool.QueueUserWorkItem(new WaitCallback(readData), socket); } m_listener.Close(); }
/// <summary> /// 用户数据存储路径 /// </summary> /// <returns>程序路径</returns> public static String GetUserPath() { String userPath = Environment.GetEnvironmentVariable("LOCALAPPDATA"); if (!FCFile.isDirectoryExist(userPath)) { userPath = GetAppPath(); } else { userPath += "\\idesigner"; if (!FCFile.isDirectoryExist(userPath)) { FCFile.createDirectory(userPath); } } return(userPath); }
/// <summary> /// 获取分时数据 /// </summary> public static void getMinuteDatas() { if (m_minuteDatas.Count > 0) { return; } String appPath = DataCenter.getAppPath(); foreach (String code in m_codedMap.Keys) { String fileName = m_newFileDir + FCStrEx.convertDBCodeToFileName(code); if (!FCFile.isFileExist(fileName)) { fileName = m_newFileDir + FCStrEx.convertDBCodeToSinaCode(code).ToUpper() + ".txt"; } if (FCFile.isFileExist(fileName)) { String text = ""; FCFile.read(fileName, ref text); List <SecurityData> datas = new List <SecurityData>(); StockService.getHistoryDatasByMinuteStr(text, datas); if (datas.Count > 0) { int rindex = 0; int dataSize = datas.Count; while (rindex < dataSize) { SecurityData d = datas[rindex]; if (rindex == 0) { d.m_avgPrice = d.m_close; } else { SecurityData ld = datas[rindex - 1]; d.m_avgPrice = (ld.m_avgPrice * rindex + d.m_close) / (rindex + 1); } rindex++; } m_minuteDatas[code] = datas; } } } }
/// <summary> /// 获取或设置是否需要创建表 /// </summary> public void CreateTable() { String dataBasePath = DataCenter.GetUserPath() + "\\data\\" + DATABASENAME; if (!FCFile.isFileExist(dataBasePath)) { //创建数据库文件 SQLiteConnection.CreateFile(dataBasePath); } //创建表 SQLiteConnection conn = new SQLiteConnection(m_connectStr); conn.Open(); SQLiteCommand cmd = conn.CreateCommand(); cmd.CommandText = CREATETABLESQL; cmd.ExecuteNonQuery(); conn.Close(); }
/// <summary> /// 登录 /// </summary> /// <param name="sender">调用者</param> /// <param name="e">参数</param> private void btnLogin_Click(object sender, EventArgs e) { //收集信息 String mdServer = txtMDServer.Text.Trim(); String tdServer = txtTDServer.Text.Trim(); String brokerID = txtBrokerID.Text.Trim(); String investorID = txtInvestorID.Text.Trim(); String password = txtPassword.Text.Trim(); if (mdServer.Length == 0) { MessageBox.Show("请输入行情服务器的地址!"); return; } if (tdServer.Length == 0) { MessageBox.Show("请输入交易服务器的地址!"); return; } if (brokerID.Length == 0) { MessageBox.Show("请输入机构ID!"); return; } if (investorID.Length == 0) { MessageBox.Show("请输入投资者账号!"); return; } if (password.Length == 0) { MessageBox.Show("请输入密码!"); return; } String content = String.Format("{0}\r\n{1}\r\n{2}\r\n{3}\r\n{4}", mdServer, tdServer, brokerID, investorID, password); String filePath = Application.StartupPath + "\\LoginInfo.txt"; FCFile.write(filePath, content); //发起登录 m_mainForm.Xml.loginCTP(mdServer, tdServer, brokerID, investorID, password); this.DialogResult = DialogResult.OK; Close(); }
/// <summary> /// 获取证券列表 /// </summary> /// <returns>证券列表</returns> public List <Security> getSecurities() { List <Security> securities = new List <Security>(); String codesStr = ""; FCFile.read(DataCenter.getAppPath() + "\\codes.txt", ref codesStr); String[] strs = codesStr.Split(new String[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries); int strsSize = strs.Length; for (int i = 0; i < strsSize; i++) { String[] subStrs = strs[i].Split(','); Security security = new Security(); security.m_code = subStrs[0]; security.m_name = subStrs[1]; securities.Add(security); } return(securities); }
/// <summary> /// 加载界面方法 /// </summary> protected override void OnLoad(EventArgs e) { base.OnLoad(e); String filePath = Application.StartupPath + "\\LoginInfo.txt"; if (FCFile.isFileExist(filePath)) { String content = ""; FCFile.read(filePath, ref content); if (content.Length > 0) { String[] strs = content.Split(new String[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries); txtMDServer.Text = strs[0]; txtTDServer.Text = strs[1]; txtBrokerID.Text = strs[2]; txtInvestorID.Text = strs[3]; txtPassword.Text = strs[4]; } } }
/// <summary> /// 开始服务 /// </summary> public override void start() { base.start(); String dir = DataCenter.getDataPath() + "\\sinanews"; if (!FCFile.isDirectoryExist(dir)) { FCFile.createDirectory(dir); } List <Security> securities = DataCenter.SecurityService.getSecurities(); int securitiesSize = securities.Count; List <WorkDataInfo> dataInfos = new List <WorkDataInfo>(); for (int i = 0; i < securitiesSize; i++) { SecurityDataInfo dataInfo = new SecurityDataInfo(); dataInfo.m_id = i; dataInfo.m_security = securities[i]; dataInfos.Add(dataInfo); } m_workThread.startWork(dataInfos); }
/// <summary> /// 创建项目 /// </summary> /// <param name="dir">目录</param> private void createProject(String projectName, String dir, String identifier) { ArrayList <String> dirs = new ArrayList <String>(); FCFile.getDirectories(dir, dirs); int dirsSize = dirs.Count; for (int i = 0; i < dirsSize; i++) { createProject(projectName, dirs.get(i), identifier); } ArrayList <String> files = new ArrayList <String>(); FCFile.getFiles(dir, files); int filesSize = files.Count; for (int i = 0; i < filesSize; i++) { String file = files.get(i); String content = ""; if (file.Substring(file.LastIndexOf('\\')).IndexOf(identifier) != -1) { FCFile.read(file, ref content); String newFile = file.Replace(identifier, projectName); FCFile.write(newFile, content); FCFile.removeFile(file); file = newFile; } FCFile.read(file, ref content); if (content.IndexOf(identifier) != -1) { content = content.Replace(identifier, projectName); FCFile.write(file, content); } } dirs.Clear(); files.Clear(); }
/// <summary> /// 检查脚本 /// </summary> public void checkScript() { String newScript = ""; FCFile.read(m_fileName, ref newScript); if (m_script != newScript) { Console.WriteLine("检测到脚本被修改..."); m_script = newScript; lock (m_indicators) { while (true) { try { FCScript indicator = m_indicators.Pop(); indicator.delete(); } catch { break; } } } } }
/// <summary> /// 写日志 /// </summary> /// <param name="log">日志</param> public static void writeLog(String log) { FCFile.append(Application.StartupPath + "\\log.txt", "[" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "]" + log + "\r\n"); }
/// <summary> /// 工作中 /// </summary> /// <param name="dataInfo">信息</param> /// <returns>状态</returns> public override int onWorking(WorkDataInfo dataInfo) { Console.WriteLine(dataInfo.m_id.ToString()); SecurityDataInfo securityDataInfo = dataInfo as SecurityDataInfo; String url = String.Format(m_listUrl, FCStrEx.ConvertDBCodeToSinaCode(securityDataInfo.m_security.m_code)); Log = String.Format("下载:{0}", securityDataInfo.m_security.m_code); String html = DataCenter.getHttpWebRequest(url, "GB2312"); if (html != null && html.Length > 0) { NewsInfo newsInfo = new NewsInfo("sinanews"); newsInfo.m_code = securityDataInfo.m_security.m_code; String dir = newsInfo.getDirectory(); if (!FCFile.isDirectoryExist(dir)) { FCFile.createDirectory(dir); } String identifier = "<div class=\"datelist\">"; int pos = html.IndexOf(identifier); if (pos != -1) { html = html.Substring(pos + identifier.Length); html = html.Substring(0, html.IndexOf("</ul>")); html = html.Replace("<ul>\r\n\t\t\t", "").Replace(" ", " "); String[] strs = html.Split(new String[] { "<br>" }, StringSplitOptions.RemoveEmptyEntries); int strsSize = strs.Length; for (int i = 0; i < strsSize; i++) { try { newsInfo.m_content = ""; String str = strs[i]; String[] subStrs = str.Split(new String[] { "<a target='_blank' href='" }, StringSplitOptions.RemoveEmptyEntries); if (subStrs.Length >= 2) { newsInfo.m_time = subStrs[0].Trim(); String[] sunStrs = subStrs[1].Split(new String[] { "'>" }, StringSplitOptions.RemoveEmptyEntries); newsInfo.m_url = sunStrs[0]; newsInfo.m_title = sunStrs[1].Replace("</a>", ""); String fileName = newsInfo.getFileName(); if (!FCFile.isFileExist(fileName)) { Log = String.Format("下载:{0}", securityDataInfo.m_security.m_code); String contentHtml = DataCenter.getHttpWebRequest(newsInfo.m_url, "UTF-8"); String sIdentifier = "<!-- 原始正文start -->", eIdentifier = "<!-- 原始正文end -->"; int sPos = contentHtml.IndexOf(sIdentifier); if (sPos != -1) { String content = contentHtml.Substring(sPos + sIdentifier.Length); int ePos = content.IndexOf(eIdentifier); newsInfo.m_content = content.Substring(0, ePos); FCFile.write(fileName, newsInfo.ToString()); } } } } catch (Exception ex) { } } } } return(1); }
/// <summary> /// 数据落地线程工作 /// </summary> public static void startWork3() { //复制数据 loadHistoryDatas(); //getMinuteDatas(); //新旧数据合并 foreach (String oCode in m_historyDatas.Keys) { if (!m_latestDatas.ContainsKey(oCode) || !m_historyDatas.ContainsKey(oCode)) { continue; } SecurityLatestData securityLatestData = m_latestDatas[oCode]; List <SecurityData> oldSecurityDatas = m_historyDatas[oCode]; SecurityData oldSecurityData = oldSecurityDatas[oldSecurityDatas.Count - 1]; int myear = 0, mmonth = 0, mday = 0, mhour = 0, mmin = 0, msec = 0, mmsec = 0; FCStr.getDateByNum(oldSecurityData.m_date, ref myear, ref mmonth, ref mday, ref mhour, ref mmin, ref msec, ref mmsec); int year = 0, month = 0, day = 0, hour = 0, min = 0, sec = 0, msec2 = 0; FCStr.getDateByNum(securityLatestData.m_date, ref year, ref month, ref day, ref hour, ref min, ref sec, ref msec2); if (year >= myear && month >= mmonth && day >= mday) { SecurityData nSecurityData = new SecurityData(); nSecurityData.m_amount = securityLatestData.m_amount; nSecurityData.m_close = securityLatestData.m_close; nSecurityData.m_date = securityLatestData.m_date; nSecurityData.m_high = securityLatestData.m_high; nSecurityData.m_low = securityLatestData.m_low; nSecurityData.m_open = securityLatestData.m_open; nSecurityData.m_volume = securityLatestData.m_volume; if (day == mday) { m_historyDatas[oCode].RemoveAt(m_historyDatas[oCode].Count - 1); } m_historyDatas[oCode].Add(nSecurityData); } } String outputFileTemplate = DataCenter.getAppPath() + "\\day\\{0}.txt"; String fileInfo = "{0} {1} 日线 前复权\r\n"; String title = " 日期 开盘 最高 最低 收盘 成交量 成交额\r\n"; String lineTemp = "{0},{1},{2},{3},{4},{5},{6}\r\n"; String timeFormatStr = "yyyy-MM-dd"; //写入文件 foreach (String code in m_historyDatas.Keys) { List <SecurityData> temp3 = m_historyDatas[code]; StringBuilder strbuff = new StringBuilder(); strbuff.Append(String.Format(fileInfo, m_codedMap[code].m_code, m_codedMap[code].m_name)); strbuff.Append(title); foreach (SecurityData sdt in temp3) { strbuff.Append(String.Format(lineTemp, // FCStr.convertNumToDate(sdt.m_date).ToString(timeFormatStr), // sdt.m_open, // sdt.m_high, // sdt.m_low, // sdt.m_close, // sdt.m_volume, // sdt.m_amount)); } strbuff.Append("数据来源:通达信\r\n"); FCFile.write(String.Format(outputFileTemplate, code), strbuff.ToString()); } }
/** * 输出日志 */ public override void log(int logType, String message) { if (checkOut(logType)) { String type = null; if (logType == 1) { type = "Debug"; } else if (logType == 2) { type = "Info"; } else if (logType == 3) { type = "Warn"; } else if (logType == 4) { type = "Error"; } else if (logType == 5) { type = "Fatal"; } //yyyyMMdd String dateTime = getNowDate(m_fileAppenderConfig.m_datePattern); message = String.Format("{0} {1} {2}\r\n", dateTime, type, message); String logFile = m_fileAppenderConfig.m_logFile; if (logFile.Length == 0) { return; } String separator = LogService.FILESEPARATOR; String date = getNowDate("yyyyMMdd"); int np = logFile.LastIndexOf(date); if (np < 0) { String logDir = LogService.getAppPath() + "\\log\\" + date; FCFile.createDirectory(logDir); int pos = logFile.LastIndexOf(separator); String logFileName = logFile.Substring(pos, logFile.Length - pos + 1); String newLogFile = logDir + separator + logFileName; m_fileAppenderConfig.m_logFile = newLogFile; logFile = newLogFile; } if (FCFile.isFileExist(logFile)) { FileInfo file = new FileInfo(logFile); long len = file.Length; if (len >= m_maxFileSize) { String logDir = LogService.getAppPath() + "\\log\\" + date; ArrayList <String> files = new ArrayList <String>(); FCFile.getFiles(logDir, files); int count = files.size(); files.clear(); int pos = logFile.LastIndexOf(separator); int pos2 = logFile.LastIndexOf("."); String logFileName = logFile.Substring(pos, pos2 - 1 - pos + 1); String newFileName = String.Format("{0}\\{1}.{2}.log", logDir, logFileName, count); FileInfo oldFile = new FileInfo(logFile); FileInfo newFile = new FileInfo(newFileName); oldFile.MoveTo(newFile.FullName); } } FCFile.append(logFile, message); } }