public void TestTryRoutines()
        {
            SynchronizedDictionary <int, string> data =
                new SynchronizedDictionary <int, string>(new Dictionary <int, string>());

            Assert.IsTrue(data.TryAdd(1, "a"));
            Assert.IsFalse(data.TryAdd(1, "a"));

            Assert.IsTrue(data.TryUpdate(1, "a"));
            Assert.IsTrue(data.TryUpdate(1, "c"));
            Assert.IsTrue(data.TryUpdate(1, "d", "c"));
            Assert.IsFalse(data.TryUpdate(1, "f", "c"));
            Assert.AreEqual("d", data[1]);
            Assert.IsTrue(data.TryUpdate(1, "a", data[1]));
            Assert.AreEqual("a", data[1]);
            Assert.IsFalse(data.TryUpdate(2, "b"));

            string val;

            Assert.IsTrue(data.TryRemove(1, out val) && val == "a");
            Assert.IsFalse(data.TryRemove(2, out val));
            Assert.AreNotEqual(val, "a");

            Assert.IsFalse(data.TryUpdate(1, (k, x) => x.ToUpper()));
            data[1] = "a";
            data[1] = "b";
            Assert.IsTrue(data.TryUpdate(1, (k, x) => x.ToUpper()));
            Assert.AreEqual("B", data[1]);
        }
コード例 #2
0
ファイル: AccountCache.cs プロジェクト: hlslml77/fist
        /// <summary>
        /// 判断账号密码是否存在正确
        /// </summary>
        /// <param name="acc"></param>
        /// <param name="pwd"></param>
        /// <returns></returns>
        public bool Match(string acc, string pwd)
        {
            //if (!accModelDict.ContainsKey(acc))
            //    return false;
            //return accModelDict[acc].Password == pwd;

            //如果内存里面有 直接判断
            if (accModelDict.ContainsKey(acc))
            {
                return(accModelDict[acc].Password == pwd);
            }

            AccountModel model = new AccountModel();

            //如果没有 那就真的没有
            if (!model.Exists(acc))
            {
                return(false);
            }
            //如果数据库里面存在
            model.GetModel(acc);
            //添加到内存里
            accModelDict.TryAdd(model.Account, model);
            //再进行判断
            return(model.Password == pwd);
        }
コード例 #3
0
ファイル: PlayerCache.cs プロジェクト: hlslml77/fist
        /// <summary>
        /// 主键ID
        /// </summary>
        //private int index = 0;
        /// <summary>
        /// 创建角色
        /// </summary>
        /// <param name="name"></param>
        /// <param name="accId"></param>
        public void Create(string name, int accId)
        {
            PlayerModel model = new PlayerModel();

            model.Name      = name;
            model.AccountId = accId;

            model.Lv           = 1;
            model.Exp          = 0;
            model.Power        = 2000;
            model.WinCount     = 0;
            model.LoseCount    = 0;
            model.RunCount     = 0;
            model.HeroIdList   = "1,2";
            model.FriendIdList = "";
            //返值是自增的id
            //保存到数据库
            model.Add();
            //获取数据库数据
            model.GetModelByAccId(accId);

            //保存到内存
            accPlayerDict.TryAdd(accId, model.Id);
            idModelDict.TryAdd(model.Id, model);
        }
コード例 #4
0
        static SecurityInfoCache()
        {
            using (var zip = new ZipArchive(Resources.Securities.To <MemoryStream>()))
            {
                using (var s = zip.Entries.First().Open())
                {
                    var root = XDocument.Load(s).Root;

                    if (root == null)
                    {
                        throw new InvalidOperationException();
                    }

                    var securities = CultureInfo.InvariantCulture.DoInCulture(() =>
                                                                              root.Elements().Select(
                                                                                  elem => new SecurityInfo
                    {
                        Board      = elem.GetAttributeValue <string>("board"),
                        Multiplier = elem.GetAttributeValue <decimal?>("multiplier"),
                        Decimals   = elem.GetAttributeValue <int?>("decimals"),
                        PriceStep  = elem.GetAttributeValue <decimal?>("priceStep"),
                        Code       = elem.GetAttributeValue <string>("code"),
                        ShortName  = elem.GetAttributeValue <string>("shortName"),
                        Name       = elem.GetAttributeValue <string>("name"),
                        Isin       = elem.GetAttributeValue <string>("isin"),
                        Asset      = elem.GetAttributeValue <string>("asset"),
                        Type       = elem.GetAttributeValue <string>("type"),
                        Currency   = elem.GetAttributeValue <string>("currency"),
                        IssueSize  = elem.GetAttributeValue <decimal?>("issueSize"),
                        IssueDate  = elem.GetAttributeValue <string>("issueDate").TryToDateTime("yyyyMMdd"),
                        LastDate   = elem.GetAttributeValue <string>("lastDate").TryToDateTime("yyyyMMdd"),
                    })
                                                                              .ToArray());

                    foreach (var info in securities)
                    {
                        _securitiesByCode.SafeAdd(info.Code).Add(info);
                    }

                    foreach (var info in securities)
                    {
                        if (!info.ShortName.IsEmpty())
                        {
                            _securitiesByShortName.TryAdd(info.ShortName, info);
                        }
                        else if (!info.Name.IsEmpty())
                        {
                            _securitiesByShortName.TryAdd(info.Name, info);
                        }
                    }
                }
            }
        }
