Esempio n. 1
0
 /// <summary>
 /// Update latest values.
 /// </summary>
 /// <param name="time">Time.</param>
 /// <param name="price">Price.</param>
 /// <param name="volume">Volume.</param>
 /// <param name="side">Side.</param>
 /// <param name="openInterest">Open interest.</param>
 protected void Update(DateTimeOffset time, decimal price, decimal?volume, Sides?side, decimal?openInterest)
 {
     _time         = time;
     _price        = price;
     _volume       = volume;
     _side         = side;
     _openInterest = openInterest;
 }
Esempio n. 2
0
                    public override bool MoveNext()
                    {
                        if (_resetCurrent)
                        {
                            Current = null;

                            if (_needMoveNext && !_enumerator.MoveNext())
                            {
                                return(false);
                            }
                        }

                        _needMoveNext = true;

                        Sides?side = null;

                        do
                        {
                            var quote = _enumerator.Current;

                            if (Current == null)
                            {
                                Current = new QuoteChangeMessage
                                {
                                    SecurityId = _securityId,
                                    ServerTime = quote.ServerTime,
                                    LocalTime  = quote.LocalTime,
                                    Bids       = new List <QuoteChange>(),
                                    Asks       = new List <QuoteChange>(),
                                    IsSorted   = true,
                                };
                            }
                            else if (Current.ServerTime != quote.ServerTime || (side == Sides.Sell && quote.Side == Sides.Buy))
                            {
                                _resetCurrent = true;
                                _needMoveNext = false;

                                return(true);
                            }

                            side = quote.Side;

                            if (quote.Price != 0)
                            {
                                var quotes = (List <QuoteChange>)(quote.Side == Sides.Buy ? Current.Bids : Current.Asks);
                                quotes.Add(quote);
                            }
                        }while (_enumerator.MoveNext());

                        if (Current == null)
                        {
                            return(false);
                        }

                        _resetCurrent = true;
                        _needMoveNext = true;
                        return(true);
                    }
Esempio n. 3
0
 /// <summary>
 /// Update latest values.
 /// </summary>
 /// <param name="time">Time.</param>
 /// <param name="price">Price.</param>
 /// <param name="volume">Volume.</param>
 /// <param name="side">Side.</param>
 /// <param name="openInterest">Open interest.</param>
 /// <param name="priceLevels">Price levels.</param>
 protected void Update(DateTimeOffset time, decimal price, decimal?volume, Sides?side, decimal?openInterest, IEnumerable <CandlePriceLevel> priceLevels)
 {
     _time         = time;
     _price        = price;
     _volume       = volume;
     _side         = side;
     _openInterest = openInterest;
     _priceLevels  = priceLevels;
 }
Esempio n. 4
0
        public static void WriteNullableSide(this BitArrayWriter writer, Sides?value)
        {
            writer.Write(value != null);

            if (value is null)
            {
                return;
            }

            writer.Write(value.Value == Sides.Buy);
        }
Esempio n. 5
0
 public static void WriteSide(this BitArrayWriter writer, Sides?direction)
 {
     if (direction == null)
     {
         writer.Write(false);
     }
     else
     {
         writer.Write(true);
         writer.Write(direction == Sides.Buy);
     }
 }
Esempio n. 6
0
        public static IBSocket SendSide(this IBSocket socket, Sides?side)
        {
            if (side == null)
            {
                return(socket.Send(string.Empty));
            }

            switch (side.Value)
            {
            case Sides.Buy:
                return(socket.Send("BUY"));

            case Sides.Sell:
                return(socket.Send("SELL"));

            default:
                throw new ArgumentOutOfRangeException();
            }
        }
Esempio n. 7
0
        public void CancelOrders(bool?isStopOrder, string portfolioName, Sides?side, SecurityId securityId, SecurityTypes?securityType)
        {
            _adapter.AddDebugLog("CancelOrders: stop={0}, portf={1}, side={2}, id={3}", isStopOrder, portfolioName, side, securityId);

            var isBuySell = (side == null) ? null : side.Value.ToAlfaDirect();
            var account   = portfolioName.IsEmpty() ? null : portfolioName.AccountFromPortfolioName();
            var pCode     = securityId.SecurityCode.IsEmpty() ? null : securityId.SecurityCode;

            var treaties = new List <string>();
            var treaty   = account.IsEmpty() ? null : account.TreatyFromAccount();

            if (!treaty.IsEmpty())
            {
                treaties.Add(treaty);
            }
            else
            {
                var data = _tableAccounts.GetLocalDbData();
                treaties.AddRange(data.Select(row => FieldsAccounts.Treaty.GetStrValue(row.ToColumns())));
            }

            if (!treaties.Any())
            {
                throw new InvalidOperationException(LocalizedStrings.Str2277Params.Put(portfolioName));
            }

            string placeCode = null;

            if (!securityId.IsDefault())
            {
                placeCode = _adapter.SecurityClassInfo.GetSecurityClass(securityType, securityId.BoardCode);

                if (placeCode == null)
                {
                    throw new InvalidOperationException(LocalizedStrings.Str2278);
                }
            }

            foreach (var t in treaties)
            {
                _ad.DropOrder(null, isBuySell, t, account, placeCode, pCode, -1);
            }
        }
