Beispiel #1
0
        //数据
        public override void OnReceivedBizMsg(CT2Connection lpConnection, int hSend, CT2BizMessage lpMsg)
        {
            int errcode  = lpMsg.GetErrorNo();     //获取错误代码
            int retcode  = lpMsg.GetReturnCode();  //获取返回码
            int function = lpMsg.GetFunction();

            if (errcode != 0)
            {
                MessageManager.GetInstance().Add(MessageType.Error, string.Format("异步接收出错:", lpMsg.GetErrorInfo()));
                return;
            }

            string      msg = "", entrustlist = "", batchno = "";
            uint        cnt      = 0;
            CT2UnPacker unpacker = null;

            unsafe
            {
                int   iLen   = 0;
                void *lpdata = lpMsg.GetContent(&iLen);
                unpacker = new CT2UnPacker(lpdata, (uint)iLen);
            }

            errcode = unpacker.GetInt("ErrorCode");
            if (errcode != 0)
            {
                msg = unpacker.GetStr("ErrorMsg");
                MessageManager.GetInstance().Add(MessageType.Error, string.Format("操作失败:{0}", msg));
                return;
            }

            //回报数据存于第1个数据集,第0个为错误消息
            unpacker.SetCurrentDatasetByIndex(1);
            cnt = unpacker.GetRowCount();
            while (unpacker.IsEOF() == 0)
            {
                entrustlist += unpacker.GetInt("entrust_no") + "|";
                batchno      = unpacker.GetInt("batch_no").ToString();
                unpacker.Next();
            }

            //返回消息
            switch (function)
            {
            case (int)EntrustHundsun.OptionFunction.SingleEntrust:
                MessageManager.GetInstance().Add(MessageType.TradeNotice, string.Format("单笔委托回报:成功,共1笔,|{0}", entrustlist));
                break;

            case (int)EntrustHundsun.OptionFunction.BasketEntrust:
                MessageManager.GetInstance().Add(MessageType.TradeNotice, string.Format("篮子委托回报:成功,批号={0}", batchno));
                break;

            case (int)EntrustHundsun.OptionFunction.Withdraw:
                MessageManager.GetInstance().Add(MessageType.TradeNotice, string.Format("委托撤单回报:成功,共{0}笔,|{1}", cnt, entrustlist));
                break;

            default:
                break;
            }
        }
Beispiel #2
0
 //回报
 public override void OnReceived(CT2SubscribeInterface lpSub, int subscribeIndex, void *lpData, int nLength, tagSubscribeRecvData lpRecvData)
 {
     try
     {
         Debug.Print("/*********************************收到主推数据 begin***************************/");
         string strInfo = string.Format("附加数据长度:       {0}", lpRecvData.iAppDataLen);
         Debug.Print(strInfo);
         if (lpRecvData.iAppDataLen > 0)
         {
             unsafe
             {
                 strInfo = string.Format("附加数据:           {0}", Marshal.PtrToStringAuto(new IntPtr(lpRecvData.lpAppData)));
                 Debug.Print(strInfo);
             }
         }
         Debug.Print("过滤字段部分:\n");
         if (lpRecvData.iFilterDataLen > 0)
         {
             CT2UnPacker lpUnpack = new CT2UnPacker(lpRecvData.lpFilterData, (uint)lpRecvData.iFilterDataLen);
             //ufxengine.ShowUnPacker(lpUnpack);
             lpUnpack.Dispose();
         }
         CT2UnPacker lpUnPack1 = new CT2UnPacker((void *)lpData, (uint)nLength);
         if (lpUnPack1 != null)
         {
             //ufxengine.ShowUnPacker(lpUnPack1);
             lpUnPack1.Dispose();
         }
         Debug.Print("/*********************************收到主推数据 end ***************************/");
     }
     catch (System.Exception ex)
     {
         throw ex;
     }
 }
        public override void OnReceived(CT2SubscribeInterface lpSub, int subscribeIndex, void* lpData, int nLength, tagSubscribeRecvData lpRecvData)
        {
            //收到主推数据 - 开始
            if (lpRecvData.iAppDataLen > 0)
            {
                unsafe
                {
                    //附加数据
                    string strInfo = string.Format("{0}", Marshal.PtrToStringAuto(new IntPtr(lpRecvData.lpAppData)));
                }
            }

            //过滤字段部分
            if (lpRecvData.iFilterDataLen > 0)
            {
                CT2UnPacker lpUnpacker = new CT2UnPacker(lpRecvData.lpFilterData, (uint)lpRecvData.iFilterDataLen);
                //解包
                //.....
                lpUnpacker.Dispose();
            }

            CT2UnPacker lpUnpacker1 = new CT2UnPacker((void*)lpData, (uint)nLength);
            if(lpUnpacker1 != null)
            {
                //解包
                //....
                lpUnpacker1.Dispose();
            }

            //收到主推数据 - 结束
        }
        public override void OnReceived(CT2SubscribeInterface lpSub, int subscribeIndex, void *lpData, int nLength, tagSubscribeRecvData lpRecvData)
        {
            //收到主推数据 - 开始
            if (lpRecvData.iAppDataLen > 0)
            {
                unsafe
                {
                    //附加数据
                    string strInfo = string.Format("{0}", Marshal.PtrToStringAuto(new IntPtr(lpRecvData.lpAppData)));
                }
            }

            UFXPushMessageType messageType = UFXPushMessageType.None;

            //过滤字段部分
            if (lpRecvData.iFilterDataLen > 0)
            {
                CT2UnPacker lpUnpacker = new CT2UnPacker(lpRecvData.lpFilterData, (uint)lpRecvData.iFilterDataLen);
                //解包
                //.....
                DataParser parser = new DataParser();
                parser.Parse(lpUnpacker);


                Log("====推送=====过滤字段部分=====开始");
                //parser.Output();
                Log(parser);
                Log("====推送=====过滤字段部分=====结束");
                lpUnpacker.Dispose();

                messageType = _filterBLL.GetMessageType(parser);
            }

            if (nLength > 0)
            {
                CT2UnPacker lpUnpacker1 = new CT2UnPacker((void *)lpData, (uint)nLength);
                if (lpUnpacker1 != null)
                {
                    //解包
                    //....
                    DataParser parser = new DataParser();
                    parser.Parse(lpUnpacker1);
                    Log("====推送*****数据部分=====开始");
                    //parser.Output();
                    Log(parser);
                    Log("====推送*****数据部分=====结束");
                    lpUnpacker1.Dispose();

                    IUFXMessageHandlerBase subscriberHandler = _handlerFactory.Create(messageType);
                    if (subscriberHandler != null)
                    {
                        TaskFactory taskFactory = new TaskFactory(_taskScheduler);
                        taskFactory.StartNew(() => subscriberHandler.Handle(parser));
                    }
                }
            }

            //收到主推数据 - 结束
        }