コード例 #5
0
        /// <summary>
        /// 创建角色
        /// </summary>
        /// <param name="name"></param>
        /// <param name="accId"></param>
        public void Create(string name, int accId)
        {
            PlayerModel model = new PlayerModel();

            model.Name      = name;
            model.AccountId = accId;
            //保存的数据库
            model.Id = model.Add();
            //保存到内存
            accPlayerDict.TryAdd(accId, model.Id);
            idModelDict.TryAdd(model.Id, model);
        }
コード例 #6
0
        public void AddOrderByRegistrationId(Order order)
        {
            if (order == null)
            {
                throw new ArgumentNullException(nameof(order));
            }

            AddOrder(order);

            GetData(order.Security).Orders.Add(CreateOrderKey(order.Type, order.TransactionId, false), new OrderInfo(order));

            // с таким же идентификатором транзакции может быть заявка по другому инструменту
            _allOrdersByTransactionId.TryAdd(Tuple.Create(order.TransactionId, order.Type == OrderTypes.Conditional), order);
        }
コード例 #7
0
        /// <summary>
        /// 创建角色
        /// </summary>
        /// <param name="name"></param>
        /// <param name="accId"></param>
        public void Create(string name, int accId)
        {
            PlayerModel model = new PlayerModel();

            model.Name      = name;
            model.AccountId = accId;

            MobaApplication.LogInfo("创建玩家 name = " + name + "accId = " + accId);

            //返回值是自增 键值
            model.Id = model.Add();

            accPlayerDict.TryAdd(accId, model.Id);
            idModelDict.TryAdd(model.Id, model);
        }
コード例 #8
0
            public void ProcessRequest(Security security, MarketDataMessage message, bool tryAdd)
            {
                if (security == null)
                {
                    throw new ArgumentNullException(nameof(security));
                }

                if (message == null)
                {
                    throw new ArgumentNullException(nameof(message));
                }

                if (message.TransactionId == 0)
                {
                    message.TransactionId = _connector.TransactionIdGenerator.GetNextId();
                }

                message.FillSecurityInfo(_connector, security);

                var value = Tuple.Create((MarketDataMessage)message.Clone(), security);

                if (tryAdd)
                {
                    // if the message was looped back via IsBack=true
                    _pendingSubscriptions.TryAdd(message.TransactionId, value);
                }
                else
                {
                    _pendingSubscriptions.Add(message.TransactionId, value);
                }

                _connector.SendInMessage(message);
            }
        public void TestAtomicAdd()
        {
            SynchronizedDictionary <int, string> data =
                new SynchronizedDictionary <int, string>(new Dictionary <int, string>());

            int[] counter = new int[] { -1 };
            for (int i = 0; i < 100; i++)
            {
                Assert.IsTrue(data.TryAdd(i, (k) => (++counter[0]).ToString()));
            }
            Assert.AreEqual(100, data.Count);
            Assert.AreEqual(100, counter[0] + 1);

            //Inserts of existing keys will not call method
            Assert.IsFalse(data.TryAdd(50, (k) => { throw new InvalidOperationException(); }));
            Assert.AreEqual(100, data.Count);
        }
コード例 #10
0
        /// <summary>
        /// 创建角色
        /// </summary>
        /// <param name="name"></param>
        /// <param name="accountID"></param>
        public void Create(string name, int accountID)
        {
            PlayerModel playerModel = new PlayerModel(index, name, accountID);

            accountPlayers.TryAdd(accountID, playerModel.Id);
            playerModels.TryAdd(playerModel.Id, playerModel);
            index++;
        }
コード例 #11
0
        /// <inheritdoc />
        public void Save(Security security, bool forced)
        {
            if (security is null)
            {
                throw new ArgumentNullException(nameof(security));
            }

            if (_inner.TryAdd(security.ToSecurityId(), security))
            {
                Added?.Invoke(new[] { security });
            }
        }
コード例 #12
0
        /// <summary>
        ///    匹配账号密码是否存在正确
        /// </summary>
        /// <returns></returns>
        public bool Match(string acc, string pwd)
        {
            //如果内存有就直接判断
            if (accModelDict.ContainsKey(acc))
            {
                return(accModelDict[acc].Password == pwd);
            }

            AccountModel model = new AccountModel();

            if (!model.Exists(acc))
            {
                return(false);
            }

            //如果数据库存在
            model.GetModel(acc);
            //添加到内存
            accModelDict.TryAdd(model.Account, model);

            return(model.Password == pwd);
        }
コード例 #13
0
        void Bind(int tokenIndex)
        {
            var token = m_pool[tokenIndex];

            Logger.Print("BindClient: {0}->{1}", token.uid, token.Address);
            try
            {
                m_indexMap.TryAdd(token.uid, tokenIndex);
                token.OnBinded();
            }
            catch (Exception e)
            {
                Logger.Exception(e);
            }
        }
コード例 #14
0
        private void OnBoardsResponse(BoardsResponse response)
        {
            foreach (var board in response.Boards)
            {
                var code = board.Id.FixBoardName();

                SendOutMessage(new BoardMessage
                {
                    Code         = code,
                    ExchangeCode = Exchange.Moex.Name,
                });

                _boards.TryAdd(board.Market, code);
            }
        }
