Пример #1
0
        /// <summary>
        /// 预处理线程启动
        /// </summary>
        private static void ThreadProc()
        {
            log.LogEvent("交易预处理线程开始执行");


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

                /*****************************
                 * 生成交易List之前的例行工作
                 * **************************/

                #region 策略生成交易队列
                List <TradeOrderStruct> tos = PreTradeModule.instance.DeQueue();


                if (tos != null)
                {
                    log.LogEvent("来自策略的交易数:" + tos.Count.ToString());

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

                    string user       = tos[0].cUser;
                    string strategyid = tos[0].belongStrategy;

                    //风控检测
                    string result = string.Empty;
                    bool   brisk  = riskmonitor.RiskDetection(user, tos, out result);


                    //DBAccessLayer.AddRiskRecord(user, result, strategyid, "00", 0, 0, "0");

                    //List<RISK_TABLE> risks = DBAccessLayer.GetRiskRecord(user);

                    //int count = 0;

                    //if (risks.Count > 0)
                    //{
                    //    List<TMRiskInfo> riskinfos = new List<TMRiskInfo>();

                    //    foreach (RISK_TABLE risk in risks)
                    //    {
                    //        count++;
                    //        if (count > 10) break;
                    //        riskinfos.Add(new TMRiskInfo() { code = risk.code, hand = risk.amount.ToString(), price = risk.price.ToString(), orientation = risk.orientation, time = risk.time.ToString(), strategy = "00", user = risk.alias, errinfo = risk.err });
                    //    }


                    //    TradeMonitor.Instance.updateRiskList(user, JsonConvert.SerializeObject(riskinfos), JsonConvert.SerializeObject(riskmonitor.riskPara));

                    //}



                    if (!brisk)
                    {
                        continue;
                    }

                    //获取到新的list
                    List <TradeOrderStruct> stocks_sh = (from item in tos where item.cExhcnageID == ExchangeID.SH select item).OrderBy(i => i.cOrderLevel).ToList();

                    List <TradeOrderStruct> stocks_sz = (from item in tos where item.cExhcnageID == ExchangeID.SZ select item).OrderBy(i => i.cOrderLevel).ToList();

                    List <TradeOrderStruct> future = (from item in tos where item.cExhcnageID == ExchangeID.CF select item).OrderBy(i => i.cOrderLevel).ToList();

                    //将新的list推送到对应的线程控制器
                    #region 交易送入队列

                    List <TradeOrderStruct> unit = new List <TradeOrderStruct>();

                    #region SH股票交易送入队列
                    if (stocks_sh.Count > 0)
                    {
                        log.LogEvent("上海交易所入队交易数量:" + stocks_sh.Count.ToString());

                        foreach (TradeOrderStruct stu in stocks_sh)
                        {
                            TradeOrderStruct _tos = CreateNewTrade(stu);
                            unit.Add(_tos);

                            if (unit.Count == 15)
                            {
                                List <TradeOrderStruct> _li = CreateList(unit);
                                unit.Clear();

                                lock (QUEUE_SH_TRADE.GetQueue().SyncRoot)
                                {
                                    QUEUE_SH_TRADE.GetQueue().Enqueue((object)_li);
                                }
                            }
                        }

                        if (unit.Count != 0)
                        {
                            List <TradeOrderStruct> _li = CreateList(unit);
                            unit.Clear();

                            lock (QUEUE_SH_TRADE.GetQueue().SyncRoot)
                            {
                                QUEUE_SH_TRADE.GetQueue().Enqueue((object)_li);
                            }
                        }
                    }
                    #endregion

                    #region SZ股票交易送入队列
                    if (stocks_sz.Count > 0)
                    {
                        log.LogEvent("深圳交易所入队交易数量:" + stocks_sz.Count.ToString());
                        foreach (TradeOrderStruct stu in stocks_sz)
                        {
                            TradeOrderStruct _tos = CreateNewTrade(stu);
                            unit.Add(_tos);

                            if (unit.Count == 15)
                            {
                                List <TradeOrderStruct> _li = CreateList(unit);
                                unit.Clear();

                                lock (QUEUE_SZ_TRADE.GetQueue().SyncRoot)
                                {
                                    QUEUE_SZ_TRADE.GetQueue().Enqueue((object)_li);
                                }

                                unit.Clear();
                            }
                        }

                        if (unit.Count != 0)
                        {
                            List <TradeOrderStruct> _li = CreateList(unit);
                            unit.Clear();

                            lock (QUEUE_SZ_TRADE.GetQueue().SyncRoot)
                            {
                                QUEUE_SZ_TRADE.GetQueue().Enqueue((object)_li);
                            }

                            //unit.Clear();
                        }
                    }
                    #endregion

                    #region 期货交易送入队列
                    if (future.Count > 0)
                    {
                        log.LogEvent("期货交易入队交易数量:" + future.Count.ToString());
                        foreach (TradeOrderStruct stu in future)
                        {
                            TradeOrderStruct _tos = stu;
                            unit.Add(_tos);

                            List <TradeOrderStruct> _li = CreateList(unit);
                            unit.Clear();

                            if (_li.Count == 15)
                            {
                                lock (QUEUE_FUTURE_TRADE.GetQueue().SyncRoot)
                                {
                                    QUEUE_FUTURE_TRADE.GetQueue().Enqueue((object)_li);
                                }
                            }

                            if (_li.Count != 0)
                            {
                                lock (QUEUE_FUTURE_TRADE.GetQueue().SyncRoot)
                                {
                                    QUEUE_FUTURE_TRADE.GetQueue().Enqueue((object)_li);
                                }
                            }
                        }
                    }
                    #endregion

                    #endregion
                }

                #endregion

                #region 交易管理界面直接发起交易
                List <MakeOrder> mos = PreTradeModule.instance.DeQueueMonitorOrder();


                if (mos != null)
                {
                    if (mos.Count == 0)
                    {
                        continue;
                    }

                    if (mos.Count > 1)
                    {
                        GlobalTestLog.LogInstance.LogEvent("批量交易已到交易预处理模块,数量:" + mos.Count + "时间:" + DateTime.Now.ToString("yyyy-MM-dd hh-mm-ss") + " : " + DateTime.Now.Millisecond.ToString());
                    }
                    else if (mos.Count == 1)
                    {
                        GlobalTestLog.LogInstance.LogEvent("单笔交易已到交易预处理模块,数量:" + mos.Count + "时间:" + DateTime.Now.ToString("yyyy-MM-dd hh-mm-ss") + " : " + DateTime.Now.Millisecond.ToString());
                    }

                    List <TradeOrderStruct> _TradeList = new List <TradeOrderStruct>();
                    string User = String.Empty;
                    foreach (MakeOrder mo in mos)
                    {
                        User = mo.User;
                        TradeOrderStruct _tradeUnit = new TradeOrderStruct()
                        {
                            cExhcnageID         = mo.exchangeId,
                            cSecurityCode       = mo.cSecurityCode,
                            nSecurityAmount     = mo.nSecurityAmount,
                            dOrderPrice         = mo.dOrderPrice,
                            cTradeDirection     = mo.cTradeDirection,
                            cOffsetFlag         = mo.offsetflag,
                            SecurityName        = String.Empty,
                            cOrderPriceType     = "0",
                            cUser               = mo.User,
                            cSecurityType       = mo.cSecurityType,
                            cOrderLevel         = "1",
                            cOrderexecutedetail = "0",
                            belongStrategy      = mo.belongStrategy,
                            OrderRef            = REQUEST_ID.ApplyNewID()
                        };

                        if (mo.cSecurityType.ToUpper() == "F")
                        {
                            _tradeUnit.cTradeDirection = ((_tradeUnit.cTradeDirection == "0") ? "48" : "49");
                            _tradeUnit.cOffsetFlag     = (_tradeUnit.cOffsetFlag == "0" ? "48" : "49");
                        }
                        if (mo.cSecurityType.ToUpper() == "S")
                        {
                            _tradeUnit.cTradeDirection = ((_tradeUnit.cTradeDirection == "0") ? "1" : "2");
                        }

                        UserRequestMap.GetInstance().AddOrUpdate(_tradeUnit.OrderRef, mo.User, (key, oldValue) => oldValue = mo.User);

                        _TradeList.Add(_tradeUnit);
                    }

                    //风控检测
                    string result = string.Empty;
                    //bool brisk = riskmonitor.RiskDetection(User, _TradeList, out result);
                    bool brisk = true;
                    if (_TradeList.Count > 10)
                    {
                        GlobalTestLog.LogInstance.LogEvent("交易经过风控,时间:" + DateTime.Now.ToString("yyyy-MM-dd hh-mm-ss") + " : " + DateTime.Now.Millisecond.ToString() + "数量:" + _TradeList.Count.ToString());
                    }

                    if (!brisk)
                    {
                        continue;
                    }

                    log.LogEvent("来自交易管理页面的交易");

                    List <TradeOrderStruct> shTradeList     = new List <TradeOrderStruct>();
                    List <TradeOrderStruct> szTradeList     = new List <TradeOrderStruct>();
                    List <TradeOrderStruct> futureTradeList = new List <TradeOrderStruct>();
                    foreach (TradeOrderStruct tradeUnit in _TradeList)
                    {
                        if (tradeUnit.cSecurityType.ToUpper() == "S")
                        {
                            if (tradeUnit.cExhcnageID.ToUpper() == ExchangeID.SH)
                            {
                                shTradeList.Add(tradeUnit);
                                continue;
                            }
                            else if (tradeUnit.cExhcnageID.ToUpper() == ExchangeID.SZ)
                            {
                                szTradeList.Add(tradeUnit);
                                continue;
                            }
                        }
                        else if (tradeUnit.cSecurityType.ToUpper() == "F")
                        {
                            futureTradeList.Add(tradeUnit);
                        }
                    }

                    if (shTradeList.Count > 0)
                    {
                        lock (QUEUE_SH_TRADE.GetQueue().SyncRoot)
                        {
                            QUEUE_SH_TRADE.GetQueue().Enqueue((object)shTradeList);
                        }
                    }
                    if (szTradeList.Count > 0)
                    {
                        lock (QUEUE_SZ_TRADE.GetQueue().SyncRoot)
                        {
                            QUEUE_SZ_TRADE.GetQueue().Enqueue((object)szTradeList);
                        }
                    }
                    if (futureTradeList.Count > 0)
                    {
                        lock (QUEUE_FUTURE_TRADE.GetQueue().SyncRoot)
                        {
                            QUEUE_FUTURE_TRADE.GetQueue().Enqueue((object)futureTradeList);
                        }
                    }

                    List <RISK_TABLE> risks = DBAccessLayer.GetRiskRecord(User);

                    int count = 0;

                    if (risks.Count > 0)
                    {
                        List <TMRiskInfo> riskinfos = new List <TMRiskInfo>();

                        foreach (RISK_TABLE risk in risks)
                        {
                            count++;
                            if (count > 10)
                            {
                                break;
                            }
                            riskinfos.Add(new TMRiskInfo()
                            {
                                code = risk.code, hand = risk.amount.ToString(), price = risk.price.ToString(), orientation = risk.orientation, time = risk.time.ToString(), strategy = "00", user = risk.alias, errinfo = risk.err
                            });
                        }


                        TradeMonitor.Instance.updateRiskList(User, JsonConvert.SerializeObject(riskinfos), JsonConvert.SerializeObject(riskmonitor.riskPara));
                    }
                }

                #endregion

                if (DateTime.Now.Second != PreTradeModule.isRunning.Second)
                {
                    KeyValuePair <string, object> message1 = new KeyValuePair <string, object>("THREAD_PRE_TRADE", (object)true);
                    queue_system_status.GetQueue().Enqueue((object)message1);
                    PreTradeModule.isRunning = DateTime.Now;
                }
            }
        }