Beispiel #5
0
        public override void OnReceivedBizMsg(CT2Connection lpConnection, int hSend, CT2BizMessage lpMsg)
        {
            int iRetCode   = lpMsg.GetErrorNo();    //获取返回码
            int iErrorCode = lpMsg.GetReturnCode(); //获取错误码
            int iFunction  = lpMsg.GetFunction();

            if (iRetCode != 0)
            {
                Debug.Print("异步接收出错:" + lpMsg.GetErrorNo().ToString() + lpMsg.GetErrorInfo());
            }
            else
            {
                if (iFunction == 620000)//1.0消息中心心跳
                {
                    Debug.Print("收到心跳!==>" + iFunction);
                    lpMsg.ChangeReq2AnsMessage();
                    connMain.SendBizMsg(lpMsg, 1);
                    return;
                }
                else if (iFunction == 620003 || iFunction == 620025) //收到发布过来的行情
                {
                    Debug.Print("收到主推消息!==>" + iFunction);
                    int         iKeyInfo  = 0;
                    void *      lpKeyInfo = lpMsg.GetKeyInfo(&iKeyInfo);
                    CT2UnPacker unPacker  = new CT2UnPacker(lpKeyInfo, (uint)iKeyInfo);
                    //this.ShowUnPacker(unPacker);
                    unPacker.Dispose();
                }
                else if (iFunction == 620001)
                {
                    Debug.Print("收到订阅应答!==>");
                    return;
                }
                else if (iFunction == 620002)
                {
                    Debug.Print("收到取消订阅应答!==>");
                    return;
                }

                CT2UnPacker unpacker = null;
                unsafe
                {
                    int   iLen   = 0;
                    void *lpdata = lpMsg.GetContent(&iLen);
                    unpacker = new CT2UnPacker(lpdata, (uint)iLen);
                }
                if (iFunction == 10001)
                {
                    int code = unpacker.GetInt("ErrCode");
                    if (code == 0)
                    {
                        unpacker.SetCurrentDatasetByIndex(1);
                        token = unpacker.GetStr("user_token");
                    }
                }
                //this.ShowUnPacker(unpacker);
            }
        }
Beispiel #6
0
        private void button1_Click(object sender, EventArgs e)
        {
            //初始化t2连接
            if (!InitT2())
            {
                return;
            }

            //打包请求报文
            CT2Packer packer  = new CT2Packer(2);
            sbyte     strType = Convert.ToSByte('S');
            sbyte     intType = Convert.ToSByte('I');

            packer.BeginPack();
            //插件编号
            packer.AddField("plugin_id", strType, 255, 4);
            //管理功能号
            packer.AddField("function_id", intType, 255, 4);
            packer.AddStr("com.hundsun.fbase.f2core");
            packer.AddInt(100);
            packer.EndPack();
            //功能号,业务包
            int iRet = conn.SendBiz(8, packer, 0, 0, 1);

            if (iRet < 0)
            {
                DisplayText(conn.GetErrorMsg(iRet));
            }
            else
            {
                string      error    = null;
                CT2UnPacker unpacker = null;
                iRet = conn.RecvBiz(iRet, out error, out unpacker, 4000, 0);
                if (iRet == 0 || iRet == 1)
                {
                    while (unpacker.IsEOF() != 1)
                    {
                        for (int i = 0; i < unpacker.GetColCount(); i++)
                        {
                            textBox1.Text += unpacker.GetStrByIndex(i) + " ";
                        }
                        textBox1.Text += "\r\n";
                        unpacker.Next();
                    }
                }
                else if (iRet < 0)
                {
                    DisplayText(conn.GetErrorMsg(iRet));
                }
                else if (iRet == 2)
                {
                    DisplayText("解包失败");
                }
            }

            packer.Dispose();
        }
Beispiel #7
0
        public ConnectionCode Subscribe(LoginUser user, IUFXMessageHandlerFactory handlerFactory)
        {
            callback = new T2SubCallback(handlerFactory);
            subcribe = _conn.NewSubscriber(callback, SubscribeName, (int)_timeOut, 2000, 100);
            if (subcribe == null)
            {
                string msg = string.Format("主推业务订阅创建失败: {0}", _conn.GetMCLastError());
                logger.Error(msg);
                return(ConnectionCode.ErrorFailSubscribe);
            }

            CT2SubscribeParamInterface args = new CT2SubscribeParamInterface();

            args.SetTopicName("ufx_topic");
            args.SetReplace(false);
            args.SetFilter("operator_no", user.Operator);

            CT2Packer req = new CT2Packer(2);

            req.BeginPack();
            req.AddField("login_operator_no", Convert.ToSByte('S'), 16, 4);
            req.AddField("password", Convert.ToSByte('S'), 16, 4);
            req.AddStr(user.Operator);
            req.AddStr(user.Password);
            req.EndPack();

            CT2UnPacker unpacker = null;
            int         ret      = subcribe.SubscribeTopicEx(args, 50000, out unpacker, req);

            req.Dispose();
            //根据文档说明,返回值大于0表示有效的订阅标识,否则其他表示错误。
            if (ret > 0)
            {
                string msg = string.Format("主推业务订阅创建成功, 返回码: {0}, 消息: {1}", ret, _conn.GetErrorMsg(ret));
                logger.Info(msg);
                return(ConnectionCode.SuccessSubscribe);
            }
            else
            {
                string outMsg = string.Empty;
                if (unpacker != null)
                {
                    //Show(back);
                    DataParser parser = new DataParser();
                    parser.Parse(unpacker);
                    unpacker.Dispose();

                    var errResponse = T2ErrorHandler.Handle(parser);
                    outMsg = errResponse.MessageDetail;
                }

                string msg = string.Format("主推业务订阅创建失败,返回码: {0}, 消息: {1}, 返回数据包消息: {2}", ret, _conn.GetErrorMsg(ret), outMsg);
                logger.Error(msg);
                return(ConnectionCode.ErrorFailSubscribe);
            }
        }