コード例 #15
0
        /// <inheritdoc />
        protected override bool OnSendInMessage(Message message)
        {
            switch (message.Type)
            {
            case MessageTypes.Reset:
                Reset();
                Buffer.SendInMessage(message);
                break;

            case MessageTypes.Connect:
                //Buffer.Enabled = CanAutoStorage && (_storageProcessor.StorageRegistry != null || SupportBuffer);
                StartStorageTimer();
                break;

            case MessageTypes.OrderStatus:
            {
                if (message.Adapter != null && message.Adapter != this)
                {
                    break;
                }

                message = ProcessOrderStatus((OrderStatusMessage)message);
                break;
            }

            case MessageTypes.OrderCancel:
            {
                var cancelMsg = (OrderCancelMessage)message;

                // can be looped back from offline
                _cancellationTransactions.TryAdd(cancelMsg.TransactionId, cancelMsg.OriginalTransactionId);

                break;
            }

            case MessageTypes.MarketData:
                ProcessMarketData((MarketDataMessage)message);
                break;
            }

            if (message == null)
            {
                return(true);
            }

            return(base.OnSendInMessage(message));
        }
コード例 #16
0
        /// <summary>
        /// Process message.
        /// </summary>
        /// <param name="message">Message.</param>
        public void SendInMessage(Message message)
        {
            if (message is null)
            {
                throw new ArgumentNullException(nameof(message));
            }

            if (message.OfflineMode != MessageOfflineModes.None)
            {
                return;
            }

            switch (message.Type)
            {
            case MessageTypes.Reset:
            {
                _subscriptionsById.Clear();

                _ticksBuffer.Clear();
                _level1Buffer.Clear();
                _candleBuffer.Clear();
                _orderLogBuffer.Clear();
                _orderBooksBuffer.Clear();
                _transactionsBuffer.Clear();
                _newsBuffer.Clear();
                _positionChangesBuffer.Clear();

                //SendOutMessage(new ResetMessage());
                break;
            }

            case MessageTypes.OrderRegister:
            {
                var regMsg = (OrderRegisterMessage)message;

                //if (!CanStore<ExecutionMessage>(regMsg.SecurityId, ExecutionTypes.Transaction))
                //	break;

                // try - cause looped back messages from offline adapter
                _securityIds.TryAdd(regMsg.TransactionId, regMsg.SecurityId);

                _transactionsBuffer.Add(regMsg.SecurityId, new ExecutionMessage
                    {
                        ServerTime     = DateTimeOffset.Now,
                        ExecutionType  = ExecutionTypes.Transaction,
                        SecurityId     = regMsg.SecurityId,
                        TransactionId  = regMsg.TransactionId,
                        HasOrderInfo   = true,
                        OrderPrice     = regMsg.Price,
                        OrderVolume    = regMsg.Volume,
                        Currency       = regMsg.Currency,
                        PortfolioName  = regMsg.PortfolioName,
                        ClientCode     = regMsg.ClientCode,
                        BrokerCode     = regMsg.BrokerCode,
                        Comment        = regMsg.Comment,
                        Side           = regMsg.Side,
                        TimeInForce    = regMsg.TimeInForce,
                        ExpiryDate     = regMsg.TillDate,
                        Balance        = regMsg.Volume,
                        VisibleVolume  = regMsg.VisibleVolume,
                        LocalTime      = regMsg.LocalTime,
                        IsMarketMaker  = regMsg.IsMarketMaker,
                        IsMargin       = regMsg.IsMargin,
                        Slippage       = regMsg.Slippage,
                        IsManual       = regMsg.IsManual,
                        OrderType      = regMsg.OrderType,
                        UserOrderId    = regMsg.UserOrderId,
                        OrderState     = OrderStates.Pending,
                        Condition      = regMsg.Condition?.Clone(),
                        MinVolume      = regMsg.MinOrderVolume,
                        PositionEffect = regMsg.PositionEffect,
                        PostOnly       = regMsg.PostOnly,
                    });

                break;
            }

            case MessageTypes.OrderCancel:
            {
                var cancelMsg = (OrderCancelMessage)message;

                //if (!CanStore<ExecutionMessage>(cancelMsg.SecurityId, ExecutionTypes.Transaction))
                //	break;

                // try - cause looped back messages from offline adapter
                _securityIds.TryAdd(cancelMsg.TransactionId, cancelMsg.SecurityId);

                _transactionsBuffer.Add(cancelMsg.SecurityId, new ExecutionMessage
                    {
                        ServerTime            = DateTimeOffset.Now,
                        ExecutionType         = ExecutionTypes.Transaction,
                        SecurityId            = cancelMsg.SecurityId,
                        HasOrderInfo          = true,
                        TransactionId         = cancelMsg.TransactionId,
                        IsCancellation        = true,
                        OrderId               = cancelMsg.OrderId,
                        OrderStringId         = cancelMsg.OrderStringId,
                        OriginalTransactionId = cancelMsg.OriginalTransactionId,
                        OrderVolume           = cancelMsg.Volume,
                        //Side = cancelMsg.Side,
                    });

                break;
            }

            case MessageTypes.MarketData:
            {
                var mdMsg = (MarketDataMessage)message;

                if (Enabled)
                {
                    if (mdMsg.IsSubscribe)
                    {
                        _subscriptionsById.Add(mdMsg.TransactionId);
                    }
                    else
                    {
                        _subscriptionsById.Remove(mdMsg.OriginalTransactionId);
                    }
                }

                break;
            }
            }
        }
