Ejemplo n.º 1
0
        public static void RtnTradeProc(object trade)
        {
            CThostFtdcTradeField_M pTrade = (CThostFtdcTradeField_M)trade;

            lock (syncRtnTradeObject)
            {
                TradeRecord.GetInstance().UpdateTrade(Convert.ToInt16(pTrade.OrderRef), pTrade.Volume, Convert.ToDecimal(pTrade.Price), pTrade.TradeID);
            }
        }
Ejemplo n.º 2
0
 /// <summary>
 /// 交易提交出现问题回掉函数
 /// </summary>
 /// <param name="pInputOrder"></param>
 /// <param name="pRspInfo"></param>
 /// <param name="nRequestID"></param>
 /// <param name="bIsLast"></param>
 public static void _client_RspOrderInsert(CTP_CLI.CThostFtdcInputOrderField_M pInputOrder, CTP_CLI.CThostFtdcRspInfoField_M pRspInfo, int nRequestID, bool bIsLast)
 {
     TradeRecord.GetInstance().MarkFailure(Convert.ToInt16(pInputOrder.OrderRef), pRspInfo.ErrorMsg);
     if (pInputOrder.CombOffsetFlag_0 == (byte)(FutureTradeOffSet.Open))
     {
         //只有开仓涉及冻结资金
         //交易失败,需要释放冻结掉的期货交易资金
         accountMonitor.UpdateRiskFrozonAccount(pInputOrder.UserID, pInputOrder.InstrumentID, pInputOrder.VolumeTotalOriginal * (-1), pInputOrder.VolumeTotalOriginal * pInputOrder.LimitPrice * (-1), "F", pInputOrder.Direction.ToString());
     }
 }
Ejemplo n.º 3
0
        public void Delete(int OrderRef, RecordItem Record)
        {
            //交易完成或者失败情况下才会记录数据库,清除正在交易列表
            if (Record.Status == TradeDealStatus.ORDERCOMPLETED || Record.Status == TradeDealStatus.ORDERFAILURE)
            {
                int _k = 0; //尝试删除次数

                while (_k < 5)
                {
                    if (TradeRecord.GetInstance().TryRemove(OrderRef, out Record))
                    {
                        _k = 6;
                    }
                    _k++;
                }

                if (DBAccessLayer.DBEnable == true)
                {
                    //TODO : 更新数据库
                }
            }
        }
Ejemplo n.º 4
0
        public static void RtnOrderProc(object order)
        {
            CThostFtdcOrderField_M pOrder = (CThostFtdcOrderField_M)order;

            lock (syncRtnOrderObject)
            {
                switch (pOrder.OrderStatus)
                {
                case 48:
                {
                    //全部成交
                    TradeRecord.GetInstance().UpdateOrder(pOrder.VolumeTraded, Convert.ToInt16(pOrder.OrderRef), pOrder.OrderSysID, pOrder.StatusMsg, pOrder.OrderStatus, pOrder.VolumeTotal, pOrder.ExchangeID);

                    if (pOrder.CombOffsetFlag_0 == (byte)(FutureTradeOffSet.Open))
                    {
                        //只有开仓涉及冻结资金
                        //交易失败,需要释放冻结掉的期货交易资金
                        accountMonitor.UpdateRiskFrozonAccount(pOrder.UserID, pOrder.InstrumentID, pOrder.VolumeTotalOriginal * (-1), pOrder.VolumeTotalOriginal * pOrder.LimitPrice * (-1), "F", pOrder.Direction.ToString());
                    }
                }
                break;

                case 49:
                {
                    //部分成交
                    TradeRecord.GetInstance().UpdateOrder(pOrder.VolumeTraded, Convert.ToInt16(pOrder.OrderRef), pOrder.OrderSysID, pOrder.StatusMsg, pOrder.OrderStatus, pOrder.VolumeTotal, pOrder.ExchangeID);
                }
                break;

                case 51:
                {
                    //未成交状态
                    TradeRecord.GetInstance().UpdateOrder(pOrder.VolumeTraded, Convert.ToInt16(pOrder.OrderRef), pOrder.OrderSysID, pOrder.StatusMsg, pOrder.OrderStatus, pOrder.VolumeTotal, pOrder.ExchangeID);
                }
                break;

                case 53:
                {
                    //已撤单状态
                    TradeRecord.GetInstance().UpdateOrder(pOrder.VolumeTraded, Convert.ToInt16(pOrder.OrderRef), pOrder.OrderSysID, pOrder.StatusMsg, pOrder.OrderStatus, pOrder.VolumeTotal, pOrder.ExchangeID);
                }
                break;

                case 97:
                {
                    //报单已经提交,创建委托记录
                    if (CONFIG.CheckOrderRefAvailiable(Convert.ToInt16(pOrder.OrderRef)))
                    {
                        // 重复返回不需要记库
                        TradeRecord.GetInstance().SubscribeOrder("1", pOrder.InstrumentID, Convert.ToChar(pOrder.Direction).ToString(), pOrder.VolumeTotalOriginal, Convert.ToDecimal(pOrder.LimitPrice), Convert.ToInt16(pOrder.OrderRef), pOrder.OrderStatus, pOrder.CombOffsetFlag_0);
                    }
                }
                break;

                default:
                {
                    //如果是没有见过的状态,则默认更新委托信息
                    TradeRecord.GetInstance().UpdateOrder(pOrder.VolumeTraded, Convert.ToInt16(pOrder.OrderRef), pOrder.OrderSysID, pOrder.StatusMsg, pOrder.OrderStatus, pOrder.VolumeTotal, pOrder.ExchangeID);
                }
                break;
                }
            }
        }