Beispiel #8
0
        public override void Logon(string user, string pwd)
        {
            //无需重复登陆
            if (islogon())
            {
                return;
            }

            #region packer
            CT2Packer packer = new CT2Packer(2);
            packer.BeginPack();

            //字段名
            packer.AddField("operator_no", Convert.ToSByte('S'), 16, 4);
            packer.AddField("password", Convert.ToSByte('S'), 16, 4);
            packer.AddField("mac_address", Convert.ToSByte('S'), 32, 4);
            packer.AddField("ip_address", Convert.ToSByte('S'), 32, 4);
            packer.AddField("hd_volserial", Convert.ToSByte('S'), 10, 4);
            packer.AddField("op_station", Convert.ToSByte('S'), 255, 4);
            packer.AddField("authorization_id", Convert.ToSByte('S'), 64, 4);
            packer.AddField("login_time", Convert.ToSByte('S'), 6, 4);
            packer.AddField("verification_code", Convert.ToSByte('S'), 32, 4);

            //参数值
            packer.AddStr(user);
            packer.AddStr(pwd);
            packer.AddStr("mac");       //TODO: 使用真实数据替代
            packer.AddStr("ip");
            packer.AddStr("vol");
            packer.AddStr("op");
            packer.AddStr("");
            packer.AddStr("");
            packer.AddStr("");

            packer.EndPack();
            #endregion
            MessageManager.GetInstance().Add(MessageType.Warning, string.Format("Logon:mac,ip等信息为虚拟的"));

            int retcode = this.sendpacker(OptionFunction.Logon, packer, false);

            #region unpacker
            CT2UnPacker unpacker = getCallbackData(retcode);
            if (unpacker != null)
            {
                this.token = unpacker.GetStr("user_token");
                MessageManager.GetInstance().Add(MessageType.Information, string.Format("恒生系统登陆成功:{0}", this.token));
            }
            else
            {
                this.token = null;
                MessageManager.GetInstance().Add(MessageType.Error, string.Format("恒生系统登陆失败"));
            }
            #endregion
        }
Beispiel #9
0
        public override void OnReceivedBizMsg(CT2Connection lpConnection, int hSend, CT2BizMessage lpMsg)
        {
            logger.Info("OnReceivedBizMsg: 接收业务数据!");

            //获取返回码
            int iRetCode = lpMsg.GetReturnCode();

            //获取错误码
            int iErrorCode = lpMsg.GetErrorNo();

            int iFunction = lpMsg.GetFunction();

            if (iRetCode != 0)
            {
                logger.Error("异步接收数据出错:" + lpMsg.GetErrorNo().ToString() + lpMsg.GetErrorInfo());
            }
            else
            {
                CT2UnPacker unpacker = null;
                unsafe
                {
                    int   iLen   = 0;
                    void *lpdata = lpMsg.GetContent(&iLen);
                    unpacker = new CT2UnPacker(lpdata, (uint)iLen);
                }

                switch (iFunction)
                {
                case (int)FunctionCode.QueryTradingInstance:
                {
                }
                break;

                case (int)FunctionCode.EntrustInstanceBasket:
                    break;

                case (int)FunctionCode.QueryEntrustInstance:
                    break;

                case (int)FunctionCode.QueryDealInstance:
                    break;

                default:
                    break;
                }

                unpacker.Dispose();
            }

            lpMsg.Dispose();
        }
Beispiel #10
0
        public override void OnReceivedBizMsg(CT2Connection lpConnection, int hSend, CT2BizMessage lpMsg)
        {
            logger.Info("OnReceivedBizMsg: 接收业务数据!");

            //获取返回码
            int iRetCode = lpMsg.GetReturnCode();

            //获取错误码
            int iErrorCode = lpMsg.GetErrorNo();

            int iFunction = lpMsg.GetFunction();

            if (iRetCode != 0)
            {
                logger.Error("异步接收数据出错:" + lpMsg.GetErrorNo().ToString() + lpMsg.GetErrorInfo());
            }
            else
            {
                CT2UnPacker unpacker = null;
                unsafe
                {
                    int   iLen   = 0;
                    void *lpdata = lpMsg.GetContent(&iLen);
                    unpacker = new CT2UnPacker(lpdata, (uint)iLen);
                }

                switch (iFunction)
                {
                case (int)FunctionCode.Login:
                {
                    var token = unpacker.GetStr("user_token");
                    if (string.IsNullOrEmpty(token))
                    {
                        LoginManager.Instance.LoginUser.Token = token;
                    }
                }
                break;

                case (int)FunctionCode.Logout:
                    break;

                default:
                    break;
                }

                PrintUnPack(unpacker);
                unpacker.Dispose();
            }

            lpMsg.Dispose();
        }
Beispiel #11
0
        public void Subcribe(string user, string pwd)
        {
            subcallback = new UFXSubCallback(this);
            subcribe    = this.connMain.NewSubscriber(subcallback, "ufx_demo", 50000, 2000, 100);
            if (subcribe == null)
            {
                Debug.Print(string.Format("订阅创建失败 {0}", connMain.GetMCLastError()));
                return;
            }
            CT2SubscribeParamInterface args = new CT2SubscribeParamInterface();

            args.SetTopicName("ufx_topic");
            args.SetReplace(false);
            args.SetFilter("operator_no", user);

            CT2Packer req = new CT2Packer(2);

            req.BeginPack();
            req.AddField("login_operator_no", Convert.ToSByte('S'), 16, 4);
            req.AddField("password", Convert.ToSByte('S'), 16, 4);

            req.AddStr(user);
            req.AddStr(pwd);

            req.EndPack();

            CT2UnPacker unpacker = null;
            int         ret      = subcribe.SubscribeTopicEx(args, 50000, out unpacker, req);

            req.Dispose();
            if (ret > 0)
            {
                Debug.Print("订阅成功");
                subcribeid = ret;
            }
            else
            {
                if (unpacker != null)
                {
                    Debug.Print("订阅失败");
                    this.ShowUnPacker(unpacker);
                }
            }
        }