コード例 #17
0
        /// <inheritdoc />
        public override bool SendInMessage(Message message)
        {
            switch (message.Type)
            {
            case MessageTypes.Reset:
            {
                Reset();
                break;
            }

            case MessageTypes.OrderRegister:
            {
                var regMsg = (OrderRegisterMessage)message;
                _secIds.TryAdd(regMsg.TransactionId, regMsg.SecurityId);
                break;
            }

            case MessageTypes.OrderReplace:
            {
                var replaceMsg = (OrderReplaceMessage)message;

                if (_secIds.TryGetValue(replaceMsg.OriginalTransactionId, out var secId))
                {
                    _secIds.TryAdd(replaceMsg.TransactionId, secId);
                }

                break;
            }

            case MessageTypes.OrderPairReplace:
            {
                var replaceMsg = (OrderPairReplaceMessage)message;

                if (_secIds.TryGetValue(replaceMsg.Message1.OriginalTransactionId, out var secId))
                {
                    _secIds.TryAdd(replaceMsg.Message1.TransactionId, secId);
                }

                if (_secIds.TryGetValue(replaceMsg.Message2.OriginalTransactionId, out secId))
                {
                    _secIds.TryAdd(replaceMsg.Message2.TransactionId, secId);
                }

                break;
            }

            case MessageTypes.OrderStatus:
            {
                var statusMsg = (OrderStatusMessage)message;

                if (statusMsg.IsSubscribe)
                {
                    if (IsSupportTransactionLog)
                    {
                        _transactionLogSubscriptions.Add(statusMsg.TransactionId, new SubscriptionInfo(statusMsg.TypedClone()));
                    }
                    else
                    {
                        _orderStatusIds.Add(statusMsg.TransactionId);
                    }
                }

                break;
            }
            }

            return(base.SendInMessage(message));
        }