Ejemplo n.º 5
0
        /// <summary>
        /// 期货交易工作线程
        /// </summary>
        /// <param name="para"></param>
        public void FutureTradeSubThreadProc(object para)
        {
            string ErrorMsg = string.Empty;

            //令该线程为前台线程
            Thread.CurrentThread.IsBackground = true;

            DateTime lastmessagetime = DateTime.Now;

            TradeParaPackage _tpp = (TradeParaPackage)para;

            //当前线程编号
            int _threadNo = _tpp._threadNo;

            sublog.LogEvent("线程 :" + _threadNo.ToString() + " 开始执行");

            //用作发送心跳包的时间标记
            DateTime _markedTime = DateTime.Now;

            //控制期货交易线程执行
            bool _threadRunControl = true;

            //获取未成交期货委托
            List <ER_TAOLI_TABLE> ERs = DBAccessLayer.GetInCompletedERRecord("F");

            if (ERs != null)
            {
                foreach (ER_TAOLI_TABLE ER in ERs)
                {
                    decimal price = (ER.ER_VOLUME_TOTAL_ORIGINAL == 0 ? 0 : Convert.ToDecimal(ER.ER_FROZEN_MONEY / ER.ER_VOLUME_TOTAL_ORIGINAL));
                    string  code  = ER.ER_CODE;

                    TradeRecord.GetInstance().SubscribeIncompleteOrder("F", ER.ER_CODE, ER.ER_ID, ER.ER_DIRECTION.ToString(), Convert.ToInt16(ER.ER_VOLUME_TOTAL_ORIGINAL), price, Convert.ToInt16(ER.ER_ORDER_REF), Convert.ToInt16("0"), Convert.ToInt16(ER.ER_OFFSETFLAG.Trim()), ER.ER_USER);
                }
            }

            while (_threadRunControl)
            {
                //初始化完成前,不接收实际交易
                queue_future_excuteThread.SetThreadBusy(_threadNo);

                _client.Connect();

                //状态 DISCONNECTED -> CONNECTED
                while (status != FutureTradeThreadStatus.CONNECTED)
                {
                    Thread.Sleep(10);
                }

                _client.ReqUserLogin();

                //状态 CONNECTED -> LOGIN
                while (status != FutureTradeThreadStatus.LOGIN)
                {
                    Thread.Sleep(10);
                }


                if (ERs != null)
                {
                    foreach (ER_TAOLI_TABLE ER in ERs)
                    {
                        _client.QryOrder(ER.ER_ORDER_EXCHANGE_ID, "", "", "", ER.ER_ID.PadLeft(12));
                    }
                }

                while (true)
                {
                    Thread.Sleep(10);

                    if ((DateTime.Now - GlobalHeartBeat.GetGlobalTime()).TotalMinutes > 10)
                    {
                        sublog.LogEvent("线程 :" + _threadNo.ToString() + "心跳停止 , 最后心跳 : " + GlobalHeartBeat.GetGlobalTime().ToString());
                        _threadRunControl = false;
                        break;
                    }

                    if (lastmessagetime.Second != DateTime.Now.Second)
                    {
                        KeyValuePair <string, object> message1 = new KeyValuePair <string, object>("THREAD_FUTURE_TRADE_WORKER", (object)_threadNo);
                        queue_system_status.GetQueue().Enqueue((object)message1);
                    }

                    if (queue_future_excuteThread.GetQueue(_threadNo).Count < 2)
                    {
                        queue_future_excuteThread.SetThreadFree(_threadNo);
                        status = FutureTradeThreadStatus.FREE;
                    }
                    else
                    {
                        status = FutureTradeThreadStatus.BUSY;
                    }

                    if (queue_future_excuteThread.GetQueue(_threadNo).Count > 0)
                    {
                        List <TradeOrderStruct> trades = (List <TradeOrderStruct>)queue_future_excuteThread.FutureExcuteQueue[_threadNo].Dequeue();
                        if (trades == null)
                        {
                            continue;
                        }
                        if (trades.Count > 0)
                        {
                            sublog.LogEvent("线程 :" + _threadNo.ToString() + " 执行交易数量 : " + trades.Count);
                        }

                        if (trades.Count == 0)
                        {
                            continue;
                        }

                        foreach (TradeOrderStruct order in trades)
                        {
                            CTP_CLI.CThostFtdcInputOrderField_M args = new CThostFtdcInputOrderField_M();

                            //填写委托参数

                            args.BrokerID            = CommConfig.BROKER;
                            args.InvestorID          = CommConfig.INVESTOR;
                            args.InstrumentID        = order.cSecurityCode;
                            args.Direction           = Convert.ToByte(order.cTradeDirection);
                            args.CombOffsetFlag_0    = Convert.ToByte(order.cOffsetFlag);
                            args.VolumeTotalOriginal = Convert.ToInt16(order.nSecurityAmount);
                            args.LimitPrice          = Convert.ToDouble(order.dOrderPrice);
                            args.OrderRef            = order.OrderRef.ToString();
                            args.OrderPriceType      = Convert.ToByte("50");
                            args.CombHedgeFlag_0     = Convert.ToByte('1');
                            args.MinVolume           = 1;
                            args.ContingentCondition = Convert.ToByte('1');
                            args.TimeCondition       = Convert.ToByte('3');
                            args.VolumeCondition     = Convert.ToByte('1');
                            args.UserID           = order.cUser;
                            args.ForceCloseReason = Convert.ToByte('0');
                            args.IsAutoSuspend    = 0;
                            args.UserForceClose   = 0;

                            //提交报单委托
                            //步骤完成后线程任务结束
                            //返回工作交由回调函数处理
                            _client.OrderInsert(args);

                            //创建记录
                            RecordItem item = new RecordItem();
                            item.AveragePrice        = 0;
                            item.Code                = order.cSecurityCode;
                            item.CombOffsetFlag      = Convert.ToInt16(order.cOffsetFlag);
                            item.OrderRef            = order.OrderRef;
                            item.OrderStatus         = 0;
                            item.OrderSysID          = "0";
                            item.Orientation         = order.cTradeDirection;
                            item.Price               = Convert.ToDecimal(order.dOrderPrice);
                            item.Status              = TradeDealStatus.ORDERING;
                            item.StrategyId          = order.belongStrategy;
                            item.Type                = "1";
                            item.VolumeTotalOriginal = item.VolumeTotal = Convert.ToInt32(order.nSecurityAmount);
                            item.VolumeTraded        = 0;
                            item.User                = order.cUser;


                            TradeRecord.GetInstance().CreateOrder(order.OrderRef, item);
                        }
                    }
                }
            }
        }