Beispiel #12
0
        //显示
        public void ShowUnPacker(CT2UnPacker lpUnPack)
        {
            int count = lpUnPack.GetDatasetCount();

            for (int k = 0; k < count; k++)
            {
                Debug.Print(string.Format("第[{0}]个数据集", k));
                lpUnPack.SetCurrentDatasetByIndex(k);
                String strInfo = string.Format("记录行数:           {0}", lpUnPack.GetRowCount());
                Debug.Print(strInfo);
                strInfo = string.Format("列行数:			 {0}", lpUnPack.GetColCount());
                Debug.Print(strInfo);
                while (lpUnPack.IsEOF() == 0)
                {
                    for (int i = 0; i < lpUnPack.GetColCount(); i++)
                    {
                        String colName = lpUnPack.GetColName(i);
                        sbyte  colType = lpUnPack.GetColType(i);
                        if (!colType.Equals('R'))
                        {
                            String colValue = lpUnPack.GetStrByIndex(i);
                            String str      = string.Format("{0}:			[{1}]", colName, colValue);
                            Debug.Print(str);
                        }
                        else
                        {
                            int colLength = 0;
                            unsafe
                            {
                                void * colValue = (char *)lpUnPack.GetRawByIndex(i, &colLength);
                                string str      = string.Format("{0}:			[{1}]({2})", colName, Marshal.PtrToStringAuto(new IntPtr(colValue)), colLength);
                            }
                        }
                    }
                    lpUnPack.Next();
                }
            }
        }
Beispiel #13
0
        private CT2UnPacker getCallbackData(int retcode)
        {
            //外部所指向的消息对象的内存由SDK内部管理,外部切勿释放
            CT2BizMessage lpMsg;

            this.connMain.RecvBizMsg(retcode, out lpMsg, 5000, 1);

            int errcode  = lpMsg.GetErrorNo();     //获取返回码
            int function = lpMsg.GetFunction();    //读取功能号

            if (errcode != 0)
            {
                MessageManager.GetInstance().Add(MessageType.Error, string.Format("操作失败:{0}", lpMsg.GetErrorInfo()));
                return(null);
            }

            CT2UnPacker unpacker = null;

            unsafe
            {
                int   iLen   = 0;
                void *lpdata = lpMsg.GetContent(&iLen);
                unpacker = new CT2UnPacker(lpdata, (uint)iLen);
            }

            int code = unpacker.GetInt("ErrorCode");

            if (code != 0)
            {
                string msg = unpacker.GetStr("ErrorMsg");
                MessageManager.GetInstance().Add(MessageType.Error, string.Format("操作失败:{0}", msg));
                return(null);
            }

            unpacker.SetCurrentDatasetByIndex(1);
            return(unpacker);
        }
Beispiel #14
0
        public void UnPack(CT2UnPacker lpUnPack)
        {
            var flag  = 0;
            var count = lpUnPack.GetRowCount();

            _showlist           = new ShowList();
            _showlist.ValueList = new List <string> [count];
            _showlist.NameList  = new List <string>();

            for (int i = 0; i < count; i++)
            {
                _showlist.ValueList[i] = new List <string>();
            }


            while (lpUnPack.IsEOF() != 1)
            {
                for (int j = 0; j < lpUnPack.GetColCount(); j++)
                {
                    var   colName = lpUnPack.GetColName(j);
                    sbyte colType = lpUnPack.GetColType(j);
                    if (colType != 'R')
                    {
                        var colValue = lpUnPack.GetStrByIndex(j);
                        if (flag == 0)
                        {
                            _showlist.NameList.Add(colName);
                        }
                        _showlist.ValueList[flag].Add(colValue);
                    }
                }

                lpUnPack.Next();
                flag++;
            }
            var aa = _showlist;
        }
        public void Parse(CT2UnPacker lpUnPack)
        {
            for (int i = 0, dsLen = lpUnPack.GetDatasetCount(); i < dsLen; i++)
            {
                RawDataSet dataSet = new RawDataSet();
                dataSet.Rows = new List <RawDataRow>();
                //设置当前结果集
                lpUnPack.SetCurrentDatasetByIndex(i);

                Dictionary <int, string> columnDic = new Dictionary <int, string>();
                //数据包中字段
                for (int j = 0, hLen = lpUnPack.GetColCount(); j < hLen; j++)
                {
                    columnDic.Add(j, lpUnPack.GetColName(j));
                }

                //所有记录
                for (int k = 0, rLen = (int)lpUnPack.GetRowCount(); k < rLen; k++)
                {
                    RawDataRow row = new RawDataRow();
                    row.Columns = new Dictionary <string, DataValue>();

                    //每条记录
                    for (int t = 0, cLen = lpUnPack.GetColCount(); t < cLen; t++)
                    {
                        string    colName   = columnDic[t];
                        DataValue dataValue = new DataValue();
                        switch (lpUnPack.GetColType(t))
                        {
                        case (sbyte)'I':      //I 整数
                        {
                            dataValue.Type  = DataValueType.Int;
                            dataValue.Value = lpUnPack.GetIntByIndex(t);
                        }
                        break;

                        case (sbyte)'C':      //C
                        {
                            dataValue.Type  = DataValueType.Char;
                            dataValue.Value = lpUnPack.GetCharByIndex(t);
                        }
                        break;

                        case (sbyte)'S':       //S
                        {
                            dataValue.Type  = DataValueType.String;
                            dataValue.Value = lpUnPack.GetStrByIndex(t);
                        }
                        break;

                        case (sbyte)'F':      //F
                        {
                            dataValue.Type  = DataValueType.Float;
                            dataValue.Value = lpUnPack.GetDoubleByIndex(t);
                        }
                        break;

                        case (sbyte)'R':      //R
                        {
                            break;
                        }

                        default:
                            // 未知数据类型
                            break;
                        }

                        if (!row.Columns.ContainsKey(colName))
                        {
                            row.Columns.Add(colName, dataValue);
                        }
                    }//end to read all column for each row

                    dataSet.Rows.Add(row);

                    Console.WriteLine();
                    lpUnPack.Next();
                }//end to read rows

                _dataSets.Add(dataSet);
            }
        }
Beispiel #16
0
 public override void OnReceivedBizEx(CT2Connection lpConnection, int hSend, CT2RespondData lpRetData, String lppStr, CT2UnPacker lppUnPacker, int nResult)
 {
 }
Beispiel #17
0
 public override void OnReceivedBizEx(CT2Connection lpConnection, int hSend, CT2RespondData lpRetData, string lppStr, CT2UnPacker lppUnPacker, int nResult)
 {
     Debug.Print(MethodBase.GetCurrentMethod().Name);
 }
