/// <summary> /// 根据股票代码获取新浪最新数据 /// </summary> /// <param name="codes">股票代码列表</param> /// <returns>字符串</returns> public static String getSinaLatestDatasStrByCodes(String codes) { String[] strs = codes.Split(new String[] { "," }, StringSplitOptions.RemoveEmptyEntries); int strLen = strs.Length; List <String> sinaCodes = new List <String>(); List <String> dcCodes = new List <String>(); for (int i = 0; i < strLen; i++) { String postCode = strs[i]; sinaCodes.Add(FCStrEx.convertDBCodeToSinaCode(postCode)); } String requestCode = ""; int sinaCodesSize = sinaCodes.Count; for (int i = 0; i < sinaCodesSize; i++) { String postCode = sinaCodes[i]; requestCode += postCode; if (i != strLen - 1) { requestCode += ","; } } String result = ""; if (sinaCodesSize > 0) { String url = "http://hq.sinajs.cn/list=" + requestCode.ToLower(); result = FCHttpGetService.get(url); } return(result); }
/// <summary> /// 获取目录 /// </summary> /// <returns>目录</returns> public String getDirectory() { String fileName = FCStrEx.convertDBCodeToFileName(m_code); String dir = DataCenter.getDataPath() + "\\" + m_identifier; dir += "\\" + fileName.Replace(".txt", ""); return(dir); }
/// <summary> /// 获取通达信的历史数据的字符串 /// </summary> /// <param name="code">股票代码</param> /// <param name="path">本地文件路径</param> /// <returns>数据字符串</returns> public static String getTdxHistoryDatasStrByCode(String code, String path) { String fileName = FCStrEx.convertDBCodeToFileName(code); String result = ""; String filePath = path + fileName; if (FCFile.isFileExist(filePath)) { FCFile.read(filePath, ref result); } return(result); }
/// <summary> /// 更新会话 /// </summary> /// <param name="cookie">会话</param> /// <returns>状态</returns> public int updateCookie(UserCookie cookie) { String sql = String.Format("UPDATE USERCOOKIE SET VALUE = '{0}' WHERE USERID = {1} AND KEY = '{2}'", FCStrEx.getDBString(cookie.m_value), m_userID, FCStrEx.getDBString(cookie.m_key)); SQLiteConnection conn = new SQLiteConnection(m_connectStr); SQLiteCommand cmd = conn.CreateCommand(); cmd.CommandText = sql; conn.Open(); cmd.ExecuteNonQuery(); conn.Close(); return(1); }
/// <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> /// 添加用户Cookie /// </summary> /// <param name="cookie">消息</param> /// <returns>状态</returns> public int addCookie(UserCookie cookie) { UserCookie oldCookie = new UserCookie(); if (getCookie(cookie.m_key, ref oldCookie) > 0) { updateCookie(cookie); } else { String sql = String.Format("INSERT INTO USERCOOKIE(USERID, KEY, VALUE, MODIFYTIME, CREATETIME) values ({0}, '{1}', '{2}','1970-1-1','1970-1-1')", m_userID, FCStrEx.getDBString(cookie.m_key), FCStrEx.getDBString(cookie.m_value)); SQLiteConnection conn = new SQLiteConnection(m_connectStr); conn.Open(); SQLiteCommand cmd = conn.CreateCommand(); cmd.CommandText = sql; cmd.ExecuteNonQuery(); conn.Close(); } return(1); }
/// <summary> /// 加载历史数据 /// </summary> /// <param name="history"></param> public static void loadHistoryDatas() { if (m_historyDatas.Count > 0) { return; } foreach (String code in m_codedMap.Keys) { String fileName = DataCenter.getAppPath() + "\\day\\" + FCStrEx.convertDBCodeToSinaCode(code).ToUpper() + ".txt"; if (File.Exists(fileName)) { StreamReader sra = new StreamReader(fileName, Encoding.Default); String text = sra.ReadToEnd(); List <SecurityData> datas = new List <SecurityData>(); StockService.getHistoryDatasByTdxStr(text, datas); if (datas.Count > 0) { m_historyDatas[code] = datas; } } } }
/// <summary> /// 平仓 /// </summary> /// <param name="investorPosition">持仓</param> /// <param name="code">代码</param> /// <param name="direction">方向</param> /// <param name="close">最新价</param> /// <param name="openPrice">开仓价</param> /// <param name="state">state=0为手动平仓,其余为自动</param> public static void askOrBidClose(InvestorPosition investorPosition, String code, String direction, double close, double openPrice, int state) { //如果持仓为0,则不检查 if (investorPosition.m_position == 0) { return; } //获取对应的行情数据 SecurityLatestData latestData = null; lock (m_latestDatas) { if (m_latestDatas.ContainsKey(code)) { latestData = m_latestDatas[code]; } } if (latestData != null) { //获取的码表 Security security = null; lock (m_securities) { if (m_securities.ContainsKey(investorPosition.m_code)) { security = m_securities[investorPosition.m_code]; } } if (security != null) { bool canTrade = true; //检查冷却时间,一次平仓10秒后才能再次平仓 if (state != 0) { lock (m_cd2) { if (m_cd2.ContainsKey(investorPosition.m_code)) { if (m_cd2[investorPosition.m_code] > 0) { canTrade = false; } } } } //获取昨仓 int ydPosition = investorPosition.m_ydPosition; //获取今仓 int todayPosition = investorPosition.m_position - ydPosition; if (canTrade) { bool isSh = security.m_exchangeID == "SHFE"; //买开仓情况下 if (direction == "买") { //上期所处理方法 if (isSh) { //平昨 if (ydPosition > 0) { CTPDLL.askClose(m_ctpID, CTPDLL.generateReqID(m_ctpID), investorPosition.m_code, security.m_exchangeID, 0, ydPosition, '3', ""); } //平今 if (todayPosition > 0) { CTPDLL.askCloseToday(m_ctpID, CTPDLL.generateReqID(m_ctpID), investorPosition.m_code, security.m_exchangeID, 0, todayPosition, '3', ""); } } //其他交易所处理方法 else { CTPDLL.askClose(m_ctpID, CTPDLL.generateReqID(m_ctpID), investorPosition.m_code, security.m_exchangeID, 0, investorPosition.m_position, '3', ""); } //打印日志 if (state == 1) { FCStrEx.writeLog(String.Format("自动止盈,开仓价{0},当前价{1},买平仓,代码{2},价格{3},数量{4}\r\n", openPrice, close, investorPosition.m_code, latestData.m_bidPrice1, investorPosition.m_position)); } else if (state == 2) { FCStrEx.writeLog(String.Format("自动止损,开仓价{0},当前价{1},买平仓,代码{2},价格{3},数量{4}\r\n", openPrice, close, investorPosition.m_code, latestData.m_bidPrice1, investorPosition.m_position)); } //开仓冷却时间+10 lock (m_cd1) { if (m_cd1.ContainsKey(investorPosition.m_code)) { m_cd1[investorPosition.m_code] += 10; } else { m_cd1[investorPosition.m_code] = 10; } } //平仓冷却时间重置 lock (m_cd2) { m_cd2[investorPosition.m_code] = 10; } } //卖开仓情况下 else if (direction == "卖") { //上期所处理方法 if (isSh) { //平昨 if (ydPosition > 0) { CTPDLL.bidClose(m_ctpID, CTPDLL.generateReqID(m_ctpID), investorPosition.m_code, security.m_exchangeID, 0, ydPosition, '3', ""); } //平今 if (todayPosition > 0) { CTPDLL.bidCloseToday(m_ctpID, CTPDLL.generateReqID(m_ctpID), investorPosition.m_code, security.m_exchangeID, 0, todayPosition, '3', ""); } } //其他交易所处理方法 else { CTPDLL.bidClose(m_ctpID, CTPDLL.generateReqID(m_ctpID), investorPosition.m_code, security.m_exchangeID, 0, investorPosition.m_position, '3', ""); } //打印日志 if (state == 1) { FCStrEx.writeLog(String.Format("自动止盈,开仓价{0},当前价{1},卖平仓,代码{2},价格{3},数量{4}\r\n", openPrice, close, investorPosition.m_code, latestData.m_bidPrice1, investorPosition.m_position)); } else if (state == 2) { FCStrEx.writeLog(String.Format("自动止损,开仓价{0},当前价{1},卖平仓,代码{2},价格{3},数量{4}\r\n", openPrice, close, investorPosition.m_code, latestData.m_bidPrice1, investorPosition.m_position)); } //开仓冷却时间+10 lock (m_cd1) { if (m_cd1.ContainsKey(investorPosition.m_code)) { m_cd1[investorPosition.m_code] += 10; } else { m_cd1[investorPosition.m_code] = 10; } } //平仓冷却时间重置 lock (m_cd2) { m_cd2[investorPosition.m_code] = 10; } } } } } }
/// <summary> /// 触发开仓 /// </summary> /// <param name="data">最新数据</param> public static void doOpen(SecurityLatestData data) { //执行买开仓 if (data.m_state1 == 1 && data.m_state2 == 1) { //判断是否有持仓 bool hasTrade = inTrade(data.m_code); if (!hasTrade) { String key = data.m_code + "买"; //判断冷却时间 bool canTrade = true; lock (Strategy1.m_cd1) { if (Strategy1.m_cd1.ContainsKey(data.m_code)) { if (Strategy1.m_cd1[data.m_code] > 0) { canTrade = false; } } } if (canTrade) { //获取默认交易手数 int tradeVol = 1; if (m_tradeVolumes.ContainsKey(key)) { tradeVol = m_tradeVolumes[key]; } //打印日志 FCStrEx.writeLog(String.Format("创近20日新高,均线上翘,买开仓,代码{0},价格{1},数量{2}\r\n", data.m_code, data.m_askPrice1, tradeVol)); Security security = null; lock (m_securities) { if (m_securities.ContainsKey(data.m_code)) { security = m_securities[data.m_code]; } } //买开仓 CTPDLL.bidOpen(Strategy1.m_ctpID, CTPDLL.generateReqID(Strategy1.m_ctpID), data.m_code, security.m_exchangeID, data.m_askPrice1, tradeVol, '3', ""); //刷新开仓冷却时间 lock (Strategy1.m_cd1) { Strategy1.m_cd1[data.m_code] = 60; } } } } //执行卖开仓 if (data.m_state3 == 1 && data.m_state4 == 1) { //判断是否有持仓 bool hasTrade = inTrade(data.m_code); if (!hasTrade) { String key = data.m_code + "卖"; //判断冷却时间 bool canTrade = true; lock (Strategy1.m_cd1) { if (Strategy1.m_cd1.ContainsKey(data.m_code)) { if (Strategy1.m_cd1[data.m_code] > 0) { canTrade = false; } } } if (canTrade) { //获取默认交易手数 int tradeVol = 1; if (m_tradeVolumes.ContainsKey(key)) { tradeVol = m_tradeVolumes[key]; } //打印日志 FCStrEx.writeLog(String.Format("创近20日新低,均线下翘,卖开仓,代码{0},价格{1},数量{2}\r\n", data.m_code, data.m_askPrice1, tradeVol)); Security security = null; lock (m_securities) { if (m_securities.ContainsKey(data.m_code)) { security = m_securities[data.m_code]; } } //卖开仓 CTPDLL.askOpen(Strategy1.m_ctpID, CTPDLL.generateReqID(Strategy1.m_ctpID), data.m_code, security.m_exchangeID, data.m_bidPrice1, tradeVol, '3', ""); //刷新开仓冷却时间 lock (Strategy1.m_cd1) { Strategy1.m_cd1[data.m_code] = 60; } } } } }
/// <summary> /// 根据字符串获取新浪的最新数据 /// </summary> /// <param name="str">数据字符串</param> /// <param name="formatType">格式</param> /// <param name="data">最新数据</param> /// <returns>状态</returns> public static int getLatestDataBySinaStr(String str, int formatType, ref SecurityLatestData data) { //分析数据 String date = ""; String[] strs2 = str.Split(new String[] { "," }, StringSplitOptions.RemoveEmptyEntries); int strLen2 = strs2.Length; bool szIndex = false; for (int j = 0; j < strLen2; j++) { String str2 = strs2[j]; switch (j) { case 0: data.m_code = FCStrEx.convertSinaCodeToDBCode(str2); if (data.m_code.StartsWith("399")) { szIndex = true; } break; case 1: { data.m_open = FCStr.convertStrToDouble(str2); break; } case 2: { data.m_lastClose = FCStr.convertStrToDouble(str2); break; } case 3: { data.m_close = FCStr.convertStrToDouble(str2); break; } case 4: { data.m_high = FCStr.convertStrToDouble(str2); break; } case 5: { data.m_low = FCStr.convertStrToDouble(str2); break; } case 8: { data.m_volume = FCStr.convertStrToDouble(str2); if (szIndex) { data.m_volume /= 100; } break; } case 9: { data.m_amount = FCStr.convertStrToDouble(str2); break; } case 10: { if (formatType == 0) { data.m_buyVolume1 = (int)FCStr.convertStrToDouble(str2); } break; } case 11: { if (formatType == 0) { data.m_buyPrice1 = FCStr.convertStrToDouble(str2); } break; } case 12: { if (formatType == 0) { data.m_buyVolume2 = (int)FCStr.convertStrToDouble(str2); } break; } case 13: { if (formatType == 0) { data.m_buyPrice2 = FCStr.convertStrToDouble(str2); } break; } case 14: { if (formatType == 0) { data.m_buyVolume3 = (int)FCStr.convertStrToDouble(str2); } break; } case 15: { if (formatType == 0) { data.m_buyPrice3 = FCStr.convertStrToDouble(str2); } break; } case 16: { if (formatType == 0) { data.m_buyVolume4 = (int)FCStr.convertStrToDouble(str2); } break; } case 17: { if (formatType == 0) { data.m_buyPrice4 = FCStr.convertStrToDouble(str2); } break; } case 18: { if (formatType == 0) { data.m_buyVolume5 = (int)FCStr.convertStrToDouble(str2); } break; } case 19: { if (formatType == 0) { data.m_buyPrice5 = FCStr.convertStrToDouble(str2); } break; } case 20: { if (formatType == 0) { data.m_sellVolume1 = (int)FCStr.convertStrToDouble(str2); } break; } case 21: { if (formatType == 0) { data.m_sellPrice1 = FCStr.convertStrToDouble(str2); } break; } case 22: { if (formatType == 0) { data.m_sellVolume2 = (int)FCStr.convertStrToDouble(str2); } break; } case 23: { if (formatType == 0) { data.m_sellPrice2 = FCStr.convertStrToDouble(str2); } break; } case 24: { if (formatType == 0) { data.m_sellVolume3 = (int)FCStr.convertStrToDouble(str2); } break; } case 25: { if (formatType == 0) { data.m_sellPrice3 = FCStr.convertStrToDouble(str2); } break; } case 26: { if (formatType == 0) { data.m_sellVolume4 = (int)FCStr.convertStrToDouble(str2); } break; } case 27: { if (formatType == 0) { data.m_sellPrice4 = FCStr.convertStrToDouble(str2); } break; } case 28: { if (formatType == 0) { data.m_sellVolume5 = (int)FCStr.convertStrToDouble(str2); } break; } case 29: { if (formatType == 0) { data.m_sellPrice5 = FCStr.convertStrToDouble(str2); } break; } case 30: date = str2; break; case 31: date += " " + str2; break; } } //获取时间 if (date != null && date.Length > 0) { DateTime dateTime = Convert.ToDateTime(date); data.m_date = FCStr.getDateNum(dateTime.Year, dateTime.Month, dateTime.Day, dateTime.Hour, dateTime.Minute, dateTime.Second, 0); } //价格修正 if (data.m_close != 0) { if (data.m_open == 0) { data.m_open = data.m_close; } if (data.m_high == 0) { data.m_high = data.m_close; } if (data.m_low == 0) { data.m_low = data.m_close; } } return(0); }
/// <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> /// 获取用户Cookie /// </summary> /// <param name="key">键</param> /// <param name="cookie">会话</param> /// <returns>状态</returns> public int getCookie(String key, ref UserCookie cookie) { int state = 0; String sql = String.Format("SELECT * FROM USERCOOKIE WHERE USERID = {0} AND KEY = '{1}'", m_userID, FCStrEx.getDBString(key)); SQLiteConnection conn = new SQLiteConnection(m_connectStr); SQLiteCommand cmd = conn.CreateCommand(); cmd.CommandText = sql; conn.Open(); SQLiteDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { cookie.m_userID = reader.GetInt32(0); cookie.m_key = reader.GetString(1); cookie.m_value = reader.GetString(2); state = 1; } reader.Close(); conn.Close(); return(state); }
/// <summary> /// 删除用户Cookie /// </summary> /// <param name="key">键</param> /// <returns>状态</returns> public int deleteCookie(String key) { String sql = String.Format("DELETE FROM USERCOOKIE WHERE USERID = {0} AND KEY = '{1}'", m_userID, FCStrEx.getDBString(key)); SQLiteConnection conn = new SQLiteConnection(m_connectStr); SQLiteCommand cmd = conn.CreateCommand(); cmd.CommandText = sql; conn.Open(); cmd.ExecuteNonQuery(); conn.Close(); return(1); }