Esempio n. 8
0
 /// <summary>
 /// Отменить группу заявок на бирже по фильтру.
 /// </summary>
 /// <param name="transactionId">Идентификатор транзакции отмены.</param>
 /// <param name="isStopOrder"><see langword="true"/>, если нужно отменить только стоп-заявки, <see langword="false"/> - если только обычный и <see langword="null"/> - если оба типа.</param>
 /// <param name="portfolio">Портфель. Если значение равно <see langword="null"/>, то портфель не попадает в фильтр снятия заявок.</param>
 /// <param name="direction">Направление заявки. Если значение равно <see langword="null"/>, то направление не попадает в фильтр снятия заявок.</param>
 /// <param name="board">Торговая площадка. Если значение равно <see langword="null"/>, то площадка не попадает в фильтр снятия заявок.</param>
 /// <param name="security">Инструмент. Если значение равно <see langword="null"/>, то инструмент не попадает в фильтр снятия заявок.</param>
 /// <param name="securityType">Тип инструмента. Если значение равно <see langword="null"/>, то тип не попадает в фильтр снятия заявок.</param>
 protected override void OnCancelOrders(long transactionId, bool?isStopOrder = null, Portfolio portfolio = null, Sides?direction = null, ExchangeBoard board = null, Security security = null, SecurityTypes?securityType = null)
 {
     if (security != null && portfolio != null && security.Type == SecurityTypes.Future && !security.UnderlyingSecurityId.IsEmpty())
     {
         base.OnCancelOrders(transactionId, isStopOrder, portfolio, direction, board, security);
     }
     else
     {
         this.CancelOrders(Orders, isStopOrder, portfolio, direction, board, null, securityType);
     }
 }
Esempio n. 9
0
        private static RenkoCandleMessage CreateCandle(ICandleBuilderSubscription subscription, DataType buildFrom, Unit boxSize, decimal openPrice, decimal renkoStep, decimal price, decimal?volume, Sides?side, DateTimeOffset time, decimal?oi)
        {
            var candle = new RenkoCandleMessage
            {
                SecurityId = subscription.Message.SecurityId,
                BoxSize    = boxSize,
                BuildFrom  = buildFrom,

                OpenPrice  = openPrice,
                ClosePrice = openPrice + renkoStep,
                //HighPrice = openPrice + renkoStep,
                //LowPrice = openPrice,
                OpenVolume     = volume,
                CloseVolume    = volume,
                HighVolume     = volume,
                LowVolume      = volume,
                OpenTime       = time,
                CloseTime      = time,
                HighTime       = time,
                LowTime        = time,
                RelativeVolume = side == null ? null : (side == Sides.Buy ? volume : -volume),
                TotalTicks     = 1,
                State          = CandleStates.Active,
                OpenInterest   = oi,
            };

            if (volume != null)
            {
                candle.TotalPrice  += price * volume.Value;
                candle.TotalVolume += volume.Value;
            }

            if (renkoStep > 0)
            {
                candle.HighPrice = candle.ClosePrice;
                candle.LowPrice  = candle.OpenPrice;
            }
            else
            {
                candle.HighPrice = candle.OpenPrice;
                candle.LowPrice  = candle.ClosePrice;
            }

            if (subscription.Message.IsCalcVolumeProfile)
            {
                var levels = new List <CandlePriceLevel>();

                subscription.VolumeProfile = new VolumeProfileBuilder(levels);
                subscription.VolumeProfile.Update(price, volume, side);

                candle.PriceLevels = levels;
            }

            return(candle);
        }
