private void OnReceivedEx(Connection connection, int hSend, LDFastMessageAdapter lpFastMsg, int result) { if (ConnectionManagerOnReceivedEx != null) { ConnectionManagerOnReceivedEx(connection, hSend, lpFastMsg, result); } }
private void OnPublish(Connection connection, string strTopicName, LDFastMessageAdapter fastMsg) { if (ConnectionManagerOnPublish != null) { ConnectionManagerOnPublish(connection, strTopicName, fastMsg); } }
private void Connect_OnReceivedEx(int hSend, LDFastMessageAdapter lpFastMsg, int result) { if (OnReceivedExCallBack != null) { OnReceivedExCallBack(ConnectionID, hSend, lpFastMsg, result); } }
private void Connect_OnPublish(string strTopicName, LDFastMessageAdapter lpFastMsg) { if (OnPublishCallBack != null) { OnPublishCallBack(ConnectionID, strTopicName, lpFastMsg); } }
/// <summary> /// 发送请求数据包的方法 /// </summary> /// <param name="fastMsg"></param> /// <param name="funcId"></param> /// <returns></returns> private Task SendRequsetPackage(LDFastMessageAdapter fastMsg, string funcId) { Task tsk = Task.Run(() => { sendConnectionAdapter.AsyncSend(funcId, fastMsg, 60000); fastMsg.FreeMsg(); }); return(tsk); }
/// <summary> /// 输出应答数据的结果 /// </summary> /// <param name="lpFastMsg">应答数据包</param> /// <param name="savePath">文件保存路径</param> public static unsafe void OutPutResult(LDFastMessageAdapter lpFastMsg, string savePath) { StringBuilder outPutInfo = new StringBuilder(); outPutInfo.Append("\r\n**************************************************************"); try { if (lpFastMsg.Record != null) { int errorNo = lpFastMsg.GetInt32(LDBizTag.LDBIZ_ERROR_NO_INT); if (errorNo != 0) { return; } //打印包头信息 LDRecordAdapter headRecord = lpFastMsg.GetHeadRecord(); if (headRecord.Record != null) { string tempHeadRecord = ShowRecord(headRecord); outPutInfo.Append(tempHeadRecord); } //打印包体信息 LDGroupAdapter lpGroup = lpFastMsg.GetGroup(1000); if (lpGroup.ld == null) //非结果集 { LDRecordAdapter record = lpFastMsg.GetBizBodyRecord(); if (record.Record != null) { string tempInfo = ShowRecord(record); outPutInfo.Append(tempInfo); } } else //结果集 { int recordCount = lpGroup.GetRecordCount(); outPutInfo.AppendLine($"\r\nrow_count : {recordCount}"); for (int i = 0; i < recordCount; i++) { LDRecordAdapter record = lpGroup.GetRecord(i); if (record.Record != null) { string tempInfo = ShowRecord(record); outPutInfo.Append(tempInfo); } } } CSVFileHelper.AppendSaveScript(savePath, outPutInfo.ToString()); } } catch (Exception error) { outPutInfo.Append($"{error.Message}\r\n{error.StackTrace}"); CSVFileHelper.AppendSaveScript(savePath, outPutInfo.ToString()); } }
private Task <int> SendPackage(LDFastMessageAdapter fastMsg) { int result = -1; Task <int> tsk = Task <int> .Run(new Func <int>(() => { result = sendConnectionAdapter.PubTopics("quote.realtime", fastMsg); return(result); })); return(tsk); }
/// <summary> /// 发送广播数据包的方法 /// </summary> /// <param name="fastMsg"></param> /// <param name="funcId"></param> /// <returns></returns> private Task <int> SendPubTopicsPackage(LDFastMessageAdapter fastMsg, string funcId) { int result = -1; Task <int> tsk = Task <int> .Run(() => { result = sendConnectionAdapter.PubTopics(funcId, fastMsg); fastMsg.FreeMsg(); return(result); }); return(tsk); }
/// <summary> /// 初始化数据包 /// </summary> /// <param name="funcId">功能号</param> /// <param name="fastMsg">需要进行初始化的数据包</param> public static void InitMsg(string funcId, ref LDFastMessageAdapter fastMsg) { fastMsg.SetInt32(LDBizTag.LDBIZ_OPOR_CO_NO_INT, 9999); fastMsg.SetInt32(LDBizTag.LDBIZ_OPOR_NO_INT, 99990001); fastMsg.SetString(LDBizTag.LDBIZ_OPOR_PWD_STR, "ZTI0MTA1ZDRiNmVmNjIxNWViMTA2ZmQ1YzkxMjYyNDM="); fastMsg.SetString(LDBizTag.LDBIZ_OPER_MAC_STR, " "); fastMsg.SetString(LDBizTag.LDBIZ_OPER_IP_ADDR_STR, " "); fastMsg.SetString(LDBizTag.LDBIZ_OPER_INFO_STR, " "); fastMsg.SetString(LDBizTag.LDBIZ_OPER_WAY_STR, "1"); fastMsg.SetInt32(LDBizTag.LDBIZ_MENU_NO_INT, 0); fastMsg.SetString(LDBizTag.LDBIZ_FUNC_CODE_STR, funcId); }
/// <summary> /// 获取应答包内的字段和值的信息 /// </summary> /// <param name="fastmsg">应答数据包</param> /// <param name="filedType">字段类型</param> /// <param name="filedIndex">字段索引</param> /// <returns></returns> public static string GetFastMsgValue(LDFastMessageAdapter fastmsg, int filedType, int filedIndex) { string filedValue = ""; switch (filedType) { case LDSdkTag.TypeInt16: case LDSdkTag.TypeuInt16: case LDSdkTag.TypeInt32: case LDSdkTag.TypeuInt32: Int32 intValue = 0; intValue = (int)fastmsg.GetInt32byIndex(filedIndex); filedValue = intValue.ToString(); break; case LDSdkTag.TypeInt64: case LDSdkTag.TypeuInt64: Int64 longValue = 0; longValue = (Int64)fastmsg.GetInt64byIndex(filedIndex); filedValue = longValue.ToString(); break; case LDSdkTag.TypeDouble: double doubleValue = 0; doubleValue = fastmsg.GetDoublebyIndex(filedIndex); filedValue = doubleValue.ToString(); break; case LDSdkTag.TypeString: case LDSdkTag.TypeVector: filedValue = fastmsg.GetStringbyIndex(filedIndex); break; default: break; } return(filedValue); }
/// <summary> /// 根据字段的FieldId进行构建数据包 /// </summary> /// <param name="fastmsg"></param> /// <param name="filedType"></param> /// <param name="filedValue"></param> /// <param name="filedIndex"></param> public static void SetFastMsgValueById(LDFastMessageAdapter fastmsg, int filedType, string filedValue, int fieldId) { switch (filedType) { case LDSdkTag.TypeInt16: case LDSdkTag.TypeuInt16: case LDSdkTag.TypeInt32: case LDSdkTag.TypeuInt32: Int32 intValue = 0; Int32.TryParse(filedValue, out intValue); //fastmsg.SetInt32byIndex(filedIndex, intValue); fastmsg.SetInt32(fieldId, intValue); break; case LDSdkTag.TypeInt64: case LDSdkTag.TypeuInt64: Int64 longValue = 0; Int64.TryParse(filedValue, out longValue); fastmsg.SetInt64(fieldId, (ulong)longValue); break; case LDSdkTag.TypeDouble: double doubleValue = 0; double.TryParse(filedValue, out doubleValue); fastmsg.SetDouble(fieldId, doubleValue); break; case LDSdkTag.TypeString: case LDSdkTag.TypeVector: if (string.IsNullOrEmpty(filedValue)) { filedValue = " "; } fastmsg.SetString(fieldId, filedValue); break; default: break; } }
/// <summary> /// 接收并处理应答的函数 /// </summary> /// <param name="connection">连接</param> /// <param name="hSend">句柄</param> /// <param name="lpFastMsg">应答包</param> /// <param name="result">结果</param> private void Instance_ConnectionManagerOnReceivedEx(Connection connection, int hSend, LDFastMessageAdapter lpFastMsg, int result) { RespDataPackageModel.DataQueue.Enqueue(new RespDataPackageModel(hSend, lpFastMsg)); }
/// <summary> /// 发送数据并绘制正弦曲线 /// </summary> private async void DrawSin() { try { int Zoom = 15; //放大倍数 Point center = new Point(0, 174); //原点 float x1 = (float)(0 * Math.PI * Zoom / 180 + center.X); float y1 = (float)(Math.Sin(0 * Math.PI / 180) * 11 * Zoom + center.Y); this.Dispatcher.Invoke(() => { //定义绘制的第一个点 pf.StartPoint = center; //加入到PathFigure对象中,true表示描绘线段 pf.Segments.Add(new LineSegment(center, true)); //组合绘制的线段,只要操作一次 pg.Figures.Add(pf); //作为Path对象的数据 pa.Data = pg; //加入Canvas在屏幕显示 this.cvsDraw.Children.Add(pa); }); for (int i = 1; i < 360 * 99; i++) //角 { if (isPause) //是否暂停 { waitHandle.WaitOne(); } if (token.IsCancellationRequested)//是否重置(取消当前线程) { return; } float x2 = (float)(i * Math.PI * Zoom / 180 + center.X); float y2 = (float)(Math.Sin(i * Math.PI / 180) * (-1) * 11 * Zoom + center.Y); this.Dispatcher.Invoke(() => { pf.Segments.Add(new LineSegment(new Point(x2, y2), true)); }); #region 针对每个券码发送一个生成并发送一个数据包还要将行情进行落库 int rows = LoadStockInfo.excelData.Rows.Count;//券码总条数 for (int j = 0; j < (rows < stockCountLimit ? rows : stockCountLimit); j++) { LDFastMessageAdapter fastMsg = new LDFastMessageAdapter("pubL.16.5", 0); //行情包 LDFastMessageAdapter saveMsg = new LDFastMessageAdapter("pubL.16.2", 0); //将行情落户的请求包 unsafe { if (fastMsg.Record == null || saveMsg.Record == null) { this.Dispatcher.Invoke(() => { btnStart.IsEnabled = true; MessageBox.Show("初始化数据包失败!\r\n请检查服务器是否正常", "异常", MessageBoxButton.OK, MessageBoxImage.Error); }); return; } } //券码 string stockNo = LoadStockInfo.excelData.Rows[j]["stock_code"].ToString(); if (forbidStocks.Contains(stockNo)) { continue; } char[] stockNos = stockNo.ToCharArray(); //市场 int exchNo = Convert.ToInt32(LoadStockInfo.excelData.Rows[j]["exch_no"]); //证券类型 int stockType = Convert.ToInt32(LoadStockInfo.excelData.Rows[j]["stock_type"]); if (stockNos.Length < 5 || stockNos.Length > 6) { continue; } //对5位数的券码进行数据处理 if (stockNos.Length < 6) { var tempStocks = stockNos.ToList(); tempStocks.Add('\0'); stockNos = tempStocks.ToArray(); } //昨收价格作为初始价格 double preClosePrice = Convert.ToDouble(LoadStockInfo.excelData.Rows[j]["pre_close_price"]); //涨停价 double upPrice = preClosePrice * (1 + limitPercent / 100.00); //跌停价 double downPrice = preClosePrice * (1 - limitPercent / 100.00); //精度 int precision = 0; //递增/递减价格 double price1 = CaculatePrecision((upPrice - preClosePrice) * Math.Sin(i * Math.PI / 180) + preClosePrice, exchNo, stockType, out precision); double price2 = CaculatePrecision((upPrice - preClosePrice) * Math.Sin((i + 1) * Math.PI / 180) + preClosePrice, exchNo, stockType, out precision); double price3 = CaculatePrecision((upPrice - preClosePrice) * Math.Sin((i + 2) * Math.PI / 180) + preClosePrice, exchNo, stockType, out precision); double price4 = CaculatePrecision((upPrice - preClosePrice) * Math.Sin((i + 3) * Math.PI / 180) + preClosePrice, exchNo, stockType, out precision); double price5 = CaculatePrecision((upPrice - preClosePrice) * Math.Sin((i + 4) * Math.PI / 180) + preClosePrice, exchNo, stockType, out precision); //最大最小价格Model MaxMinPriceModel MMP = null; //最大价格 double maxPrice = 0; //最小价格 double minPrice = 0; if (MaxMinPriceCollection.TryGetValue(stockNo, out MMP)) { if (price1 >= MMP.maxPrice) { maxPrice = price1; minPrice = MMP.minPrice; MaxMinPriceCollection[stockNo].maxPrice = price1; } else { maxPrice = MMP.maxPrice; //判断最小价格 if (price1 <= MMP.minPrice) { minPrice = price1; MaxMinPriceCollection[stockNo].minPrice = price1; } else { minPrice = MMP.minPrice; } } } else { MaxMinPriceCollection.Add(stockNo, new MaxMinPriceModel() { maxPrice = price1, minPrice = price1 }); } InitFastMsg.InitMsg("pubL.16.5", ref fastMsg); InitFastMsg.InitMsg("pubL.16.2", ref saveMsg); fastMsg.SetInt32(LDBizTag.LDBIZ_EXCH_NO_INT, exchNo); fastMsg.SetString(LDBizTag.LDBIZ_STOCK_CODE_STR, stockNo); //开始组装数据包 /* * 价格信息以正弦曲线的方式进行变动 price = (upPrice - price0) * Math.Sin((i + 4) * Math.PI / 180) + price0; * 数量信息呈线性增长 y = kx */ //数据基数 const int tmpValue = 1000; const int tmpValue0 = 100; IntPtr ptr; if (errorStocks.Contains(stockNo)) { #region 创建异常的行情包 WrongStockLevelRealTimeData wrongStockFiled = new WrongStockLevelRealTimeData(); wrongStockFiled.WrongData = tmpValue * 111; wrongStockFiled.PriceUnit = tmpValue; wrongStockFiled.UpPrice = (int)(downPrice * tmpValue); wrongStockFiled.DownPrice = (int)(upPrice * tmpValue); wrongStockFiled.FiveDayVol = 0; wrongStockFiled.OpenPrice = (int)(preClosePrice * tmpValue); wrongStockFiled.PrevClose = (int)(preClosePrice * tmpValue);; wrongStockFiled.BuyPrice1 = (int)(price1 * tmpValue); //买一价 wrongStockFiled.BuyPrice2 = (int)(price2 * tmpValue); //买二价 wrongStockFiled.BuyPrice3 = (int)(price3 * tmpValue); //买三价 wrongStockFiled.BuyPrice4 = (int)(price4 * tmpValue); //买四价 wrongStockFiled.BuyPrice5 = (int)(price5 * tmpValue); //买五价 wrongStockFiled.BuyCount1 = (uint)(tmpValue0 * i); wrongStockFiled.BuyCount2 = (uint)(tmpValue0 * i * 2); wrongStockFiled.BuyCount3 = (uint)(tmpValue0 * i * 3); wrongStockFiled.BuyCount4 = (uint)(tmpValue0 * i * 4); wrongStockFiled.BuyCount5 = (uint)(tmpValue0 * i * 5); wrongStockFiled.SellPrice1 = (int)(price1 * tmpValue); //卖一价 wrongStockFiled.SellPrice2 = (int)(price2 * tmpValue); //卖二价 wrongStockFiled.SellPrice3 = (int)(price3 * tmpValue); //卖三价 wrongStockFiled.SellPrice4 = (int)(price4 * tmpValue); //卖四价 wrongStockFiled.SellPrice5 = (int)(price5 * tmpValue); //卖五价 wrongStockFiled.SellCount1 = (uint)(tmpValue0 * i); wrongStockFiled.SellCount2 = (uint)(tmpValue0 * i * 2); wrongStockFiled.SellCount3 = (uint)(tmpValue0 * i * 3); wrongStockFiled.SellCount4 = (uint)(tmpValue0 * i * 4); wrongStockFiled.SellCount5 = (uint)(tmpValue0 * i * 5); //成交额 wrongStockFiled.AvgPrice = (int)(price1 * tmpValue) * (uint)(tmpValue0 * i) + (int)(price2 * tmpValue) * (uint)(tmpValue0 * i * 2) + (int)(price3 * tmpValue) * (uint)(tmpValue0 * i * 3) + (int)(price4 * tmpValue) * (uint)(tmpValue0 * i * 4) + (int)(price5 * tmpValue) * (uint)(tmpValue0 * i * 5); wrongStockFiled.MaxPrice = (int)(price5 * tmpValue); wrongStockFiled.MinPrice = (int)(price1 * tmpValue); wrongStockFiled.NewPrice = (int)(price3 * tmpValue); wrongStockFiled.HandNum = 100; wrongStockFiled.CodeType = 4361; wrongStockFiled.Decimal = 3; wrongStockFiled.StockCode = stockNos; //成交量 wrongStockFiled.Total = (uint)(tmpValue0 * i * 15); #endregion //将数据包转化成非托管类型 ptr = Marshal.AllocHGlobal(Marshal.SizeOf(wrongStockFiled)); Marshal.StructureToPtr(wrongStockFiled, ptr, false); fastMsg.SetRawData(LDBizTag.LDBIZ_QUOT_PRICE_INFO_STR, ptr, Marshal.SizeOf(wrongStockFiled)); } else { #region 创建正常的数据包 StockLevelRealTimeData stockFiled = new StockLevelRealTimeData(); stockFiled.PriceUnit = tmpValue; stockFiled.Decimal = precision; stockFiled.UpPrice = (int)(upPrice * tmpValue); stockFiled.DownPrice = (int)(downPrice * tmpValue); stockFiled.FiveDayVol = 0; stockFiled.OpenPrice = (int)(preClosePrice * tmpValue); stockFiled.PrevClose = (int)(preClosePrice * tmpValue);; stockFiled.BuyPrice1 = (int)(price1 * tmpValue); //买一价 stockFiled.BuyPrice2 = (int)(price2 * tmpValue); //买二价 stockFiled.BuyPrice3 = (int)(price3 * tmpValue); //买三价 stockFiled.BuyPrice4 = (int)(price4 * tmpValue); //买四价 stockFiled.BuyPrice5 = (int)(price5 * tmpValue); //买五价 stockFiled.BuyCount1 = (uint)(tmpValue0 * i); stockFiled.BuyCount2 = (uint)(tmpValue0 * i * 2); stockFiled.BuyCount3 = (uint)(tmpValue0 * i * 3); stockFiled.BuyCount4 = (uint)(tmpValue0 * i * 4); stockFiled.BuyCount5 = (uint)(tmpValue0 * i * 5); stockFiled.SellPrice1 = (int)(price1 * tmpValue); //卖一价 stockFiled.SellPrice2 = (int)(price2 * tmpValue); //卖二价 stockFiled.SellPrice3 = (int)(price3 * tmpValue); //卖三价 stockFiled.SellPrice4 = (int)(price4 * tmpValue); //卖四价 stockFiled.SellPrice5 = (int)(price5 * tmpValue); //卖五价 stockFiled.SellCount1 = (uint)(tmpValue0 * i); stockFiled.SellCount2 = (uint)(tmpValue0 * i * 2); stockFiled.SellCount3 = (uint)(tmpValue0 * i * 3); stockFiled.SellCount4 = (uint)(tmpValue0 * i * 4); stockFiled.SellCount5 = (uint)(tmpValue0 * i * 5); //成交额 stockFiled.AvgPrice = (int)(price1 * tmpValue) * (uint)(tmpValue0 * i) + (int)(price2 * tmpValue) * (uint)(tmpValue0 * i * 2) + (int)(price3 * tmpValue) * (uint)(tmpValue0 * i * 3) + (int)(price4 * tmpValue) * (uint)(tmpValue0 * i * 4) + (int)(price5 * tmpValue) * (uint)(tmpValue0 * i * 5); stockFiled.MaxPrice = (int)(maxPrice * tmpValue); stockFiled.MinPrice = (int)(minPrice * tmpValue); stockFiled.NewPrice = (int)(price1 * tmpValue); stockFiled.HandNum = 100; stockFiled.CodeType = 4361; stockFiled.StockCode = stockNos; //成交量 stockFiled.Total = (uint)(tmpValue0 * i * 15); #endregion #region 构建行情落库请求包 saveMsg.SetInt32(LDBizTag.LDBIZ_EXCH_NO_INT, exchNo); saveMsg.SetString(LDBizTag.LDBIZ_STOCK_CODE_STR, stockNo); saveMsg.SetDouble(LDBizTag.LDBIZ_LAST_PRICE_FLOAT, price3); saveMsg.SetDouble(LDBizTag.LDBIZ_PRE_CLOSE_PRICE_FLOAT, preClosePrice); saveMsg.SetString(LDBizTag.LDBIZ_STOP_STATUS_STR, "0"); saveMsg.SetDouble(LDBizTag.LDBIZ_UP_LIMIT_PRICE_FLOAT, 0); saveMsg.SetDouble(LDBizTag.LDBIZ_DOWN_LIMIT_PRICE_FLOAT, 0); saveMsg.SetDouble(LDBizTag.LDBIZ_TODAY_OPEN_PRICE_FLOAT, preClosePrice); saveMsg.SetDouble(LDBizTag.LDBIZ_TODAY_CLOSE_PRICE_FLOAT, price3); saveMsg.SetDouble(LDBizTag.LDBIZ_TODAY_MAX_PRICE_FLOAT, upPrice); saveMsg.SetDouble(LDBizTag.LDBIZ_TODAY_MIN_PRICE_FLOAT, downPrice); saveMsg.SetDouble(LDBizTag.LDBIZ_BUY_PRICE_1_FLOAT, price1); saveMsg.SetDouble(LDBizTag.LDBIZ_BUY_PRICE_2_FLOAT, price2); saveMsg.SetDouble(LDBizTag.LDBIZ_BUY_PRICE_3_FLOAT, price3); saveMsg.SetDouble(LDBizTag.LDBIZ_BUY_PRICE_4_FLOAT, price4); saveMsg.SetDouble(LDBizTag.LDBIZ_BUY_PRICE_5_FLOAT, price5); saveMsg.SetDouble(LDBizTag.LDBIZ_BUY_QTY_1_FLOAT, tmpValue0 * i); saveMsg.SetDouble(LDBizTag.LDBIZ_BUY_QTY_2_FLOAT, tmpValue0 * i * 2); saveMsg.SetDouble(LDBizTag.LDBIZ_BUY_QTY_3_FLOAT, tmpValue0 * i * 3); saveMsg.SetDouble(LDBizTag.LDBIZ_BUY_QTY_4_FLOAT, tmpValue0 * i * 4); saveMsg.SetDouble(LDBizTag.LDBIZ_BUY_QTY_5_FLOAT, tmpValue0 * i * 5); saveMsg.SetDouble(LDBizTag.LDBIZ_SELL_PRICE_1_FLOAT, price1); saveMsg.SetDouble(LDBizTag.LDBIZ_SELL_PRICE_2_FLOAT, price2); saveMsg.SetDouble(LDBizTag.LDBIZ_SELL_PRICE_3_FLOAT, price3); saveMsg.SetDouble(LDBizTag.LDBIZ_SELL_PRICE_4_FLOAT, price4); saveMsg.SetDouble(LDBizTag.LDBIZ_SELL_PRICE_5_FLOAT, price5); saveMsg.SetDouble(LDBizTag.LDBIZ_SELL_QTY_1_FLOAT, tmpValue0 * i); saveMsg.SetDouble(LDBizTag.LDBIZ_SELL_QTY_2_FLOAT, tmpValue0 * i * 2); saveMsg.SetDouble(LDBizTag.LDBIZ_SELL_QTY_3_FLOAT, tmpValue0 * i * 3); saveMsg.SetDouble(LDBizTag.LDBIZ_SELL_QTY_4_FLOAT, tmpValue0 * i * 4); saveMsg.SetDouble(LDBizTag.LDBIZ_SELL_QTY_5_FLOAT, tmpValue0 * i * 5); saveMsg.SetDouble(LDBizTag.LDBIZ_STRIKE_QTY_FLOAT, tmpValue0 * i * 15); saveMsg.SetDouble(LDBizTag.LDBIZ_STRIKE_AMT_FLOAT, price1 * tmpValue0 * i + price2 * tmpValue0 * i * 2 + price3 * tmpValue0 * i * 3 + price4 * tmpValue0 * i * 4 + price5 * tmpValue0 * i * 5); #endregion //将数据包转化成非托管类型 ptr = Marshal.AllocHGlobal(Marshal.SizeOf(stockFiled)); Marshal.StructureToPtr(stockFiled, ptr, false); fastMsg.SetRawData(LDBizTag.LDBIZ_QUOT_PRICE_INFO_STR, ptr, Marshal.SizeOf(stockFiled)); } //制造阻塞,确保数据包发送之后才进行内存回收 int result = await SendPubTopicsPackage(fastMsg, "quote.realtime"); //发送行情落库请求包 await SendRequsetPackage(saveMsg, "pubL.16.2"); Marshal.FreeHGlobal(ptr);//释放非托管内存 Thread.Sleep(TimeSpan.FromMilliseconds(delay)); } #endregion } this.Dispatcher.Invoke(() => { btnStart.IsEnabled = true; }); } catch (Exception error) { this.Dispatcher.Invoke(() => { btnStart.IsEnabled = true; }); MessageBox.Show(error.Message + "\r\n" + error.StackTrace); } }
/// <summary> /// 发送数据并且绘制正弦曲线 /// </summary> private async void DrawSin() { try { int Zoom = 15; //放大倍数 Point center = new Point(0, pbShow.Height / 2); //原点 float x1 = (float)(0 * Math.PI * Zoom / 180 + center.X); float y1 = (float)(Math.Sin(0 * Math.PI / 180) * 11 * Zoom + center.Y); grap.DrawLine(Pens.Black, 0, center.Y, pbShow.Width, center.Y); //x坐标轴 grap.DrawLine(Pens.Black, center.X, 0, center.X, pbShow.Height); //y坐标轴 LDFastMessageAdapter fastMsg = new LDFastMessageAdapter("pubL.16.5", 0); StockLevelRealTimeData stockFiled = new StockLevelRealTimeData(); for (double i = 1; i < 360 * 4; i++) //角 { if (isPause) { waitHandle.WaitOne(); } float x2 = (float)(i * Math.PI * Zoom / 180 + center.X); float y2 = (float)Math.Sin(i * Math.PI / 180) * (-1) * 11 * Zoom + center.Y; grap.DrawLine(Pens.Red, x1, y1, x2, y2); grap.Save(); this.pbShow.Invoke(new Action(() => { pbShow.Image = bmp; })); #region 针对每个券码发送一个生成并发送一个数据包 int rows = LoadStockInfo.excelData.GetLength(0); for (int j = 1; j < rows; j++) { //券码 string stockNo = LoadStockInfo.excelData[j, 1].ToString(); char[] stockNos = stockNo.ToCharArray(); if (stockNos.Length < 5 || stockNos.Length > 6) { continue; } if (stockNos.Length < 6) { var tempStocks = stockNos.ToList(); tempStocks.Add('\0'); stockNos = tempStocks.ToArray(); } //涨停价 double upPrice = Convert.ToDouble(LoadStockInfo.excelData[j, 4]); //跌停价 double downPrice = Convert.ToDouble(LoadStockInfo.excelData[j, 5]); //初始价格 double price0 = (upPrice + downPrice) / 2.00; //递增/递减价格 double price1 = (upPrice - price0) * Math.Sin(i * Math.PI / 180) + price0; double price2 = (upPrice - price0) * Math.Sin((i + 1) * Math.PI / 180) + price0; double price3 = (upPrice - price0) * Math.Sin((i + 2) * Math.PI / 180) + price0; double price4 = (upPrice - price0) * Math.Sin((i + 3) * Math.PI / 180) + price0; double price5 = (upPrice - price0) * Math.Sin((i + 4) * Math.PI / 180) + price0; fastMsg.SetInt32(LDBizTag.LDBIZ_EXCH_NO_INT, 1); fastMsg.SetString(LDBizTag.LDBIZ_STOCK_CODE_STR, stockNo); //开始组装数据包 int tmpValue = 1000; int tmpValue0 = 100; stockFiled.PriceUnit = tmpValue; stockFiled.UpPrice = (int)(upPrice * tmpValue); stockFiled.DownPrice = (int)(downPrice * tmpValue); stockFiled.FiveDayVol = 0; stockFiled.OpenPrice = (int)(price0 * tmpValue); stockFiled.PrevClose = (int)(price0 * tmpValue);; stockFiled.BuyPrice1 = (int)(price1 * tmpValue); stockFiled.BuyPrice2 = (int)(price2 * tmpValue); stockFiled.BuyPrice3 = (int)(price3 * tmpValue); stockFiled.BuyPrice4 = (int)(price4 * tmpValue); stockFiled.BuyPrice5 = (int)(price5 * tmpValue); stockFiled.BuyCount1 = (uint)(tmpValue0 * i); stockFiled.BuyCount2 = (uint)(tmpValue0 * i * 2); stockFiled.BuyCount3 = (uint)(tmpValue0 * i * 3); stockFiled.BuyCount4 = (uint)(tmpValue0 * i * 4); stockFiled.BuyCount5 = (uint)(tmpValue0 * i * 5); stockFiled.SellPrice1 = (int)(price1 * tmpValue); stockFiled.SellPrice2 = (int)(price2 * tmpValue); stockFiled.SellPrice3 = (int)(price3 * tmpValue); stockFiled.SellPrice4 = (int)(price4 * tmpValue); stockFiled.SellPrice5 = (int)(price5 * tmpValue); stockFiled.SellCount1 = (uint)(tmpValue0 * i); stockFiled.SellCount2 = (uint)(tmpValue0 * i * 2); stockFiled.SellCount3 = (uint)(tmpValue0 * i * 3); stockFiled.SellCount4 = (uint)(tmpValue0 * i * 4); stockFiled.SellCount5 = (uint)(tmpValue0 * i * 5); stockFiled.AvgPrice = (int)(price1 * tmpValue) * (uint)(tmpValue0 * i) + (int)(price2 * tmpValue) * (uint)(tmpValue0 * i * 2) + (int)(price3 * tmpValue) * (uint)(tmpValue0 * i * 3) + (int)(price4 * tmpValue) * (uint)(tmpValue0 * i * 4) + (int)(price5 * tmpValue) * (uint)(tmpValue0 * i * 5); stockFiled.MaxPrice = (int)(price5 * tmpValue); stockFiled.MinPrice = (int)(price1 * tmpValue); stockFiled.NewPrice = (int)(price3 * tmpValue); stockFiled.HandNum = 100; stockFiled.CodeType = 4361; stockFiled.Decimal = 3; stockFiled.StockCode = stockNos; stockFiled.Total = (uint)(tmpValue0 * i * 10); //将数据包转化成非托管类型 IntPtr ptr = Marshal.AllocHGlobal(Marshal.SizeOf(stockFiled)); Marshal.StructureToPtr(stockFiled, ptr, false); fastMsg.SetRawData(LDBizTag.LDBIZ_QUOT_PRICE_INFO_STR, ptr, Marshal.SizeOf(stockFiled)); //制造阻塞,确保数据包发送之后才进行内存回收 int result = await SendPackage(fastMsg); fastMsg.FreeMsg(); Marshal.FreeHGlobal(ptr); Thread.Sleep(TimeSpan.FromMilliseconds(delay)); } #endregion x1 = x2; y1 = y2; } this.btnStart.Invoke(new Action(() => { btnStart.Enabled = true; })); } catch (Exception error) { Log.WriteLog(error.Message); MessageBox.Show(error.StackTrace + "\r\n" + error.Message); } }
/// <summary> /// 发送请求数据包的方法 /// </summary> /// <param name="fun">已经构建好的请求应答包</param> /// <param name="defaultTable">对应defaultvalue.xlsx文件,取默认值用的</param> private unsafe void SendFastMsgFun(BizFunction fun, DataTable defaultTable) { LDsdkDefineEx.LDFastMessageAdapter fastmsg = new LDFastMessageAdapter(fun.FunctonId, 0); LDRecordAdapter lpRecord = fastmsg.GetBizBodyRecord(); //获取字段总数量 int iFieldCount = lpRecord.GetFieldCount(); int iIndex = 0; for (iIndex = 0; iIndex < iFieldCount; iIndex++) { //取得字段类型 int fieldtype = lpRecord.GetFieldType(iIndex); //取得字段名称 string fieldName = lpRecord.GetFieldNamebyIndex(iIndex); BizRequestField bizField = fun.ReqFields.FirstOrDefault(o => o.FieldName.Equals(fieldName)); String fieldValue = ""; if (bizField != null) { fieldValue = bizField.FieldValue; //取得入参的值 } if (string.IsNullOrEmpty(fieldValue)) //如果没有手动赋值,则去默认值 { fieldValue = UtilTool.GetDefaultValue(defaultTable, fieldName); } if ("func_code".Equals(fieldName)) //如果字段名称是func_code,则把功能号作为值赋给字段 { fieldValue = fun.FunctonId; } UtilTool.SetFastMsgValue(fastmsg, fieldtype, fieldValue, iIndex); } //应答包 LDFastMessageAdapter outFast = null; int nRet = (int)ConnectionManager.Instance.CurConnection.Connect.SendAndReceive(fun.FunctonId, fastmsg, ref outFast, 5000); fastmsg.FreeMsg(); /**********************************开始对应答包进行处理**************************************/ if (nRet < 0) { LogHelper.Logger.Error(fun.FunctonId + "发送失败,错误号=" + nRet); PrintHelper.Print.AppendLine(fun.FunctonId + "发送失败,错误号=" + nRet); } if (nRet >= 0 && outFast.Record != null) { int iErrorNo = outFast.GetInt32(LDSdkTag.LDTAG_ERRORNO); if (iErrorNo != 0) { LogHelper.Logger.Error("SystemErrorInfo=" + outFast.GetString(LDSdkTag.LDTAG_ERRORINFO)); } else { //将回归脚本的应答包信息写入文件 //string savePath = Environment.CurrentDirectory + @"\RegressionTestResult.txt";//文件保存路径 //LogAnswerPackageInfo.OutPutResult(outFast, savePath); if (fun.AnswerFlag) { //获取应答包包体数据 LDRecordAdapter lpOutRecord = outFast.GetBizBodyRecord(); //获取应答包字段总数 int iAnswerFieldCount = lpOutRecord.GetFieldCount(); //遍历获取应答包字段的 出参=值 信息,并塞入到对应的请求应答包里面去 BizFunction fun int iAnswerIndex = 0; for (iAnswerIndex = 0; iAnswerIndex < iAnswerFieldCount; iAnswerIndex++) { //获取出参字段名 string fieldName = lpOutRecord.GetFieldNamebyIndex(iAnswerIndex); //获取出参字段类型 int fieldType = lpOutRecord.GetFieldType(iAnswerIndex); //只把会用到的字段塞入 BizAnswerField bizField = fun.Answer.RspFields.FirstOrDefault(o => o.FieldName.Equals(fieldName)); if (bizField != null) { bizField.FieldValue = UtilTool.GetFastMsgValue(outFast, fieldType, iAnswerIndex); bizField.FieldType = fieldType; } } } } outFast.FreeMsg(); } }
/// <summary> /// 发送压力测试的请求包 /// </summary> /// <param name="file"></param> /// <param name="result"></param> private void SendFastMsgReq(CaseFileData file, out string result) { try { foreach (CaseFunction funitem in file.Functions) { int nSendTimes = 0; do { bool bNeedWait = (file.SendCount - file.RecCount) >= file.UpStage; if (bNeedWait) { file.ResetEvent.Reset(); if (!file.ResetEvent.WaitOne(10000)) { file.SendCount = file.RecCount; //每秒钟判断一次是否达到积压上限 continue; } } nSendTimes++; #region 发送包 LDsdkDefineEx.LDFastMessageAdapter fastmsg = new LDFastMessageAdapter(funitem.FunID, funitem.FunType); //读取储存默认值的Excel文档,给未复制的参数赋予默认值 foreach (var filedItem in funitem.Fileds) { string FiledValue = filedItem.FiledValue; int filedType = filedItem.FiledType; string filedName = filedItem.FiledName; FiledValue = GetParamValue(funitem, filedItem); //如果获取参数值失败,直接退出 if (FiledValue == "error") { result = "error"; return; } if (string.IsNullOrEmpty(FiledValue)) { //没有默认值,取默认值 if (!filedItem.HaveDefaultValue) { FiledValue = GetDefaultValue(filedItem.FiledName, FiledValue); filedItem.DefaultValue = FiledValue; filedItem.HaveDefaultValue = true; } FiledValue = filedItem.DefaultValue; } UtilTool.SetFastMsgValueById(fastmsg, filedType, FiledValue, filedItem.FiledTag); } int sendId = Interlocked.Increment(ref LastSendId); fastmsg.SetInt32(LDBizTagDefine.LDSdkTag.LDTAG_PACKETID, sendId); //赋值完毕,异步发送数据包 lock (ReqLock) { ReqAllList.Add(new ReqDTO() { SendID = sendId, CaseData = file }); } int nRet = (int)ConnectionManager.Instance.CurConnection.Connect.AsyncSend(funitem.FunID, fastmsg, 5000); if (nRet > 0) { Interlocked.Increment(ref file.SendCount); Interlocked.Increment(ref file.SendOkCount); } else { Interlocked.Increment(ref file.SendFailCount); } fastmsg.FreeMsg(); #endregion }while (funitem.SendTimes > nSendTimes); } result = "OK"; } catch (Exception error) { this.Dispatcher.Invoke(() => { MessageBox.Show($"{error.Message} \r\n {error.StackTrace}"); }); result = "error"; } }
/// <summary> /// 加载案例数据 /// </summary> /// <param name="filePath"></param> /// <param name="funList"></param> /// <returns></returns> public CaseFileData LoadCaseData(String filePath, List <CaseFunction> funList) { CaseFileData datas = new CaseFileData(); try { if (!File.Exists(filePath)) { return(datas); } datas.FilePath = @filePath; XElement rootXML = XDocument.Load(filePath).Element("bizmsgs"); var funsXml = rootXML.Elements("function"); foreach (var item in funsXml) { string functionid = item.Attribute("functionid").Value; string packettype = item.Attribute("packettype").Value; var CheckFun = funList.FirstOrDefault(o => o.Check == 1 && o.FunID == functionid); if (packettype.Equals("0") && CheckFun != null) { string functionname = item.Attribute("functionname").Value; CaseFunction fun = new CaseFunction() { FunID = functionid, FunType = 0, Check = 1, FunName = functionname }; //发送次数 if (item.Attribute("times") != null) { string sendTimes = item.Attribute("times").Value; int nSendTimes = 1; int.TryParse(sendTimes, out nSendTimes); fun.SendTimes = nSendTimes; } datas.Functions.Add(fun); var filedsXml = item.Elements("field"); LDsdkDefineEx.LDFastMessageAdapter fastmsg = new LDFastMessageAdapter(functionid, 0); LDRecordAdapter lpRecord = fastmsg.GetBizBodyRecord(); int iIndex = 0; foreach (var filedItem in filedsXml) { string fieldid = filedItem.Attribute("fieldid").Value; string fieldname = filedItem.Attribute("fieldname").Value; int filedtype = lpRecord.GetFieldType(iIndex); PARAMTYPE paramtype = PARAMTYPE.emFile; string value = ""; if (filedItem.Attribute("value") != null) { value = filedItem.Attribute("value").Value; } if (filedItem.Attribute("paramtype") != null) { string strparamtype = filedItem.Attribute("paramtype").Value; if ("file".Equals(strparamtype)) { paramtype = PARAMTYPE.emFile; } } CaseFiled filed = new CaseFiled() { FiledTag = int.Parse(fieldid), FiledName = fieldname, FiledValue = value, FiledType = filedtype, FiledIndex = iIndex, ParamType = paramtype }; var fileElemt = filedItem.Element("file"); if (fileElemt != null && paramtype == PARAMTYPE.emFile) { filed.ColumnName = fieldname; if (fileElemt.Attribute("columnname") != null) { filed.ColumnName = fileElemt.Attribute("columnname").Value; } if (fileElemt.Attribute("filename") != null) { filed.FileName = fileElemt.Attribute("filename").Value; CSVFile csvFile = null; if (File.Exists(filed.FileName) && !fun.AllCsvFile.TryGetValue(filed.FileName, out csvFile)) { var data = CSVFileHelper.OpenCSV(filed.FileName); if (data != null) { csvFile = new CSVFile(); csvFile.FileName = filed.FiledName; csvFile.Table = data; fun.AllCsvFile.Add(filed.FileName, csvFile); } } if (csvFile != null && string.IsNullOrWhiteSpace(csvFile.DefaultFieldName)) { csvFile.DefaultFieldName = fieldname; } } filed.SelectRow = VALUETYPE.emSameLine; if (fileElemt.Attribute("selectrow") != null) { try { string SelectRow = fileElemt.Attribute("selectrow").Value; if ("sequence".Equals(SelectRow)) { filed.SelectRow = VALUETYPE.emSequence; } else if (new Regex("same_line").Match(SelectRow).Success) { filed.SameLineColumn = SelectRow.Split('[')[1].Split(']')[0]; filed.SelectRow = VALUETYPE.emSameLine; } else if ("random".Equals(SelectRow)) { //默认("random".Equals(SelectRow)) filed.SelectRow = VALUETYPE.emRandom; } } catch (Exception) { //throw; } } } fun.Fileds.Add(filed); iIndex++; } fastmsg.FreeMsg(); } } return(datas); } catch (Exception error) { this.Dispatcher.Invoke(() => { MessageBox.Show($"{error.Message} \r\n {error.StackTrace}"); }); return(datas); } }
/// <summary> /// 死循环处理队列里的应答包 /// </summary> private void DealRespPackage() { Task.Run( () => { while (true) { RespDataPackageModel RDP = new RespDataPackageModel(); if (RespDataPackageModel.DataQueue.TryDequeue(out RDP)) { Task.Run( () => { int hSend = RDP.hSend; LDFastMessageAdapter lpFastMsg = RDP.lpFastMsg; DateTime timeStamp = DateTime.Now; ReqDTO req = null; lock (ReqLock) { req = ReqAllList.FirstOrDefault(o => o.SendID == hSend); ReqAllList.Remove(req); } if (req != null && lpFastMsg != null) { Interlocked.Increment(ref req.CaseData.RecCount); //递增应答数量 if (req.CaseData.SendCount - req.CaseData.RecCount <= req.CaseData.DownStage) { req.CaseData.ResetEvent.Set(); } //功能号 string strFunCode = lpFastMsg.GetString(LDSdkTag.LDTAG_FUNCID); /***********************************郑建翔新加部分,用于计算应答频率***************************************/ lock (lockFlag) { //如果集合中不存这个功能号则添加 if (ReplyRateInfos.Count(i => i.functionId == strFunCode) == 0) { DateTime startTime = DateTime.Now; this.Dispatcher.Invoke(() => ReplyRateInfos.Add(new ReplyRateModel(strFunCode, startTime))); /*****************************接收到每个功能号的第一条应答时,保存应答信息**************************/ //文件保存路径 string savePath = Environment.CurrentDirectory + @"\ScriptOutPut.txt"; LogAnswerPackageInfo.OutPutResult(lpFastMsg, savePath); } else { //如果集合中已经存在这个功能号,开始更新并计算数据 ReplyRateModel replyInfo = ReplyRateInfos.FirstOrDefault(i => i.functionId == strFunCode); replyInfo.timeStamp = timeStamp; replyInfo.replyCount++; } } /*******************************************修改结束*********************************************************/ int iErrorNo = lpFastMsg.GetInt32(LDSdkTag.LDTAG_ERRORNO); // LogHelper.Logger.Info("系统错误号:" + iErrorNo); if (iErrorNo != 0) { //如果是中间件返回的错误 // Interlocked.Increment(ref req.CaseData.RecFailCount);//递增应答失败数量 } else { string strErrorCode = lpFastMsg.GetString(LDBizTag.LDBIZ_ERROR_CODE_STR); //LogHelper.Logger.Info("业务错误号:" + strErrorCode); Interlocked.Increment(ref req.CaseData.RecOkCount); //递增应答成功数量 if (!"0".Equals(strErrorCode)) { Interlocked.Increment(ref req.CaseData.RecFailCount); //递增应答失败数量 string strErrorInfo = lpFastMsg.GetString(LDBizTag.LDBIZ_ERROR_INFO_STR); string strErrorPrompt = lpFastMsg.GetString(LDBizTag.LDBIZ_ERROR_PROMPT_STR); string logInfo = string.Format("功能号[{0}],errorCode[{1}],errorinfo[{2}],errorprompt[{3}]", strFunCode, strErrorCode, strErrorInfo, strErrorPrompt); LogHelper.Logger.Error(logInfo); } //else //{ // Interlocked.Increment(ref req.CaseData.RecOkCount);//递增应答成功数量 //} } } if (lpFastMsg != null) { lpFastMsg.FreeMsg(); } } ); } //else //{ // pauseFlag.WaitOne(10); //} } } ); }
private void ConnectionInfo_OnPublishCallBack(int connectionID, string strTopicName, LDFastMessageAdapter fastMsg) { OnPublish(GetConnectionInfo(connectionID), strTopicName, fastMsg); }
public RespDataPackageModel(int send, LDFastMessageAdapter fastMsg) { hSend = send; lpFastMsg = fastMsg; }
private void ConnectionInfo_OnReceivedExCallBack(int connectionID, int hSend, LDFastMessageAdapter lpFastMsg, int result) { OnReceivedEx(GetConnectionInfo(connectionID), hSend, lpFastMsg, result); }