Exemple #1
0
        /// <summary>
        /// 更新成交信息
        /// </summary>
        /// <param name="OrderRef">交易委托本地索引</param>
        /// <param name="Volume">成交量</param>
        /// <param name="Price">成交价格</param>
        /// <param name="TradeId">成交编号</param>
        public void UpdateTrade(int OrderRef, int Volume, decimal Price, String TradeId)
        {
            RecordItem _record = new RecordItem();

            _record = this.GetOrAdd(OrderRef, _record);

            if (_record.Trades == null)
            {
                _record.Trades = new List <TradeItem>();
            }

            _record.Trades.Add(new TradeItem()
            {
                TradeID = TradeId,
                Price   = Price,
                Volume  = Volume
            });

            decimal totalVolume = 0;
            decimal totalCost   = 0;

            foreach (TradeItem item in _record.Trades)
            {
                totalVolume += item.Volume;
                totalCost   += (item.Volume * item.Price);
            }

            _record.AveragePrice = (totalCost / totalVolume);

            String        UserName = UserRequestMap.GetInstance()[OrderRef];
            TradeViewItem trade    = new TradeViewItem(OrderRef.ToString(), TradeId, _record.Code, _record.Orientation, _record.CombOffsetFlag.ToString(), Price.ToString(), Volume.ToString(), _record.OrderSysID);

            String JsonString = JsonConvert.SerializeObject(trade);

            //TradeMonitor.Instance.updateTradeList(UserName, JsonString); 不从这里收集成交信息,直接从数据库中同步

            this.AddOrUpdate(OrderRef, _record, (key, oldValue) =>
                             oldValue = _record
                             );

            if (_record.Status == TradeDealStatus.ORDERCOMPLETED || _record.VolumeTotalOriginal == totalVolume)
            {
                CompletedTradeRecord.GetInstance().Update(_record.OrderRef, _record);
                CompletedTradeRecord.GetInstance().Delete(_record.OrderRef, _record);

                managedBargainreturnstruct bargin = new managedBargainreturnstruct()
                {
                    Security_code = _record.Code,
                    OrderType     = Convert.ToSByte(_record.Type),
                    stock_amount  = _record.VolumeTraded,
                    bargain_price = Convert.ToDouble(Price),
                    User          = _record.User,
                    offsetflag    = _record.CombOffsetFlag,
                    direction     = (_record.Orientation == "0") ? 48 : 49
                };

                //更新持仓列表
                ThreadPool.QueueUserWorkItem(new WaitCallback(DBAccessLayer.UpdateCCRecords), (object)bargin);

                //删除委托信息
                ThreadPool.QueueUserWorkItem(new WaitCallback(DBAccessLayer.DeleteERRecord), (object)OrderRef);
            }
        }
        /// <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;
                }
            }
        }
Exemple #3
0
        /// <summary>
        /// 更新委托信息
        /// </summary>
        /// <param name="volumeTraded"></param>
        /// <param name="OrderRef"></param>
        /// <param name="OrderSysID"></param>
        /// <param name="StatusMsg"></param>
        /// <param name="OrderStatus"></param>
        /// <param name="VolumeTotal"></param>
        /// <param name="ExchangeID">退货使用</param>
        public void UpdateOrder(int volumeTraded, int OrderRef, String OrderSysID, String StatusMsg, int OrderStatus, int VolumeTotal, String ExchangeID)
        {
            RecordItem _record = new RecordItem();

            _record = this.GetOrAdd(OrderRef, _record);

            _record.VolumeTraded = volumeTraded;
            _record.VolumeTotal  = VolumeTotal;
            _record.ErrMsg       = StatusMsg;
            _record.OrderStatus  = OrderStatus;
            _record.OrderSysID   = OrderSysID;
            _record.ExchangeID   = ExchangeID;
            _record.Status       = TradeDealStatus.ORDERING;
            if (_record.OrderSysID.Trim() == "0" && _record.OrderSysID != String.Empty)
            {
                QueryEntrustOrderStruct_M record = new QueryEntrustOrderStruct_M()
                {
                    Code         = _record.Code,
                    User         = _record.User,
                    OrderRef     = _record.OrderRef,
                    Direction    = Convert.ToInt32(_record.Orientation),
                    ExchangeID   = ExchangeID,
                    OrderPrice   = Convert.ToDouble(_record.Price),
                    OrderSysID   = _record.OrderSysID.Trim(),
                    SecurityType = Convert.ToSByte(_record.Type),
                    StrategyId   = _record.StrategyId,
                    OffsetFlag   = _record.CombOffsetFlag,
                    Amount       = _record.VolumeTotalOriginal
                };

                ThreadPool.QueueUserWorkItem(new WaitCallback(DBAccessLayer.CreateFutureERRecord), ((object)record));
            }

            //若交易已撤单 或者 全部成交则标记该委托完成
            if (OrderStatus == 53 || _record.VolumeTotalOriginal == _record.VolumeTraded)
            {
                _record.OrderTime_Completed = DateTime.Now;
                _record.Status = TradeDealStatus.ORDERCOMPLETED;
            }



            this.AddOrUpdate(OrderRef, _record, (key, oldValue) =>
                             oldValue = _record
                             );


            if (UserRequestMap.GetInstance().Count == 0)
            {
                return;
            }

            String USERNAME = string.Empty;

            try
            {
                USERNAME = UserRequestMap.GetInstance()[OrderRef];
            }
            catch (Exception ex)
            {
                DBAccessLayer.LogSysInfo("TradeAdditionalClass->UpdateOrder", ex.ToString());
            }
            OrderViewItem order = new OrderViewItem(_record.OrderRef.ToString(), _record.OrderSysID, _record.Code, _record.Orientation, _record.CombOffsetFlag.ToString(), _record.VolumeTotalOriginal.ToString(), _record.VolumeTotal.ToString(), _record.Price.ToString(), _record.ErrMsg, _record.OrderTime_Start.ToString());

            TradeMonitor.Instance.updateOrderList(USERNAME, order);

            if (_record.Status == TradeDealStatus.ORDERCOMPLETED)
            {
                CompletedTradeRecord.GetInstance().Update(_record.OrderRef, _record);
            }
        }