コード例 #18
0
        /// <summary>
        /// Process message.
        /// </summary>
        /// <param name="message">Message.</param>
        public void ProcessMessage(Message message)
        {
            if (message == null)
            {
                throw new ArgumentNullException(nameof(message));
            }

            if (message.OfflineMode != MessageOfflineModes.None)
            {
                return;
            }

            switch (message.Type)
            {
            // in message
            case MessageTypes.Reset:
            {
                _subscriptionsById.Clear();

                _ticksBuffer.Clear();
                _level1Buffer.Clear();
                _candleBuffer.Clear();
                _orderLogBuffer.Clear();
                _orderBooksBuffer.Clear();
                _transactionsBuffer.Clear();
                _newsBuffer.Clear();
                _positionChangesBuffer.Clear();

                //SendOutMessage(new ResetMessage());
                break;
            }

            case MessageTypes.OrderRegister:
            {
                var regMsg = (OrderRegisterMessage)message;

                //if (!CanStore<ExecutionMessage>(regMsg.SecurityId, ExecutionTypes.Transaction))
                //	break;

                // try - cause looped back messages from offline adapter
                _securityIds.TryAdd(regMsg.TransactionId, regMsg.SecurityId);

                _transactionsBuffer.Add(regMsg.SecurityId, new ExecutionMessage
                    {
                        ServerTime    = DateTimeOffset.Now,
                        ExecutionType = ExecutionTypes.Transaction,
                        SecurityId    = regMsg.SecurityId,
                        TransactionId = regMsg.TransactionId,
                        HasOrderInfo  = true,
                        OrderPrice    = regMsg.Price,
                        OrderVolume   = regMsg.Volume,
                        Currency      = regMsg.Currency,
                        PortfolioName = regMsg.PortfolioName,
                        ClientCode    = regMsg.ClientCode,
                        BrokerCode    = regMsg.BrokerCode,
                        Comment       = regMsg.Comment,
                        Side          = regMsg.Side,
                        TimeInForce   = regMsg.TimeInForce,
                        ExpiryDate    = regMsg.TillDate,
                        Balance       = regMsg.Volume,
                        VisibleVolume = regMsg.VisibleVolume,
                        LocalTime     = regMsg.LocalTime,
                        IsMarketMaker = regMsg.IsMarketMaker,
                        IsMargin      = regMsg.IsMargin,
                        Slippage      = regMsg.Slippage,
                        IsManual      = regMsg.IsManual,
                        OrderType     = regMsg.OrderType,
                        UserOrderId   = regMsg.UserOrderId,
                        OrderState    = OrderStates.Pending,
                        Condition     = regMsg.Condition?.Clone(),
                    });

                break;
            }

            case MessageTypes.OrderCancel:
            {
                var cancelMsg = (OrderCancelMessage)message;

                //if (!CanStore<ExecutionMessage>(cancelMsg.SecurityId, ExecutionTypes.Transaction))
                //	break;

                // try - cause looped back messages from offline adapter
                _securityIds.TryAdd(cancelMsg.TransactionId, cancelMsg.SecurityId);

                _transactionsBuffer.Add(cancelMsg.SecurityId, new ExecutionMessage
                    {
                        ServerTime            = DateTimeOffset.Now,
                        ExecutionType         = ExecutionTypes.Transaction,
                        SecurityId            = cancelMsg.SecurityId,
                        HasOrderInfo          = true,
                        TransactionId         = cancelMsg.TransactionId,
                        IsCancellation        = true,
                        OrderId               = cancelMsg.OrderId,
                        OrderStringId         = cancelMsg.OrderStringId,
                        OriginalTransactionId = cancelMsg.OriginalTransactionId,
                        OrderVolume           = cancelMsg.Volume,
                        //Side = cancelMsg.Side,
                    });

                break;
            }

            case MessageTypes.MarketData:
            {
                var mdMsg = (MarketDataMessage)message;

                if (Enabled)
                {
                    if (mdMsg.IsSubscribe)
                    {
                        _subscriptionsById.Add(mdMsg.TransactionId);
                    }
                    else
                    {
                        _subscriptionsById.Remove(mdMsg.OriginalTransactionId);
                    }
                }

                break;
            }

            // out messages
            case MessageTypes.Level1Change:
            {
                var level1Msg = (Level1ChangeMessage)message;

                if (CanStore(level1Msg))
                {
                    _level1Buffer.Add(level1Msg.SecurityId, level1Msg.TypedClone());
                }

                break;
            }

            case MessageTypes.QuoteChange:
            {
                var quotesMsg = (QuoteChangeMessage)message;

                if (CanStore(quotesMsg))
                {
                    _orderBooksBuffer.Add(quotesMsg.SecurityId, quotesMsg.TypedClone());
                }

                break;
            }

            case MessageTypes.Execution:
            {
                var execMsg = (ExecutionMessage)message;

                DataBuffer <SecurityId, ExecutionMessage> buffer;

                var secId    = execMsg.SecurityId;
                var execType = execMsg.ExecutionType;

                switch (execType)
                {
                case ExecutionTypes.Tick:
                    buffer = _ticksBuffer;
                    break;

                case ExecutionTypes.Transaction:
                {
                    // some responses do not contains sec id
                    if (secId.IsDefault() && !_securityIds.TryGetValue(execMsg.OriginalTransactionId, out secId))
                    {
                        return;
                    }

                    buffer = _transactionsBuffer;
                    break;
                }

                case ExecutionTypes.OrderLog:
                    buffer = _orderLogBuffer;
                    break;

                default:
                    throw new ArgumentOutOfRangeException(nameof(message), execType, LocalizedStrings.Str1695Params.Put(message));
                }

                //if (execType == ExecutionTypes.Transaction && execMsg.TransactionId == 0)
                //	break;

                if (execType == ExecutionTypes.Transaction || CanStore(execMsg))
                {
                    buffer.Add(secId, execMsg.TypedClone());
                }

                break;
            }

            case MessageTypes.News:
            {
                var newsMsg = (NewsMessage)message;

                if (CanStore(newsMsg))
                {
                    _newsBuffer.Add(newsMsg.TypedClone());
                }

                break;
            }

            case MessageTypes.PositionChange:
            {
                var posMsg = (PositionChangeMessage)message;
                var secId  = posMsg.SecurityId;

                //if (CanStore<PositionChangeMessage>(secId))
                _positionChangesBuffer.Add(secId, posMsg.TypedClone());

                break;
            }

            default:
            {
                if (message is CandleMessage candleMsg && candleMsg.State == CandleStates.Finished)
                {
                    if (CanStore(candleMsg))
                    {
                        _candleBuffer.Add(Tuple.Create(candleMsg.SecurityId, candleMsg.GetType(), candleMsg.Arg), candleMsg.TypedClone());
                    }
                }

                break;
            }
            }
        }
コード例 #19
0
		/// <inheritdoc />
		protected override void OnSendInMessage(Message message)
		{
			switch (message.Type)
			{
				case MessageTypes.Reset:
				{
					ClearSubscriptions();

					_ticksBuffer.Clear();
					_level1Buffer.Clear();
					_candleBuffer.Clear();
					_orderLogBuffer.Clear();
					_orderBooksBuffer.Clear();
					_transactionsBuffer.Clear();
					_newsBuffer.Clear();
					_positionChangesBuffer.Clear();
					//SendOutMessage(new ResetMessage());
					break;
				}

				case MessageTypes.OrderRegister:
					var regMsg = (OrderRegisterMessage)message;

					//if (!CanStore<ExecutionMessage>(regMsg.SecurityId, ExecutionTypes.Transaction))
					//	break;

					// try - cause looped back messages from offline adapter
					_securityIds.TryAdd(regMsg.TransactionId, regMsg.SecurityId);

					_transactionsBuffer.Add(regMsg.SecurityId, new ExecutionMessage
					{
						ServerTime = DateTimeOffset.Now,
						ExecutionType = ExecutionTypes.Transaction,
						SecurityId = regMsg.SecurityId,
						TransactionId = regMsg.TransactionId,
						HasOrderInfo = true,
						OrderPrice = regMsg.Price,
						OrderVolume = regMsg.Volume,
						Currency = regMsg.Currency,
						PortfolioName = regMsg.PortfolioName,
						ClientCode = regMsg.ClientCode,
						BrokerCode = regMsg.BrokerCode,
						Comment = regMsg.Comment,
						Side = regMsg.Side,
						TimeInForce = regMsg.TimeInForce,
						ExpiryDate = regMsg.TillDate,
						Balance = regMsg.Volume,
						VisibleVolume = regMsg.VisibleVolume,
						LocalTime = regMsg.LocalTime,
						IsMarketMaker = regMsg.IsMarketMaker,
						IsMargin = regMsg.IsMargin,
						Slippage = regMsg.Slippage,
						IsManual = regMsg.IsManual,
						OrderType = regMsg.OrderType,
						UserOrderId = regMsg.UserOrderId,
						OrderState = OrderStates.Pending,
						Condition = regMsg.Condition?.Clone(),
					});
					break;
				case MessageTypes.OrderCancel:
					var cancelMsg = (OrderCancelMessage)message;

					//if (!CanStore<ExecutionMessage>(cancelMsg.SecurityId, ExecutionTypes.Transaction))
					//	break;

					// try - cause looped back messages from offline adapter
					_securityIds.TryAdd(cancelMsg.TransactionId, cancelMsg.SecurityId);

					_transactionsBuffer.Add(cancelMsg.SecurityId, new ExecutionMessage
					{
						ServerTime = DateTimeOffset.Now,
						ExecutionType = ExecutionTypes.Transaction,
						SecurityId = cancelMsg.SecurityId,
						HasOrderInfo = true,
						TransactionId = cancelMsg.TransactionId,
						IsCancellation = true,
						OrderId = cancelMsg.OrderId,
						OrderStringId = cancelMsg.OrderStringId,
						OriginalTransactionId = cancelMsg.OriginalTransactionId,
						OrderVolume = cancelMsg.Volume,
						//Side = cancelMsg.Side,
					});
					break;
			}

			base.OnSendInMessage(message);
		}