Beispiel #18
0
        /// <summary>
        /// 通过调用UFX接口同步发送请求,并将结果封装在DataParser对象中返回。
        /// </summary>
        /// <param name="message">CT2BizMessage对象的实例,包含用户信息,功能号,请求参数等信息</param>
        /// <returns>DataParser对象实例,包含错误代码和最终数据。</returns>
        public DataParser SendSync2(CT2BizMessage message)
        {
            DataParser dataParser = new DataParser();

            int iRet = _conn.SendBizMsg(message, (int)SendType.Sync);

            if (iRet < 0)
            {
                string msg = string.Format("一般交易业务同步发送数据失败! 错误码:{0}, 错误消息:{1}", iRet, _conn.GetErrorMsg(iRet));
                logger.Error(msg);
                dataParser.ErrorCode = ConnectionCode.ErrorSendMsg;

                return(dataParser);
            }

            CT2BizMessage bizMessage = null;
            int           retCode    = _conn.RecvBizMsg(iRet, out bizMessage, (int)_timeOut, 1);

            if (retCode < 0)
            {
                string msg = "一般交易业务同步接收出错: " + _conn.GetErrorMsg(retCode);
                logger.Error(msg);
                dataParser.ErrorCode = ConnectionCode.ErrorRecvMsg;

                return(dataParser);
            }

            int iFunction = bizMessage.GetFunction();

            if (!Enum.IsDefined(typeof(UFXFunctionCode), iFunction))
            {
                dataParser.ErrorCode = ConnectionCode.ErrorNoFunctionCode;

                return(dataParser);
            }

            dataParser.FunctionCode = (UFXFunctionCode)iFunction;

            int             iRetCode     = bizMessage.GetReturnCode();
            int             iErrorCode   = bizMessage.GetErrorNo();
            UFXFunctionCode functionCode = (UFXFunctionCode)iFunction;

            if (iRetCode != 0)
            {
                string msg = string.Format("同步接收数据出错: {0}, {1}", iErrorCode, bizMessage.GetErrorInfo());
                //Console.WriteLine(msg);
                logger.Error(msg);

                dataParser.ErrorCode = ConnectionCode.ErrorRecvMsg;
                return(dataParser);
            }

            CT2UnPacker unpacker = null;

            unsafe
            {
                int   iLen   = 0;
                void *lpdata = bizMessage.GetContent(&iLen);
                unpacker = new CT2UnPacker(lpdata, (uint)iLen);
            }

            if (unpacker == null)
            {
                string msg = string.Format("提交UFX请求回调中,功能号[{0}]数据获取失败!", iFunction);
                logger.Error(msg);

                dataParser.ErrorCode = ConnectionCode.ErrorFailContent;
            }
            else
            {
                dataParser.Parse(unpacker);
                unpacker.Dispose();

                dataParser.ErrorCode = ConnectionCode.Success;
            }

            return(dataParser);
        }
Beispiel #19
0
        public void UpdateOrderBook(int iRet, List <OrderBook> orderbooklist)
        {
            //清除旧记录
            orderbooklist.Clear();

            //读取新记录
            CT2BizMessage lpMsg; //外部所指向的消息对象的内存由SDK内部管理,外部切勿释放

            this.connMain.RecvBizMsg(iRet, out lpMsg, 5000, 1);

            int iRetCode   = lpMsg.GetErrorNo();    //获取返回码
            int iErrorCode = lpMsg.GetReturnCode(); //获取错误码
            int iFunction  = lpMsg.GetFunction();

            if (iRetCode != 0)
            {
                Debug.Print("异步接收出错:" + lpMsg.GetErrorNo().ToString() + lpMsg.GetErrorInfo());
            }
            else
            {
                //读packer
                CT2UnPacker unpacker = null;
                unsafe
                {
                    int   iLen   = 0;
                    void *lpdata = lpMsg.GetContent(&iLen);
                    unpacker = new CT2UnPacker(lpdata, (uint)iLen);
                }

                //解析
                int count = unpacker.GetDatasetCount();
                for (int k = 1; k < count; k++)
                {
                    unpacker.SetCurrentDatasetByIndex(k);
                    while (unpacker.IsEOF() == 0)
                    {
                        OrderBook ob = new OrderBook();
                        switch (iFunction)
                        {
                        case 31004:     //持仓查询
                            ob.tradecode = unpacker.GetStr("stock_code");
                            ob.volume    = unpacker.GetInt("enable_amount");
                            string positionflag = unpacker.GetStr("position_flag");
                            ob.tradedirection = (positionflag == "1") ? TradeDirection.BUY : TradeDirection.SELL;
                            if (ob.volume > 0)
                            {
                                orderbooklist.Add(ob);
                            }
                            break;

                        case 32004:     //委托查询
                            ob.entrustno = unpacker.GetInt("entrust_no");
                            ob.tradecode = unpacker.GetStr("stock_code");
                            string entrustdirection = unpacker.GetStr("entrust_direction");     //1=买,2=卖,3=...,4=...;
                            string futuresdirection = unpacker.GetStr("futures_direction");     //1=开,2=平;
                            string entruststate     = unpacker.GetStr("entrust_state");         //委托状态
                            ob.tradedirection  = (entrustdirection == "1") ? TradeDirection.BUY : TradeDirection.SELL;
                            ob.futuredirection = (futuresdirection == "1") ? FutureDirection.OPEN : FutureDirection.COVER;
                            ob.price           = unpacker.GetDouble("entrust_price");
                            int entrustvol = unpacker.GetInt("entrust_amount");
                            int dealvol    = unpacker.GetInt("deal_amount");
                            ob.volume = entrustvol - dealvol;
                            switch (entruststate)
                            {
                            case "1":            //未报
                            case "4":            //已报
                            case "6":            //部成
                                orderbooklist.Add(ob);
                                break;

                            case "5":            //废单
                            case "7":            //已成
                            case "8":            //部撤
                            case "9":            //已撤
                            case "a":            //待撤
                            case "A":            //未撤
                            case "B":            //待撤
                            case "C":            //正撤
                            case "D":            //撤认
                            case "E":            //撤废
                            case "F":            //已撤
                                break;

                            default:
                                break;
                            }
                            break;

                        default:
                            break;
                        }
                        unpacker.Next();
                    }
                }
            }
        }