Esempio n. 10
0
        private static PnFCandleMessage CreateCandle(ICandleBuilderSubscription subscription, DataType buildFrom, PnFArg pnfArg, decimal openPrice, decimal highPrice, decimal lowPrice, decimal closePrice, decimal price, decimal?volume, Sides?side, DateTimeOffset time, decimal?oi)
        {
            var candle = new PnFCandleMessage
            {
                SecurityId = subscription.Message.SecurityId,
                PnFArg     = pnfArg,
                BuildFrom  = buildFrom,

                OpenPrice  = openPrice,
                ClosePrice = closePrice,
                HighPrice  = highPrice,
                LowPrice   = lowPrice,
                OpenVolume = volume,
                //CloseVolume = volume,
                HighVolume = volume,
                LowVolume  = volume,
                OpenTime   = time,
                //CloseTime = time,
                HighTime = time,
                LowTime  = time,
                State    = CandleStates.Active,
            };

            if (subscription.Message.IsCalcVolumeProfile)
            {
                var levels = new List <CandlePriceLevel>();
                subscription.VolumeProfile = new VolumeProfileBuilder(levels);
                candle.PriceLevels         = levels;
            }

            UpdateCandle(candle, price, volume, time, side, oi, subscription.VolumeProfile);

            return(candle);
        }
Esempio n. 11
0
        private static void UpdateCandle(PnFCandleMessage currentPnFCandle, decimal price, decimal?volume, DateTimeOffset time, Sides?side, decimal?oi, VolumeProfileBuilder volumeProfile)
        {
            currentPnFCandle.TotalTicks = currentPnFCandle.TotalTicks ?? 0 + 1;

            if (volume != null)
            {
                var v = volume.Value;

                currentPnFCandle.TotalVolume += v;
                currentPnFCandle.TotalPrice  += v * price;

                currentPnFCandle.RelativeVolume = currentPnFCandle.RelativeVolume ?? 0 + (side == Sides.Buy ? v : -v);
            }

            currentPnFCandle.CloseVolume = volume;
            currentPnFCandle.CloseTime   = time;

            volumeProfile?.Update(price, volume, side);

            currentPnFCandle.OpenInterest = oi;
        }
Esempio n. 12
0
        ///// <summary>
        ///// Событие о появлении отчета о комиссии по сделке.
        ///// </summary>
        //public event Action<IBCommission> NewCommission;

        /// <summary>
        /// Cancel orders by filter.
        /// </summary>
        /// <param name="transactionId">Order cancellation transaction id.</param>
        /// <param name="isStopOrder"><see langword="true" />, if cancel only a stop orders, <see langword="false" /> - if regular orders, <see langword="null" /> - both.</param>
        /// <param name="portfolio">Portfolio. If the value is equal to <see langword="null" />, then the portfolio does not match the orders cancel filter.</param>
        /// <param name="direction">Order side. If the value is <see langword="null" />, the direction does not use.</param>
        /// <param name="board">Trading board. If the value is equal to <see langword="null" />, then the board does not match the orders cancel filter.</param>
        /// <param name="security">Instrument. If the value is equal to <see langword="null" />, then the instrument does not match the orders cancel filter.</param>
        protected override void OnCancelOrders(long transactionId, bool?isStopOrder = null, Portfolio portfolio = null, Sides?direction = null, ExchangeBoard board = null, Security security = null)
        {
            if (isStopOrder == null && portfolio == null && direction == null && board == null && security == null)
            {
                base.OnCancelOrders(transactionId);
            }
            else
            {
                this.CancelOrders(Orders, isStopOrder, portfolio, direction, board, security);
            }
        }
Esempio n. 13
0
        private static RenkoCandleMessage CreateCandle(MarketDataMessage message, Unit boxSize, decimal openPrice, decimal renkoStep, decimal price, decimal?volume, Sides?side, DateTimeOffset time, decimal?oi)
        {
            var candle = new RenkoCandleMessage
            {
                OpenPrice  = openPrice,
                ClosePrice = openPrice + renkoStep,
                //HighPrice = openPrice + renkoStep,
                //LowPrice = openPrice,
                OpenVolume     = volume,
                CloseVolume    = volume,
                HighVolume     = volume,
                LowVolume      = volume,
                SecurityId     = message.SecurityId,
                OpenTime       = time,
                CloseTime      = time,
                HighTime       = time,
                LowTime        = time,
                BoxSize        = boxSize,
                RelativeVolume = side == null ? null : (side == Sides.Buy ? volume : -volume),
                TotalTicks     = 1,
                State          = CandleStates.Active,
                OpenInterest   = oi,
            };

            if (volume != null)
            {
                candle.TotalPrice  += price * volume.Value;
                candle.TotalVolume += volume.Value;
            }

            if (renkoStep > 0)
            {
                candle.HighPrice = candle.ClosePrice;
                candle.LowPrice  = candle.OpenPrice;
            }
            else
            {
                candle.HighPrice = candle.OpenPrice;
                candle.LowPrice  = candle.ClosePrice;
            }

            if (message.IsCalcVolumeProfile)
            {
                candle.VolumeProfile = new CandleMessageVolumeProfile();
                candle.VolumeProfile.Update(price, volume, side);
            }

            return(candle);
        }