コード例 #20
0
            public void ProcessRequest(Security security, MarketDataMessage message, bool tryAdd)
            {
                if (message == null)
                {
                    throw new ArgumentNullException(nameof(message));
                }

                if (!tryAdd)
                {
                    var msg = (message.IsSubscribe ? LocalizedStrings.SubscriptionSent : LocalizedStrings.UnSubscriptionSent)
                              .Put(security?.Id, message.ToDataTypeString());

                    if (message.From != null && message.To != null)
                    {
                        msg += LocalizedStrings.Str691Params.Put(message.From.Value, message.To.Value);
                    }

                    _connector.AddDebugLog(msg + ".");
                }

                if (security == null)
                {
                    if (!message.IsSubscribe)
                    {
                        if (message.OriginalTransactionId != 0)
                        {
                            security = TryGetSecurity(message.OriginalTransactionId);
                        }
                    }
                }

                if (security == null)
                {
                    if (message.DataType != MarketDataTypes.News)
                    {
                        if (message.SecurityId.IsDefault())
                        {
                            throw new ArgumentNullException(nameof(security));
                        }

                        security = _connector.LookupById(message.SecurityId);

                        if (security == null)
                        {
                            throw new ArgumentException(LocalizedStrings.Str704Params.Put(message.SecurityId));
                        }
                    }
                }

                if (message.TransactionId == 0)
                {
                    message.TransactionId = _connector.TransactionIdGenerator.GetNextId();
                }

                if (security != null)
                {
                    message.FillSecurityInfo(_connector, security);
                }

                var value = Tuple.Create((MarketDataMessage)message.Clone(), security);

                if (tryAdd)
                {
                    // if the message was looped back via IsBack=true
                    _requests.TryAdd(message.TransactionId, value);
                }
                else
                {
                    _requests.Add(message.TransactionId, value);
                }

                _connector.SendInMessage(message);
            }
コード例 #21
0
 /// <summary>
 /// 上线
 /// </summary>
 /// <param name="client"></param>
 /// <param name="accId"></param>
 public void Online(MobaClient client, int playerId)
 {
     clientIdDict.TryAdd(client, playerId);
     idClientDict.TryAdd(playerId, client);
 }
コード例 #22
0
        private Tuple <Order, bool, bool> GetOrderInfo(SecurityData securityData, OrderTypes type, long transactionId, long?orderId, string orderStringId, Func <long, Order> createOrder, out bool isNew, bool newOrderRaised = false)
        {
            if (createOrder == null)
            {
                throw new ArgumentNullException(nameof(createOrder));
            }

            if (transactionId == 0 && orderId == null && orderStringId.IsEmpty())
            {
                throw new ArgumentException(LocalizedStrings.Str719);
            }

            var isNew2 = false;
            var orders = securityData.Orders;

            OrderInfo info;

            if (transactionId == 0)
            {
                info = orders.CachedValues.FirstOrDefault(i =>
                {
                    var order = i.Order;

                    if (orderId != null)
                    {
                        return(order.Id == orderId);
                    }
                    else
                    {
                        return(order.StringId.CompareIgnoreCase(orderStringId));
                    }
                });

                if (info == null)
                {
                    isNew = false;
                    return(null);
                    //throw new InvalidOperationException(LocalizedStrings.Str1156Params.Put(orderId.To<string>() ?? orderStringId));
                }
            }
            else
            {
                var cancelKey   = CreateOrderKey(type, transactionId, true);
                var registerKey = CreateOrderKey(type, transactionId, false);

                var cancelledOrder = (Order)orders.TryGetValue(cancelKey);

                // проверяем не отмененная ли заявка пришла
                if (cancelledOrder != null && (cancelledOrder.Id == orderId || (!cancelledOrder.StringId.IsEmpty() && cancelledOrder.StringId.CompareIgnoreCase(orderStringId))))
                {
                    isNew = false;
                    return(Tuple.Create(cancelledOrder, true /*, (Order)orders.TryGetValue(registerKey) != null*/, false));
                }

                info = orders.SafeAdd(registerKey, key =>
                {
                    isNew2 = true;

                    var o = createOrder(transactionId);

                    if (o == null)
                    {
                        throw new InvalidOperationException(LocalizedStrings.Str720Params.Put(transactionId));
                    }

                    if (o.ExtensionInfo == null)
                    {
                        o.ExtensionInfo = new Dictionary <object, object>();
                    }

                    AddOrder(o);

                    // с таким же идентификатором транзакции может быть заявка по другому инструменту
                    _allOrdersByTransactionId.TryAdd(Tuple.Create(transactionId, type == OrderTypes.Conditional), o);

                    return(new OrderInfo(o));
                });
            }

            var raiseNewOrder = info.RaiseNewOrder;

            if (raiseNewOrder && newOrderRaised)
            {
                info.RaiseNewOrder = false;
            }

            isNew = isNew2;
            return(Tuple.Create((Order)info, false, raiseNewOrder));
        }