Beispiel #20
0
        public void SendFunctionAction(int functionId, string functionIdGenerationStr, Action <ShowList> callback)
        {
            CT2Esbmsg t2Message = new CT2Esbmsg();                               //构造消息

            t2Message.GetItem(CT2tag_def.TAG_FUNCTION_ID).SetInt(functionId, 0); //设置功能号
            t2Message.GetItem(CT2tag_def.TAG_PACKET_TYPE).SetInt(0, 0);;         //设置消息类型为请求
            //打包请求报文
            CT2Packer packer   = new CT2Packer(3);
            sbyte     strType  = Convert.ToSByte('S');
            sbyte     intType  = Convert.ToSByte('I');
            sbyte     charType = Convert.ToSByte('C');

            packer.BeginPack();
            //插件编号
            //管理功能号

            foreach (var item in _sendFunctionDtoList)
            {
                if (item.Type == "int")
                {
                    packer.AddField(item.Name, intType, 255, 4);
                }
                else if (item.Type == "string")
                {
                    packer.AddField(item.Name, strType, 255, 4);
                }
            }

            foreach (var item in _sendFunctionDtoList)
            {
                if (item.Type == "int")
                {
                    packer.AddInt(Convert.ToInt32(item.Value));
                }
                else if (item.Type == "string")
                {
                    packer.AddStr(item.Value);
                }
            }

            packer.EndPack();

            unsafe
            {
                t2Message.GetItem(CT2tag_def.TAG_MESSAGE_BODY).SetRawData(packer.GetPackBuf(), packer.GetPackLen());
                int   iMsgLen = 0;
                void *lpData  = t2Message.GetBuffer(&iMsgLen);
                int   iRet    = Conn.Send(lpData, iMsgLen, 0);
                if (iRet < 0)
                {
                    MessageBox.Show(Conn.GetErrorMsg(iRet));
                }
                else
                {
                    void *lpRecvData = null;
                    int   iRecvLen   = 0;
                    iRet = Conn.Receive(iRet, &lpRecvData, &iRecvLen, 5000, 0);
                    if (iRet == 0)
                    {
                        CT2Esbmsg ansMessage  = new CT2Esbmsg();                            //构造消息
                        int       iParseError = ansMessage.SetBuffer(lpRecvData, iRecvLen); //解析消息
                        if (iParseError != 0)
                        {
                            MessageBox.Show("同步接收业务错误:解析消息失败\n");
                        }
                        else
                        {
                            int iRetCode   = ansMessage.GetItem(CT2tag_def.TAG_RETURN_CODE).GetInt(0); //获取返回码
                            int iErrorCode = ansMessage.GetItem(CT2tag_def.TAG_ERROR_NO).GetInt(0);    //获取错误码
                            if (iErrorCode != 0)
                            {
                                MessageBox.Show("同步接收出错:" + ansMessage.GetItem(CT2tag_def.TAG_ERROR_NO).GetString(0) +
                                                ansMessage.GetItem(CT2tag_def.TAG_ERROR_INFO).GetString(0));
                            }
                            else
                            {
                                CT2UnPacker unpacker = null;
                                unsafe
                                {
                                    int   iLen   = 0;
                                    void *lpdata = ansMessage.GetItem(CT2tag_def.TAG_MESSAGE_BODY).GetRawData(&iLen, 0);
                                    unpacker = new CT2UnPacker(lpdata, (uint)iLen);
                                }
                                //返回业务错误
                                if (iRetCode != 0)
                                {
                                    MessageBox.Show("同步接收业务出错:\n");
                                    UnPack(unpacker);
                                }
                                //正常业务返回
                                else
                                {
                                    UnPack(unpacker);
                                    callback?.Invoke(_showlist);
                                }

                                unpacker.Dispose();
                            }
                        }
                        ansMessage.Dispose();
                    }
                    else
                    {
                        Conn.GetErrorMsg(iRet);
                    }
                }
            }
            t2Message.Dispose();
            packer.Dispose();
        }
Beispiel #21
0
        public ConnectionCode ReceivedBizMsg(int hSend, FunctionCode functionCode)
        {
            CT2BizMessage bizMessage = null;
            int           retCode    = _conn.RecvBizMsg(hSend, out bizMessage, (int)_timeOut, 1);

            if (retCode < 0)
            {
                logger.Error("同步接收出错: " + _conn.GetErrorMsg(retCode));
                return(ConnectionCode.ErrorConn);
            }

            int iRetCode   = bizMessage.GetReturnCode();
            int iErrorCode = bizMessage.GetErrorNo();

            if (iRetCode != 0)
            {
                string msg = string.Format("同步接收数据出错: {0}, {1}", iErrorCode, bizMessage.GetErrorInfo());

                return(ConnectionCode.ErrorConn);
            }

            CT2UnPacker unpacker = null;

            unsafe
            {
                int   iLen   = 0;
                void *lpdata = bizMessage.GetContent(&iLen);
                unpacker = new CT2UnPacker(lpdata, (uint)iLen);
            }

            if (unpacker != null)
            {
                PrintUnPack(unpacker);
                switch (functionCode)
                {
                case FunctionCode.Login:
                {
                    var token = unpacker.GetStr("user_token");
                    if (!string.IsNullOrEmpty(token))
                    {
                        LoginManager.Instance.LoginUser.Token = token;
                    }
                    else
                    {
                        return(ConnectionCode.ErrorLogin);
                    }
                }
                break;

                case FunctionCode.Logout:
                    break;

                case FunctionCode.HeartBeat:
                    break;

                default:
                    break;
                }

                unpacker.Dispose();
            }
            //bizMessage.Dispose();

            return(ConnectionCode.Success);
        }
Beispiel #22
0
 public override void OnReceivedBiz(CT2Connection lpConnection, int hSend, String lppStr, CT2UnPacker lppUnPacker, int nResult)
 {
     if (nResult == 0 || nResult == 1)
     {
         while (lppUnPacker.IsEOF() != 1)
         {
             for (int i = 0; i < lppUnPacker.GetColCount(); i++)
             {
                 m_lpOwner.DisplayText(lppUnPacker.GetStrByIndex(i));
             }
             lppUnPacker.Next();
         }
     }
     else if (nResult < 0)
     {
         m_lpOwner.DisplayText(lpConnection.GetErrorMsg(nResult));
     }
     else if (nResult == 2)
     {
         m_lpOwner.DisplayText("解包失败");
     }
 }