Esempio n. 14
0
        private static PnFCandleMessage CreateCandle(MarketDataMessage message, PnFArg pnfArg, decimal openPrice, decimal highPrice, decimal lowPrice, decimal closePrice, decimal price, decimal?volume, Sides?side, DateTimeOffset time, decimal?oi)
        {
            var candle = new PnFCandleMessage
            {
                OpenPrice  = openPrice,
                ClosePrice = closePrice,
                HighPrice  = highPrice,
                LowPrice   = lowPrice,
                OpenVolume = volume,
                //CloseVolume = volume,
                HighVolume = volume,
                LowVolume  = volume,
                SecurityId = message.SecurityId,
                OpenTime   = time,
                //CloseTime = time,
                HighTime = time,
                LowTime  = time,
                PnFArg   = pnfArg,
                State    = CandleStates.Active,
            };

            if (message.IsCalcVolumeProfile)
            {
                candle.VolumeProfile = new CandleMessageVolumeProfile();
            }

            UpdateCandle(candle, price, volume, time, side, oi);

            return(candle);
        }
Esempio n. 15
0
        private Key CreateKey(Portfolio portfolio, Security security, string strategyId, Sides?side, string clientCode, string depoName, TPlusLimits?limitType)
        {
            if (portfolio is null)
            {
                throw new ArgumentNullException(nameof(portfolio));
            }

            if (security is null)
            {
                throw new ArgumentNullException(nameof(security));
            }

            if (depoName is null)
            {
                depoName = string.Empty;
            }

            if (clientCode is null)
            {
                clientCode = string.Empty;
            }

            return(Tuple.Create(portfolio, security, strategyId?.ToLowerInvariant() ?? string.Empty, side, clientCode?.ToLowerInvariant() ?? string.Empty, depoName?.ToLowerInvariant() ?? string.Empty, limitType));
        }
Esempio n. 16
0
 /// <summary>
 /// Отменить группу заявок на бирже по фильтру.
 /// </summary>
 /// <param name="isStopOrder"><see langword="true"/>, если нужно отменить только стоп-заявки, false - если только обычный и null - если оба типа.</param>
 /// <param name="portfolio">Портфель. Если значение равно null, то портфель не попадает в фильтр снятия заявок.</param>
 /// <param name="direction">Направление заявки. Если значение равно null, то направление не попадает в фильтр снятия заявок.</param>
 /// <param name="board">Торговая площадка. Если значение равно null, то площадка не попадает в фильтр снятия заявок.</param>
 /// <param name="security">Инструмент. Если значение равно null, то инструмент не попадает в фильтр снятия заявок.</param>
 public void CancelOrders(bool?isStopOrder = null, Portfolio portfolio = null, Sides?direction = null, ExchangeBoard board = null, Security security = null)
 {
     Connector.CancelOrders(isStopOrder, portfolio, direction, board, security);
 }
