Exemplo n.º 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;
                }
            }
        }
Exemplo n.º 2
0
        private static void ThreadProc()
        {
            //初始化子线程
            int stockNum = CONFIG.STOCK_TRADE_THREAD_NUM;

            DateTime lastmessage = DateTime.Now;

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

            log.LogEvent("股票交易控制子线程启动: 初始化交易线程数 :" + stockNum.ToString());

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

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

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

                //获取下一笔交易
                List <TradeOrderStruct> next_trade = new List <TradeOrderStruct>();
                if (QUEUE_SH_TRADE.GetQueueNumber() > 0)
                {
                    lock (QUEUE_SH_TRADE.GetQueue().SyncRoot)
                    {
                        if (QUEUE_SH_TRADE.GetQueue().Count > 0)
                        {
                            next_trade = (List <TradeOrderStruct>)QUEUE_SH_TRADE.GetQueue().Dequeue();
                        }
                        if (next_trade.Count > 0)
                        {
                            log.LogEvent("上海交易所出队交易数量:" + next_trade.Count.ToString());
                        }
                    }
                }
                else if (QUEUE_SZ_TRADE.GetQueueNumber() > 0)
                {
                    lock (QUEUE_SZ_TRADE.GetQueue().SyncRoot)
                    {
                        if (QUEUE_SZ_TRADE.GetQueue().Count > 0)
                        {
                            next_trade = (List <TradeOrderStruct>)QUEUE_SZ_TRADE.GetQueue().Dequeue();
                        }

                        log.LogEvent("深圳交易所出队交易数量:" + next_trade.Count.ToString());
                    }
                }


                if (next_trade.Count == 0)
                {
                    if ((DateTime.Now - GlobalHeartBeat.GetGlobalTime()).TotalMinutes > 10)
                    {
                        log.LogEvent("本模块供血不足,线程即将死亡");
                        KeyValuePair <string, object> message1 = new KeyValuePair <string, object>("THREAD_STOCK_TRADE_MONITOR", (object)false);
                        queue_system_status.GetQueue().Enqueue((object)message1);
                        break;
                    }

                    if (lastmessage.Second != DateTime.Now.Second)
                    {
                        KeyValuePair <string, object> message1 = new KeyValuePair <string, object>("THREAD_STOCK_TRADE_MONITOR", (object)true);
                        try
                        {
                            queue_system_status.GetQueue().Enqueue((object)message1);
                            lastmessage = DateTime.Now;
                        }
                        catch
                        {
                            //do nothing
                        }
                    }

                    continue;
                }
                else
                {
                    //此时内存中包含了即将被进行的交易

                    //按照15个一组分割交易
                    List <TradeOrderStruct> tradeGroup = new List <TradeOrderStruct>();
                    foreach (TradeOrderStruct trade in next_trade)
                    {
                        if (tradeGroup.Count < 15)
                        {
                            tradeGroup.Add(trade);

                            if (tradeGroup.Count == 15)
                            {
                                //判断空闲的线程
                                //利用随机选择,保证线程的平均使用
                                String para = JsonConvert.SerializeObject(tradeGroup);
                                ThreadPool.QueueUserWorkItem(new WaitCallback(ChooseThread), (object)para);
                                logword += " 发送交易: " + " 时间: " + DateTime.Now.ToString("yyyy-MM-dd hh-mm-ss") + " : " + DateTime.Now.Millisecond.ToString() + "\r\n";
                                tradeGroup.Clear();
                            }
                        }
                    }
                    if (tradeGroup.Count > 0)
                    {
                        //判断空闲的线程
                        //利用随机选择,保证线程的平均使用
                        String para = JsonConvert.SerializeObject(tradeGroup);
                        ThreadPool.QueueUserWorkItem(new WaitCallback(ChooseThread), (object)para);
                        logword += " 发送交易: " + " 时间: " + DateTime.Now.ToString("yyyy-MM-dd hh-mm-ss") + " : " + DateTime.Now.Millisecond.ToString() + "\r\n";
                        tradeGroup.Clear();
                    }

                    GlobalTestLog.LogInstance.LogEvent(logword);
                }
            }

            Thread.CurrentThread.Abort();
        }