Пример #2
0
        private void ThreadProc()
        {
            //初始化子线程
            int futureNum = CONFIG.FUTURE_TRADE_THREAD_NUM;

            DateTime lastmessage = DateTime.Now;

            List <Task> TradeThreads = new List <Task>();

            log.LogEvent("期货交易控制子线程启动: 初始化交易线程数 :" + futureNum.ToString());

            //启动心跳和交易线程
            Task.Factory.StartNew(() => HeartBeatThreadProc((object)futureNum));
            for (int i = 0; i < futureNum; i++)
            {
                TradeParaPackage tpp = new TradeParaPackage();
                tpp._threadNo = (i);
                object      para  = (object)tpp;
                FutureTrade trade = new FutureTrade();
                trade.SetLog(sublog);
                TradeThreads.Add(Task.Factory.StartNew(() => trade.FutureTradeSubThreadProc(para)));
            }

            //此时按照配置,共初始化CONFIG.FUTURE_TRADE_THREAD_NUM 数量交易线程
            // 交易线程按照方法 FutureTradeSubThreadProc 执行

            //Loop 完成对于子线程的监控
            //每一秒钟执行一次自检
            //自检包含任务:
            //  1. 对每个线程,判断当前交易执行时间,超过 CONFIG.FUTURE_TRADE_OVERTIME 仍未收到返回将会按照 该参数备注执行
            //  2. 判断当前线程空闲状态,整理可用线程列表
            //  3. 若当前存在可用线程,同时消息队列(queue_prdTrade_FutureTradeMonitor)
            //      也包含新的消息送达,则安排线程处理交易
            //  4. 记录每个交易线程目前处理的交易内容,并写入数据库
            while (true)
            {
                Thread.Sleep(10);

                if ((DateTime.Now - GlobalHeartBeat.GetGlobalTime()).TotalMinutes > 10)
                {
                    log.LogEvent("本模块供血不足,线程即将死亡");
                    break;
                }

                //获取下一笔交易
                List <TradeOrderStruct> next_trade = new List <TradeOrderStruct>();

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

                if (QUEUE_FUTURE_TRADE.GetQueueNumber() > 0)
                {
                    lock (QUEUE_FUTURE_TRADE.GetQueue().SyncRoot)
                    {
                        if (QUEUE_FUTURE_TRADE.GetQueue().Count > 0)
                        {
                            next_trade = (List <TradeOrderStruct>)QUEUE_FUTURE_TRADE.GetQueue().Dequeue();
                        }

                        if (next_trade.Count > 0)
                        {
                            log.LogEvent("期货交易所出队交易数量:" + next_trade.Count.ToString());
                        }
                    }
                }

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

                //此时next_trade中包含了交易参数
                //判断空闲的线程
                //利用随机选择,保证线程的平均使用


                Random ran      = new Random();
                bool   _bSearch = true;
                int    _tNo     = 0;

                //默认测试用户下,直接使用0号测试线程
                if (next_trade[0].cUser != DebugMode.TestUser)
                {
                    while (_bSearch)
                    {
                        _tNo = ran.Next(0, futureNum);
                        if (queue_future_excuteThread.GetThreadIsAvailiable(_tNo))
                        {
                            _bSearch = false;
                        }
                    }
                }

                log.LogEvent("安排线程 : " + _tNo + " 执行交易 数量: " + next_trade.Count);

                //选择第 _tNo 个线程执行交易
                queue_future_excuteThread.GetQueue(_tNo).Enqueue((object)next_trade);
                queue_future_excuteThread.SetThreadBusy(_tNo);


                //************************************
                //将交易发送到相应执行线程后需要做的事情
                //************************************
            }
            Thread.CurrentThread.Abort();
        }