Beispiel #23
0
        public int OnReceivedBizMsg(CT2BizMessage bizMessage)
        {
            int iRetCode   = bizMessage.GetReturnCode();
            int iErrorCode = bizMessage.GetErrorNo();
            int iFunction  = bizMessage.GetFunction();

            if (iRetCode != 0)
            {
                string msg = string.Format("异步接收数据出错: {0}, {1}", iErrorCode, bizMessage.GetErrorInfo());

                return(iRetCode);
            }

            CT2UnPacker unpacker = null;

            unsafe
            {
                int   iLen   = 0;
                void *lpdata = bizMessage.GetContent(&iLen);
                unpacker = new CT2UnPacker(lpdata, (uint)iLen);
            }

            if (unpacker != null)
            {
                Console.WriteLine("功能号:" + iFunction);
                _t2SDKWrap.PrintUnPack(unpacker);

                switch ((FunctionCode)iFunction)
                {
                case FunctionCode.Entrust:
                {
                }
                break;

                case FunctionCode.Withdraw:
                {
                }
                break;

                case FunctionCode.EntrustBasket:
                {
                }
                break;

                case FunctionCode.WithdrawBasket:
                {
                }
                break;

                case FunctionCode.QuerySecurityEntrust:
                {
                }
                break;

                default:
                    break;
                }

                unpacker.Dispose();
            }
            //bizMessage.Dispose();

            return((int)ConnectionCode.Success);
        }