コード例 #23
0
        /// <summary>
        /// Process <see cref="OrderStatusMessage"/>.
        /// </summary>
        /// <param name="message">A message requesting current registered orders and trades.</param>
        /// <returns>A message requesting current registered orders and trades.</returns>
        private OrderStatusMessage ProcessOrderStatus(OrderStatusMessage message)
        {
            if (message == null)
            {
                throw new ArgumentNullException(nameof(message));
            }

            if (!message.IsSubscribe)
            {
                return(message);
            }

            var transId = message.TransactionId;

            _orderStatusIds.Add(transId);

            if (!message.HasOrderId() && message.OriginalTransactionId == 0 && Settings.DaysLoad > TimeSpan.Zero)
            {
                var from = message.From ?? DateTime.UtcNow.Date - Settings.DaysLoad;
                var to   = message.To;

                if (Settings.IsMode(StorageModes.Snapshot))
                {
                    var storage = (ISnapshotStorage <string, ExecutionMessage>)GetSnapshotStorage(DataType.Transactions);

                    foreach (var snapshot in storage.GetAll(from, to))
                    {
                        if (snapshot.OrderId != null)
                        {
                            _orderIds.TryAdd(snapshot.OrderId.Value, snapshot.TransactionId);
                        }
                        else if (!snapshot.OrderStringId.IsEmpty())
                        {
                            _orderStringIds.TryAdd(snapshot.OrderStringId, snapshot.TransactionId);
                        }

                        snapshot.OriginalTransactionId = transId;
                        snapshot.SetSubscriptionIds(subscriptionId: transId);
                        RaiseNewOutMessage(snapshot);

                        from = snapshot.ServerTime;
                    }

                    if (from >= to)
                    {
                        return(null);
                    }

                    message.From = from;
                }
                else if (Settings.IsMode(StorageModes.Incremental))
                {
                    if (!message.SecurityId.IsDefault())
                    {
                        // TODO restore last actual state from incremental messages

                        //GetStorage<ExecutionMessage>(msg.SecurityId, ExecutionTypes.Transaction)
                        //	.Load(from, to)
                        //	.ForEach(RaiseStorageMessage);
                    }
                }
            }

            return(message);
        }
