예제 #1
0
        private void threadproc()
        {
            while (true)
            {
                Thread.Sleep(1);

                if ((DateTime.Now - GlobalHeartBeat.GetGlobalTime()).TotalMinutes > 5)
                {
                    log.LogEvent("由于供血不足,委托查询线程即将退出。");
                    break;
                }

                //单次循环最多查询100个交易的委托情况
                int maxCount = 100;

                if (!_classTradeStock.getConnectStatus())
                {
                    _classTradeStock.Init(login, ErrorMsg);
                }

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


                while (maxCount > 0 && queue_query_entrust.GetQueueNumber() > 0)
                {
                    maxCount--;

                    //获取新委托
                    QueryEntrustOrderStruct_M item = (QueryEntrustOrderStruct_M)queue_query_entrust.GetQueue().Dequeue();
                    string err = string.Empty;

                    //查询委托及获取实例
                    managedEntrustreturnstruct ret = new managedEntrustreturnstruct();

                    //ordersysid 首字母 为 'T'  是测试交易
                    if (item.OrderSysID.Length > 0 && item.OrderSysID[0] == 'T')
                    {
                        var temps = test.QueryEntrust(item);
                        ret = temps;
                    }
                    else
                    {
                        var temps = _classTradeStock.QueryEntrust(item, err);
                        if (temps.Length == 0)
                        {
                            continue;
                        }

                        ret = temps.ToList()[0];
                    }

                    if (ret == null)
                    {
                        continue;
                    }


                    OrderViewItem order = new OrderViewItem(
                        item.OrderRef.ToString(),
                        ret.cOrderSysID,
                        ret.cSecurity_code,
                        item.Direction.ToString(),
                        "NA",
                        ret.nVolumeTotalOriginal.ToString(),
                        ret.nVolumeTotal.ToString(),
                        item.OrderPrice.ToString(),
                        GetStatusWord(ret.cOrderStatus),
                        ret.cInsertTime);


                    if (!UserRequestMap.GetInstance().Keys.Contains(item.OrderRef))
                    {
                        UserRequestMap.GetInstance().AddOrUpdate(item.OrderRef, item.User, (key, oldValue) => oldValue = item.User);
                    }

                    String USERNAME = UserRequestMap.GetInstance()[item.OrderRef];
                    TradeMonitor.Instance.updateOrderList(USERNAME, order);


                    //目前仅考虑 1对1 返回的情况,不考虑出现1对多 ,类似基金交易的情况
                    //将委托变动返回更新数据库
                    if (DBAccessLayer.DBEnable == true)
                    {
                        //更新数据,记录入数据库
                        ThreadPool.QueueUserWorkItem(new WaitCallback(DBAccessLayer.UpdateERRecord), (object)(ret));

                        //修改委托缓存数据
                        EntrustRecord.ModifyEntrustPosition(item.OrderRef, Convert.ToInt32(ret.frozen_amount), Convert.ToDouble(ret.frozen_money));

                        //此处判断,相应代码的委托是否完成
                        //此处逻辑需要待返回报文内容确认后修改
                        //测试使用
                        if ((ret.cOrderStatus.ToString() != ((int)(EntrustStatus.Dealed)).ToString()) && (!(ret.cOrderStatus.ToString() == ((int)EntrustStatus.Canceled).ToString() && ret.nVolumeTotal == 0)))
                        {
                            queue_query_entrust.GetQueue().Enqueue((object)item);
                            continue;
                        }



                        //委托已经完成,进入成交状态查询
                        managedBargainreturnstruct bargin = new managedBargainreturnstruct();
                        if (item.OrderSysID.Length > 0 && item.OrderSysID[0] == 'T')
                        {
                            bargin = test.QueryTrader(item);
                        }
                        else
                        {
                            var retbargin = _classTradeStock.QueryTrader(item, err).ToList();
                            //将查询信息记录成交表
                            if (retbargin.Count > 0)
                            {
                                bargin = retbargin.ToList()[0];
                            }
                        }

                        bargin.strategyId = item.StrategyId;
                        bargin.direction  = item.Direction;
                        bargin.User       = USERNAME;
                        bargin.OrderType  = Convert.ToSByte("49");

                        if (ret.cOrderStatus.ToString() == ((int)(EntrustStatus.Dealed)).ToString())
                        {
                            bargin.OrderMark = Deal_Status.DEAL;
                        }
                        else if (ret.cOrderStatus.ToString() == ((int)EntrustStatus.Canceled).ToString())
                        {
                            bargin.OrderMark = Deal_Status.CANCELED;
                        }
                        else if (ret.nVolumeTotal == 0)
                        {
                            bargin.OrderMark = Deal_Status.PARTIALDEAL;
                        }


                        ThreadPool.QueueUserWorkItem(new WaitCallback(DBAccessLayer.CreateDLRecord), (object)bargin);

                        EntrustRecord.DeleteEntrustRecord(item.OrderRef);

                        ThreadPool.QueueUserWorkItem(new WaitCallback(DBAccessLayer.DeleteERRecord), (object)(item.OrderRef));

                        //更新持仓列表

                        if (ret.nVolumeTraded != 0)
                        {
                            //需要修改数据
                            //仅存在成交记录时才更改持仓
                            ThreadPool.QueueUserWorkItem(new WaitCallback(DBAccessLayer.UpdateCCRecords), (object)bargin);
                        }
                    }
                }
            }
        }