Beispiel #24
0
        public override void OptionPositionQuery(QueryPara param, List <PositionBook> positionbook)
        {
            try
            {
                if (!islogon())
                {
                    return;
                }

                #region packer
                CT2Packer packer = new CT2Packer(2);
                packer.BeginPack();
                packer.AddField("user_token", Convert.ToSByte('S'), 512, 4);
                packer.AddField("account_code", Convert.ToSByte('S'), 32, 4);
                packer.AddField("combi_no", Convert.ToSByte('S'), 8, 4);
                packer.AddField("stock_code", Convert.ToSByte('S'), 16, 4);

                packer.AddStr(this.token);
                packer.AddStr(param.fundcode);
                packer.AddStr(param.portfolio);
                packer.AddStr(param.securitycode);

                packer.EndPack();
                #endregion

                int retcode = this.sendpacker(OptionFunction.PositionQuery, packer, false);

                #region unpacker
                CT2UnPacker unpacker = getCallbackData(retcode);
                if (unpacker != null)
                {
                    //更新持仓
                    positionbook.Clear();
                    while (unpacker.IsEOF() == 0)
                    {
                        PositionBook pbook = new PositionBook();
                        pbook.code = unpacker.GetStr("stock_code");
                        int pflag = unpacker.GetInt("position_flag");
                        if (pflag == 1)
                        {
                            pbook.positiondirection = PostionDerection.LONG;
                        }
                        else
                        {
                            pbook.positiondirection = PostionDerection.SHORT;
                        }
                        pbook.volume = unpacker.GetInt("enable_amount");

                        //可能存在volume<=0的bug,所以筛选出为正的
                        if (pbook.volume > 0)
                        {
                            positionbook.Add(pbook);
                        }

                        unpacker.Next();
                    }
                }
                else
                {
                    MessageManager.GetInstance().Add(MessageType.Error, string.Format("持仓查询失败:{0}", param.securitycode));
                }
                #endregion
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Beispiel #25
0
 public override void OnReceivedBiz(CT2Connection lpConnection, int hSend, string lppStr, CT2UnPacker lppUnPacker, int nResult)
 {
 }
Beispiel #26
0
        public void PrintUnPack(CT2UnPacker lpUnPack)
        {
            Console.WriteLine("记录行数: {0}", lpUnPack.GetRowCount());
            Console.WriteLine("列行数:{0}", lpUnPack.GetColCount());

            for (int i = 0; i < lpUnPack.GetDatasetCount(); i++)
            {
                //设置当前结果集
                lpUnPack.SetCurrentDatasetByIndex(i);

                //打印字段
                for (int j = 0; j < lpUnPack.GetColCount(); j++)
                {
                    Console.Write("{0,20:G}", lpUnPack.GetColName(j));
                }

                Console.WriteLine();

                //打印所有记录
                for (int k = 0; k < lpUnPack.GetRowCount(); k++)
                {
                    //打印每条记录
                    for (int t = 0; t < lpUnPack.GetColCount(); t++)
                    {
                        switch (lpUnPack.GetColType(t))
                        {
                        case (sbyte)'I':      //I 整数
                            Console.Write("{0,20:D}", lpUnPack.GetIntByIndex(t));
                            break;

                        case (sbyte)'C':      //C
                            Console.Write("{0,20:G}", (char)lpUnPack.GetCharByIndex(t));
                            break;

                        case (sbyte)'S':       //S
                            Console.Write("{0,20:G}", lpUnPack.GetStrByIndex(t));
                            break;

                        case (sbyte)'F':      //F
                            Console.Write("{0,20:F2}", lpUnPack.GetDoubleByIndex(t));
                            break;

                        case (sbyte)'R':      //R
                        {
                            break;
                        }

                        default:
                            // 未知数据类型
                            Console.Write("未知数据类型\n");
                            break;
                        }
                    }

                    Console.WriteLine();
                    lpUnPack.Next();
                }
            }

            Console.WriteLine();


            /*
             * while (lpUnPack.IsEOF() != 1)
             * {
             *  for (int i = 0; i < lpUnPack.GetColCount(); i++)
             *  {
             *      String colName = lpUnPack.GetColName(i);
             *      sbyte colType = lpUnPack.GetColType(i);
             *      if (!colType.Equals('R'))
             *      {
             *          String colValue = lpUnPack.GetStrByIndex(i);
             *          Console.WriteLine("{0}:{1}", colName, colValue);
             *      }
             *      else
             *      {
             *          int colLength = 0;
             *          unsafe
             *          {
             *              void* colValue = (char*)lpUnPack.GetRawByIndex(i, &colLength);
             *              string str = String.Format("{0}:[{1}]({2})", colName, Marshal.PtrToStringAuto(new IntPtr(colValue)), colLength);
             *          }
             *      }
             *  }
             *  lpUnPack.Next();
             * }
             */
        }
        public void Parse(CT2UnPacker lpUnPack)
        {
            for (int i = 0; i < lpUnPack.GetDatasetCount(); i++)
            {
                DataSet dataSet = new DataSet();
                dataSet.Rows = new List <DataRow>();
                //设置当前结果集
                lpUnPack.SetCurrentDatasetByIndex(i);

                Dictionary <int, string> columnDic = new Dictionary <int, string>();
                //打印字段
                for (int j = 0; j < lpUnPack.GetColCount(); j++)
                {
                    columnDic.Add(j, lpUnPack.GetColName(j));
                }

                //打印所有记录
                for (int k = 0; k < lpUnPack.GetRowCount(); k++)
                {
                    DataRow row = new DataRow();
                    row.Columns = new Dictionary <string, DataValue>();

                    //打印每条记录
                    for (int t = 0; t < lpUnPack.GetColCount(); t++)
                    {
                        string colName = columnDic[t];
                        switch (lpUnPack.GetColType(t))
                        {
                        case (sbyte)'I':      //I 整数
                        {
                            DataValue dataValue = new DataValue
                            {
                                Type  = DataValueType.Int,
                                Value = lpUnPack.GetIntByIndex(t)
                            };


                            row.Columns.Add(colName, dataValue);
                        }
                        break;

                        case (sbyte)'C':      //C
                        {
                            DataValue dataValue = new DataValue
                            {
                                Type  = DataValueType.Char,
                                Value = lpUnPack.GetCharByIndex(t)
                            };


                            row.Columns.Add(colName, dataValue);
                        }
                        break;

                        case (sbyte)'S':       //S
                        {
                            DataValue dataValue = new DataValue
                            {
                                Type  = DataValueType.String,
                                Value = lpUnPack.GetStrByIndex(t)
                            };


                            row.Columns.Add(colName, dataValue);
                        }
                        break;

                        case (sbyte)'F':      //F
                        {
                            DataValue dataValue = new DataValue
                            {
                                Type  = DataValueType.Float,
                                Value = lpUnPack.GetDoubleByIndex(t)
                            };


                            row.Columns.Add(colName, dataValue);
                        }
                        break;

                        case (sbyte)'R':      //R
                        {
                            break;
                        }

                        default:
                            // 未知数据类型
                            break;
                        }
                    }//end to read all column for each row

                    dataSet.Rows.Add(row);

                    Console.WriteLine();
                    lpUnPack.Next();
                }//end to read rows

                _dataSets.Add(dataSet);
            }

            /*
             * while (lpUnPack.IsEOF() != 1)
             * {
             *  for (int i = 0; i < lpUnPack.GetColCount(); i++)
             *  {
             *      String colName = lpUnPack.GetColName(i);
             *      sbyte colType = lpUnPack.GetColType(i);
             *      if (!colType.Equals('R'))
             *      {
             *          String colValue = lpUnPack.GetStrByIndex(i);
             *          Console.WriteLine("{0}:{1}", colName, colValue);
             *      }
             *      else
             *      {
             *          int colLength = 0;
             *          unsafe
             *          {
             *              void* colValue = (char*)lpUnPack.GetRawByIndex(i, &colLength);
             *              string str = String.Format("{0}:[{1}]({2})", colName, Marshal.PtrToStringAuto(new IntPtr(colValue)), colLength);
             *          }
             *      }
             *  }
             *  lpUnPack.Next();
             * }
             */
        }
Beispiel #28
0
        private int HandleReceivedBizMsg(SendType sendType, UFXFunctionCode functionCode, int hSend, CT2BizMessage bizMessage)
        {
            int iRetCode   = bizMessage.GetReturnCode();
            int iErrorCode = bizMessage.GetErrorNo();
            int iFunction  = bizMessage.GetFunction();

            //FunctionCode functionCode = (FunctionCode)iFunction;
            if (iRetCode != 0)
            {
                string msg = string.Format("同步接收数据出错: {0}, {1}", iErrorCode, bizMessage.GetErrorInfo());
                logger.Error(msg);
                return(iRetCode);
            }

            CT2UnPacker unpacker = null;

            unsafe
            {
                int   iLen   = 0;
                void *lpdata = bizMessage.GetContent(&iLen);
                unpacker = new CT2UnPacker(lpdata, (uint)iLen);
            }

            int ret = (int)ConnectionCode.ErrorConn;

            if (unpacker == null)
            {
                ret = (int)ConnectionCode.ErrorFailContent;
                string msg = string.Format("提交UFX请求回调中,功能号[{0}]数据获取失败!", iFunction);
                logger.Error(msg);

                return(ret);
            }

            DataParser parser = new DataParser();

            parser.FunctionCode = functionCode;
            parser.Parse(unpacker);
            unpacker.Dispose();

            //parser.Output();
            if (!_dataHandlerMap.ContainsKey(functionCode))
            {
                ret = (int)ConnectionCode.ErrorNoCallback;
                string msg = string.Format("提交UFX请求时,未注册功能号[{0}]的回调方法!", iFunction);
                logger.Error(msg);

                return(ret);
            }

            var dataHandler = _dataHandlerMap[functionCode];

            if (dataHandler == null)
            {
                ret = (int)ConnectionCode.ErrorNoCallback;
                string msg = string.Format("提交UFX请求时,未注册功能号[{0}]的回调方法!", iFunction);
                logger.Error(msg);

                return(ret);
            }

            if (sendType == SendType.Sync)
            {
                return(dataHandler(functionCode, hSend, parser));
            }
            else
            {
                //TODO: control the maximum number of the thread?
                //Task task = new Task(() => dataHandler(parser));
                //task.Start();

                //use the TaskScheduler to limit the maximum thread number
                TaskFactory taskFactory = new TaskFactory(_taskScheduler);
                taskFactory.StartNew(() => dataHandler(functionCode, hSend, parser));

                return((int)ConnectionCode.Success);
            }
        }
Beispiel #29
0
 public override void OnReceivedBizEx(CT2Connection lpConnection, int hSend, CT2RespondData lpRetData, string lppStr, CT2UnPacker lppUnPacker, int nResult)
 {
     throw new NotImplementedException();
 }
Beispiel #30
0
 public override void OnReceivedBizEx(CT2Connection lpConnection, int hSend, CT2RespondData lpRetData, string lppStr, CT2UnPacker lppUnPacker, int nResult)
 {
     UFXLogger.Info(logger, "OnReceivedBizEx:成功触发回调接收数据!");
 }