Esempio n. 17
0
 /// <inheritdoc />
 public Position GetPosition(Portfolio portfolio, Security security, string strategyId, Sides?side, string clientCode = "", string depoName = "", TPlusLimits?limitType = null)
 {
     return(_positions.TryGetValue(CreateKey(portfolio, security, strategyId, side, clientCode, depoName, limitType)));
 }
                public override bool MoveNext()
                {
                    if (_resetCurrent)
                    {
                        Current = null;

                        if (_needMoveNext && !_enumerator.MoveNext())
                        {
                            return(false);
                        }
                    }

                    _needMoveNext = true;

                    Sides?side = null;

                    var bids = new List <QuoteChange>();
                    var asks = new List <QuoteChange>();

                    do
                    {
                        var quote = _enumerator.Current;

                        if (quote == null)
                        {
                            throw new InvalidOperationException("quote == null");
                        }

                        if (Current == null)
                        {
                            Current = new QuoteChangeMessage
                            {
                                SecurityId = _securityId,
                                ServerTime = quote.ServerTime,
                                LocalTime  = quote.LocalTime,
                                IsSorted   = true,
                            };
                        }
                        else if (Current.ServerTime != quote.ServerTime || (side == Sides.Sell && quote.Side == Sides.Buy))
                        {
                            _resetCurrent = true;
                            _needMoveNext = false;

                            Current.Bids = bids.ToArray();
                            Current.Asks = asks.ToArray();

                            return(true);
                        }

                        side = quote.Side;

                        if (quote.Price != null)
                        {
                            var quotes = quote.Side == Sides.Buy ? bids : asks;
                            quotes.Add(new QuoteChange(quote.Side, quote.Price.Value, quote.Volume));
                        }
                    }while (_enumerator.MoveNext());

                    if (Current == null)
                    {
                        return(false);
                    }

                    Current.Bids = bids.ToArray();
                    Current.Asks = asks.ToArray();

                    _resetCurrent = true;
                    _needMoveNext = true;
                    return(true);
                }
 public string ToChar(Sides?side)
 {
     return(side == null ? "" : side == Sides.Buy ? "B" : "S");
 }
        private Position GetPosition(SecurityId securityId, string portfolioName, string strategyId, Sides?side)
        {
            var security = (!securityId.SecurityCode.IsEmpty() && !securityId.BoardCode.IsEmpty() ? _securityStorage.LookupById(securityId) : _securityStorage.Lookup(new Security
            {
                Code = securityId.SecurityCode,
            }).FirstOrDefault()) ?? TryCreateSecurity(securityId);

            if (security == null)
            {
                return(null);
            }

            var portfolio = _positionStorage.LookupByPortfolioName(portfolioName);

            if (portfolio == null)
            {
                portfolio = new Portfolio
                {
                    Name = portfolioName
                };

                _positionStorage.Save(portfolio);
            }

            return(_positionStorage.GetPosition(portfolio, security, strategyId, side) ?? new Position
            {
                Security = security,
                Portfolio = portfolio,
                StrategyId = strategyId,
                Side = side,
            });
        }
                public override bool MoveNext()
                {
                    if (_resetCurrent)
                    {
                        Current = null;

                        if (_needMoveNext && !_enumerator.MoveNext())
                        {
                            return(false);
                        }
                    }

                    _needMoveNext = true;

                    Sides?side = null;

                    var bids = new List <QuoteChange>();
                    var asks = new List <QuoteChange>();

                    var hasPos = false;

                    void Flush()
                    {
                        Current.Bids         = bids.ToArray();
                        Current.Asks         = asks.ToArray();
                        Current.HasPositions = hasPos;
                    }

                    do
                    {
                        var quote = _enumerator.Current;

                        if (quote == null)
                        {
                            throw new InvalidOperationException("quote == null");
                        }

                        if (Current == null)
                        {
                            Current = new QuoteChangeMessage
                            {
                                SecurityId = _securityId,
                                ServerTime = quote.ServerTime,
                                LocalTime  = quote.LocalTime,
                            };
                        }
                        else if (Current.ServerTime != quote.ServerTime || (side == Sides.Sell && quote.Side == Sides.Buy))
                        {
                            _resetCurrent = true;
                            _needMoveNext = false;

                            Flush();
                            return(true);
                        }

                        side = quote.Side;

                        if (quote.Quote != null)
                        {
                            var qq = quote.Quote.Value;

                            if (qq.StartPosition != default || qq.EndPosition != default)
                            {
                                hasPos = true;
                            }

                            var quotes = quote.Side == Sides.Buy ? bids : asks;
                            quotes.Add(new QuoteChange(qq.Price, qq.Volume, qq.OrdersCount, qq.Condition));
                        }
                    }while (_enumerator.MoveNext());

                    if (Current == null)
                    {
                        return(false);
                    }

                    _resetCurrent = true;
                    _needMoveNext = true;

                    Flush();
                    return(true);
                }
Esempio n. 22
0
        /// <summary>
        /// To add a change to the collection, if value is other than <see langword="null"/>.
        /// </summary>
        /// <typeparam name="TMessage">Change message type.</typeparam>
        /// <typeparam name="TChange">Change type.</typeparam>
        /// <param name="message">Change message.</param>
        /// <param name="type">Change type.</param>
        /// <param name="value">Change value.</param>
        /// <returns>Change message.</returns>
        public static TMessage TryAdd <TMessage, TChange>(this TMessage message, TChange type, Sides?value)
            where TMessage : BaseChangeMessage <TMessage, TChange>, new()
        {
            if (value == null)
            {
                return(message);
            }

            return(message.Add(type, value.Value));
        }
Esempio n. 23
0
 public void SidesValueMassTest(object obj, bool ignoreStatus, Sides?expected)
 {
     Assert.True(EnumUtils.GetEnumValue <Sides>(obj, ignoreStatus) == expected);
 }