Esempio n. 1
0
        public DepthLevel FindLevel(Price price, bool isBid, bool shouldCreate)
        {
            DepthLevel result;
            var        levels       = isBid ? Bids : Asks;
            var        excessLevels = isBid ? _excessBidLevels : _excessAskLevels;

            if (levels.TryGetValue(price, out result))
            {
                return(result);
            }
            if (excessLevels.TryGetValue(price, out result))
            {
                return(result);
            }

            if (shouldCreate)
            {
                if (levels.Count < _size)
                {
                    result = new DepthLevel(price, false);
                    ++LastChange;
                    result.LastChange = LastChange;
                    levels.Add(price, result);

                    foreach (KeyValuePair <Price, DepthLevel> depthLevel in levels)
                    {
                        if (isBid && price > depthLevel.Value.Price)
                        {
                            depthLevel.Value.LastChange = LastChange;
                        }

                        if (!isBid && price < depthLevel.Value.Price)
                        {
                            depthLevel.Value.LastChange = LastChange;
                        }
                    }
                    return(result);
                }

                var lastLevelPrice = LastLevel(levels);
                if (isBid && price < lastLevelPrice)
                {
                    // add to excess bid levels
                    var newDepthLevel = new DepthLevel(price, true);
                    excessLevels.Add(price, newDepthLevel);
                    result = newDepthLevel;

                    return(result);
                }
                if (!isBid && price > lastLevelPrice)
                {
                    // add to excess ask levels
                    var newDepthLevel = new DepthLevel(price, true);
                    _excessAskLevels.Add(price, newDepthLevel);
                    result = newDepthLevel;

                    return(result);
                }

                foreach (KeyValuePair <Price, DepthLevel> x in levels)
                {
                    if (isBid && x.Key < price)
                    {
                        InsertLevel(price, true);
                        levels.TryGetValue(price, out result);
                        break;
                    }

                    if (!isBid && x.Key > price)
                    {
                        InsertLevel(price, false);
                        levels.TryGetValue(price, out result);
                        break;
                    }
                }
            }

            return(result);
        }