コード例 #24
0
        private void StartStorageTimer()
        {
            var isProcessing = false;
            var sync         = new SyncObject();

            var unkByOrderId       = new Dictionary <long, List <ExecutionMessage> >();
            var unkByOrderStringId = new Dictionary <string, List <ExecutionMessage> >(StringComparer.InvariantCultureIgnoreCase);

            ThreadingHelper.Timer(() =>
            {
                lock (sync)
                {
                    if (isProcessing)
                    {
                        return;
                    }

                    isProcessing = true;
                }

                try
                {
                    foreach (var pair in GetTicks())
                    {
                        GetStorage <ExecutionMessage>(pair.Key, ExecutionTypes.Tick).Save(pair.Value);
                    }

                    foreach (var pair in GetOrderLog())
                    {
                        GetStorage <ExecutionMessage>(pair.Key, ExecutionTypes.OrderLog).Save(pair.Value);
                    }

                    foreach (var pair in GetTransactions())
                    {
                        var secId = pair.Key;

                        if (Mode.Contains(StorageModes.Incremental))
                        {
                            GetStorage <ExecutionMessage>(secId, ExecutionTypes.Transaction).Save(pair.Value);
                        }

                        if (Mode.Contains(StorageModes.Snapshot))
                        {
                            var snapshotStorage = GetSnapshotStorage(DataType.Transactions);

                            foreach (var message in pair.Value)
                            {
                                // do not store cancellation commands into snapshot
                                if (message.IsCancellation /* && message.TransactionId != 0*/)
                                {
                                    continue;
                                }

                                var originTransId = message.OriginalTransactionId;

                                if (message.TransactionId == 0 && originTransId == 0)
                                {
                                    if (!message.HasTradeInfo)
                                    {
                                        continue;
                                    }

                                    long transId;

                                    if (message.OrderId != null)
                                    {
                                        if (!_orderIds.TryGetValue(message.OrderId.Value, out transId))
                                        {
                                            unkByOrderId.SafeAdd(message.OrderId.Value).Add(message);
                                            continue;
                                        }
                                    }
                                    else if (!message.OrderStringId.IsEmpty())
                                    {
                                        if (!_orderStringIds.TryGetValue(message.OrderStringId, out transId))
                                        {
                                            unkByOrderStringId.SafeAdd(message.OrderStringId).Add(message);
                                            continue;
                                        }
                                    }
                                    else
                                    {
                                        continue;
                                    }

                                    originTransId = transId;
                                }
                                else
                                {
                                    if (originTransId != 0)
                                    {
                                        if (/*message.TransactionId == 0 && */ _cancellationTransactions.TryGetValue(originTransId, out var temp))
                                        {
                                            // do not store cancellation errors
                                            if (message.Error != null)
                                            {
                                                continue;
                                            }

                                            // override cancel trans id by original order's registration trans id
                                            originTransId = temp;
                                        }

                                        if (_orderStatusIds.Contains(originTransId))
                                        {
                                            // override status request trans id by original order's registration trans id
                                            originTransId = message.TransactionId;
                                        }
                                    }

                                    if (originTransId != 0)
                                    {
                                        if (message.OrderId != null)
                                        {
                                            _orderIds.TryAdd(message.OrderId.Value, originTransId);
                                        }
                                        else if (message.OrderStringId != null)
                                        {
                                            _orderStringIds.TryAdd(message.OrderStringId, originTransId);
                                        }
                                    }
                                }

                                message.SecurityId = secId;

                                if (message.TransactionId == 0)
                                {
                                    message.TransactionId = originTransId;
                                }

                                message.OriginalTransactionId = 0;

                                SaveTransaction(snapshotStorage, message);

                                if (message.OrderId != null)
                                {
                                    if (unkByOrderId.TryGetValue(message.OrderId.Value, out var suspended))
                                    {
                                        unkByOrderId.Remove(message.OrderId.Value);

                                        foreach (var trade in suspended)
                                        {
                                            trade.TransactionId = message.TransactionId;
                                            SaveTransaction(snapshotStorage, trade);
                                        }
                                    }
                                }
                                else if (!message.OrderStringId.IsEmpty())
                                {
                                    if (unkByOrderStringId.TryGetValue(message.OrderStringId, out var suspended))
                                    {
                                        unkByOrderStringId.Remove(message.OrderStringId);

                                        foreach (var trade in suspended)
                                        {
                                            trade.TransactionId = message.TransactionId;
                                            SaveTransaction(snapshotStorage, trade);
                                        }
                                    }
                                }
                            }
                        }
                    }

                    foreach (var pair in GetOrderBooks())
                    {
                        if (Mode.Contains(StorageModes.Incremental))
                        {
                            GetStorage <QuoteChangeMessage>(pair.Key, null).Save(pair.Value);
                        }

                        if (Mode.Contains(StorageModes.Snapshot))
                        {
                            var snapshotStorage = GetSnapshotStorage(DataType.MarketDepth);

                            foreach (var message in pair.Value)
                            {
                                snapshotStorage.Update(message);
                            }
                        }
                    }

                    foreach (var pair in GetLevel1())
                    {
                        var messages = pair.Value.Where(m => m.Changes.Count > 0).ToArray();

                        var dt = DateTime.Today;

                        var historical = messages.Where(m => m.ServerTime < dt).ToArray();
                        var today      = messages.Where(m => m.ServerTime >= dt).ToArray();

                        GetStorage <Level1ChangeMessage>(pair.Key, null).Save(historical);

                        if (Mode.Contains(StorageModes.Incremental))
                        {
                            GetStorage <Level1ChangeMessage>(pair.Key, null).Save(today);
                        }

                        if (Mode.Contains(StorageModes.Snapshot))
                        {
                            var snapshotStorage = GetSnapshotStorage(DataType.Level1);

                            foreach (var message in today)
                            {
                                snapshotStorage.Update(message);
                            }
                        }
                    }

                    foreach (var pair in GetCandles())
                    {
                        GetStorage(pair.Key.Item1, pair.Key.Item2, pair.Key.Item3).Save(pair.Value);
                    }

                    foreach (var pair in GetPositionChanges())
                    {
                        var messages = pair.Value.Where(m => m.Changes.Count > 0).ToArray();

                        if (Mode.Contains(StorageModes.Incremental))
                        {
                            GetStorage <PositionChangeMessage>(pair.Key, null).Save(messages);
                        }

                        if (Mode.Contains(StorageModes.Snapshot))
                        {
                            var snapshotStorage = GetSnapshotStorage(DataType.PositionChanges);

                            foreach (var message in messages)
                            {
                                snapshotStorage.Update(message);
                            }
                        }
                    }

                    var news = GetNews().ToArray();

                    if (news.Length > 0)
                    {
                        StorageRegistry.GetNewsMessageStorage(Drive, Format).Save(news);
                    }
                }
                catch (Exception excp)
                {
                    excp.LogError();
                }
                finally
                {
                    lock (sync)
                        isProcessing = false;
                }
            }).Interval(TimeSpan.FromSeconds(10));
        }
コード例 #25
0
 /// <summary>
 /// 上线
 /// </summary>
 /// <param name="client"></param>
 /// <param name="accId"></param>
 public void OnLine(MobaClient client, int PlayerId)
 {
     clientIdDict.TryAdd(client, PlayerId);
     IdClientDict.TryAdd(PlayerId, client);
 }