예제 #2
0
        /// <summary>
        /// 线程工作函数
        /// </summary>
        private void _threadProc()
        {
            while (!bRun)
            {
                //标记最后扫描时间,交付上级判断
                RunningMark = DateTime.Now;

                //尚未运行的策略,直接丢弃队列中新的行情
                while (_marketQueue.Count > 0)
                {
                    DeQueueInfo();
                }
                //标记线程状态为正在空转
                Status = 1;

                Thread.Sleep(10);
            }

            if (DBAccessLayer.DBEnable)
            {
                DBAccessLayer.UpdateStrategyStatusRecord(StrategyInstanceID, 1);
            }

            while (!breaklabel)
            {
                /****
                 * 循环工作:
                 * 1. 更新行情信息
                 * 2. 计算中间参数
                 * 3. 判断运行条件
                 * 4. 生成交易列表
                 * ****/

                //标记最后扫描时间,交付上级判断
                RunningMark = DateTime.Now;

                if (Status == 1)
                {
                    if (DBAccessLayer.DBEnable)
                    {
                        DBAccessLayer.UpdateStrategyStatusRecord(StrategyInstanceID, 2);
                    }
                }
                if (bRun)
                {
                    //标记线程状态为正在运行
                    Status = 2;
                    Thread.Sleep(1);

                    //策略实例运算
                    List <managedMarketInforStruct> infos = new List <managedMarketInforStruct>();
                    List <MarketData> dataList            = new List <MarketData>();


                    while (_marketQueue.Count > 0)
                    {
                        MarketData d = (MarketData)DeQueueInfo();


                        if (d == null)
                        {
                            Thread.Sleep(10);
                            continue;
                        }

                        dataList.Add(d);
                    }



                    foreach (MarketData data in dataList)
                    {
                        managedMarketInforStruct info = new managedMarketInforStruct();

                        info.dAskPrice = new double[10];
                        info.dAskVol   = new double[10];
                        info.dBidPrice = new double[10];
                        info.dBidVol   = new double[10];

                        if (data.AskPrice != null)
                        {
                            for (int i = 0; i < data.AskPrice.Count(); i++)
                            {
                                info.dAskPrice[i] = Convert.ToDouble(data.AskPrice[i]) / 10000;
                                info.dAskVol[i]   = Convert.ToDouble(data.AskVol[i]);
                                info.dBidPrice[i] = Convert.ToDouble(data.BidPrice[i]) / 10000;
                                info.dBidVol[i]   = Convert.ToDouble(data.BidVol[i]);
                            }
                        }

                        managedsecurityindex index = new managedsecurityindex();
                        index.cSecurity_code = data.Code;


                        info.msecurity     = index;
                        info.security_name = data.Code;
                        info.nTime         = data.Time / 1000;
                        info.nStatus       = data.Status;
                        info.nPreClose     = Convert.ToDouble(data.PreClose) / 10000;
                        info.dLastPrice    = Convert.ToDouble(data.Match) / 10000;
                        info.dHighLimited  = Convert.ToDouble(data.HighLimited) / 10000;
                        info.dLowLimited   = Convert.ToDouble(data.LowLimited) / 10000;
                        info.exchangeID    = data.WindCode.Split('.')[1];

                        if (data.Status == 68)
                        {
                            info.bstoped = true;
                        }

                        switch (data.IOPV)
                        {
                        case 0:
                        {
                            index.cSecuritytype = 115;
                            break;
                        }

                        case 1:
                        {
                            index.cSecuritytype = 102;
                            break;
                        }

                        case 2:
                        {
                            index.cSecuritytype = 105;
                            break;
                        }
                        }
                        info.LastUpdateTime = Int32.Parse(DateTime.Now.Hour.ToString().PadLeft(2, '0') + DateTime.Now.Minute.ToString().PadLeft(2, '0') + DateTime.Now.Second.ToString().PadLeft(2, '0'));

                        //MarketDelayCalculation.cal(data.Time, 3);
                        if (data.Status == 68 || data.Status == 66)
                        {
                            info.bstoped = true;
                        }
                        else
                        {
                            info.bstoped = false;
                        }

                        info.nInfotLag = info.LastUpdateTime - info.nTime;
                        infos.Add(info);
                    }



                    if (infos.Count > 0)
                    {
                        if (Type == "OPEN")
                        {
                            DateTime d1 = DateTime.Now;

                            m_strategy_open.updateSecurityInfo(infos.ToArray(), infos.Count);

                            d1 = DateTime.Now;

                            m_strategy_open.calculateSimTradeStrikeAndDelta();
                        }
                        else
                        {
                            m_strategy_close.updateSecurityInfo(infos.ToArray(), infos.Count);
                            m_strategy_close.calculateSimTradeStrikeAndDelta();
                        }
                    }
                    else
                    {
                        continue;
                    }
                }



                if (bRun && bAllow)
                {
                    bool _reached = false;
                    if (Type == "OPEN")
                    {
                        _reached = m_strategy_open.isOpenPointReached();
                    }
                    else
                    {
                        _reached = m_strategy_close.isOpenPointReached();
                    }


                    //  _reached = true; //测试使用,注意删除

                    // 生成交易列表
                    if (_reached)
                    {
                        List <managedTraderorderstruct> ol = (Type == "OPEN") ? m_strategy_open.getTradeList().ToList() : m_strategy_close.getTradeList().ToList();



                        //交易列表送往交易线程下单(下单的线程,股票和期货是分开的)
                        List <TradeOrderStruct> orderli = new List <TradeOrderStruct>();

                        foreach (managedTraderorderstruct item in ol)
                        {
                            TradeOrderStruct order = new TradeOrderStruct();
                            order.cExhcnageID     = item.cExchangeID;
                            order.cSecurityCode   = item.cSecurity_code;
                            order.SecurityName    = item.cSecurity_code;
                            order.nSecurityAmount = item.nSecurity_amount;
                            order.dOrderPrice     = item.dOrderprice;
                            order.cTradeDirection = item.cTraderdirection.ToString();
                            order.cOffsetFlag     = item.cOffsetFlag.ToString();
                            order.cOrderPriceType = item.cOrderPriceType.ToString();

                            order.cSecurityType       = item.cSecuritytype.ToString();
                            order.cOrderLevel         = item.cOrderlevel.ToString();
                            order.cOrderexecutedetail = item.cOrderexecutedetail.ToString();
                            order.belongStrategy      = StrategyInstanceID;
                            order.OrderRef            = REQUEST_ID.ApplyNewID();
                            order.cUser = User;

                            orderli.Add(order);

                            UserRequestMap.GetInstance().AddOrUpdate(order.OrderRef, User, (key, oldvalue) => oldvalue = User);
                        }

                        if (DBAccessLayer.DBEnable == true)
                        {
                            string json = Json.Encode(orderli);
                            DBAccessLayer.InsertORDERLIST(StrategyInstanceID, json);
                        }

                        //提交风控模块

                        //下单到交易预处理模块
                        queue_prd_trade.GetQueue().Enqueue((object)orderli);

                        if (DBAccessLayer.DBEnable)
                        {
                            //写入数据库,策略状态为已下单
                            DBAccessLayer.UpdateStrategyStatusRecord(StrategyInstanceID, 3);
                            DBAccessLayer.UpdateSGOPENStatus(StrategyInstanceID, 3);
                        }


                        // 列表只会生成一次
                        breaklabel = true;
                    }
                }

                //获取中间显示参数
                //gettaderargs   getshowstatus

                if (Type == "OPEN")
                {
                    string status = m_strategy_open.getshowstatus();

                    List <String> statusLi = status.Split(' ').ToList();

                    status = string.Empty;

                    foreach (string i in statusLi)
                    {
                        if (i.Trim() != string.Empty)
                        {
                            status += (i + "&");
                        }
                    }

                    PushStrategyInfo.Instance.UpdateStrategyInfo(StrategyInstanceID, status);
                }
                else
                {
                    string status = m_strategy_close.getshowstatus();

                    List <string> statusLi = status.Split(' ').ToList();

                    status = string.Empty;

                    foreach (string i in statusLi)
                    {
                        if (i.Trim() != string.Empty)
                        {
                            status += (i + "&");
                        }
                    }

                    PushStrategyInfo.Instance.UpdateStrategyInfo(StrategyInstanceID, status);
                }
                Thread.Sleep(1);
            }
        }