Exemple #1
0
        /// <summary>
        /// Получить хранилище маркет-данных.
        /// </summary>
        /// <param name="path">Путь к данным.</param>
        /// <returns>Хранилище маркет-данных.</returns>
        public IMarketDataDrive GetDrive(string path)
        {
            if (path.IsEmpty())
            {
                return(DefaultDrive);
            }

            return(_drives.SafeAdd(path ?? string.Empty, key =>
            {
                IMarketDataDrive drive;

                try
                {
                    var addr = path.To <EndPoint>();
                    drive = new RemoteMarketDataDrive(new RemoteStorageClient(new Uri(addr.To <string>())));
                }
                catch
                {
                    drive = new LocalMarketDataDrive(path);
                }

                NewDriveCreated.SafeInvoke(drive);

                return drive;
            }));
        }
        /// <summary>
        /// Зарегистрировать индикатор. После регистрации данный индикатор начнет обновляться с использованием переданного источника.
        /// Если по данному источнику уже есть сохраненные данные, то они будут использованы для инициализации индикатора.
        /// Если пара индикатор-источник уже была ранее зарегистрирована, то вернется существующий токен.
        /// </summary>
        /// <param name="indicator">Индикатор.</param>
        /// <param name="source">Источник данных для индикатора.</param>
        /// <returns>Токен, который был зарегистрирован.</returns>
        public virtual IndicatorToken RegisterIndicator(IIndicator indicator, IIndicatorSource source)
        {
            lock (_indicatorUsages.SyncRoot)
            {
                var token = new IndicatorToken(indicator, source);

                var inDict = _indicatorUsages.TryGetValue(token);
                if (inDict != null)
                {
                    //найден индикатор, увеличим количество ссылок
                    inDict.Second++;
                    return(inDict.First);
                }

                //индикатора нет, добавим
                lock (_sources.SyncRoot)
                {
                    var indicators = _sources.SafeAdd(source, key => new IndicatorList(this, key));

                    token = new IndicatorToken(indicator, indicators.Source)
                    {
                        Container = Container
                    };
                    _indicatorUsages.Add(token, new RefPair <IndicatorToken, int>(token, 1));
                    indicators.Add(token);                     // тут пройдет подписка на события источника и обработка тех значений, которые уже есть в источнике
                }

                return(token);
            }
        }
Exemple #3
0
        /// <summary>
        /// To get the storage for <paramref name="path"/>.
        /// </summary>
        /// <param name="path">Path.</param>
        /// <returns>Market data storage.</returns>
        public IMarketDataDrive GetDrive(string path)
        {
            if (path.IsEmpty() || Guid.TryParse(path, out _) /* TODO remove few versions later 2019-08-06 */)
            {
                return(DefaultDrive);
            }

            var pair = CreatePair(path);

            return(_drives.SafeAdd(pair, key =>
            {
                IMarketDataDrive drive;

                if (pair.Item2 == null)
                {
                    drive = new LocalMarketDataDrive(path);
                }
                else
                {
                    drive = new RemoteMarketDataDrive(new RemoteStorageClient(new Uri(pair.Item2.To <string>())));
                }

                NewDriveCreated?.Invoke(drive);

                return drive;
            }));
        }
Exemple #4
0
            public void StartTimeOut(long key)
            {
                //if (key == 0)
                //	throw new ArgumentNullException(nameof(key));

                _registeredKeys.SafeAdd(key, s => TimeOut);
            }
Exemple #5
0
        private void ChangePosition(Security security, Portfolio portfolio, decimal diff)
        {
            if (security == null)
            {
                throw new ArgumentNullException("security");
            }

            if (portfolio == null)
            {
                throw new ArgumentNullException("portfolio");
            }

            bool isNew;
            var  position = _positions.SafeAdd(Tuple.Create(security, portfolio),
                                               key => new Position {
                Security = key.Item1, Portfolio = key.Item2
            }, out isNew);

            position.CurrentValue += diff;

            if (isNew)
            {
                NewPosition.SafeInvoke(position);
            }
            else
            {
                PositionChanged.SafeInvoke(position);
            }
        }
Exemple #6
0
        /// <summary>
        /// To calculate trade profitability. If the trade was already processed earlier, previous information returns.
        /// </summary>
        /// <param name="trade">Trade.</param>
        /// <param name="info">Information on new trade.</param>
        /// <returns><see langword="true" />, if new trade received, otherwise, <see langword="false" />.</returns>
        public bool ProcessMyTrade(ExecutionMessage trade, out PnLInfo info)
        {
            if (trade == null)
            {
                throw new ArgumentNullException(nameof(trade));
            }

            info = null;

            var tradeId       = trade.TradeId;
            var tradeStringId = trade.TradeStringId;

            if (tradeId != null)
            {
                if (_tradeByIdInfos.TryGetValue(tradeId.Value, out info))
                {
                    return(false);
                }

                var queue = _securityPnLs.SafeAdd(trade.SecurityId, security => new PnLQueue(security));

                info = queue.Process(trade);

                _tradeByIdInfos.Add(tradeId.Value, info);
                _realizedPnL += info.PnL;
                return(true);
            }
            else if (!tradeStringId.IsEmpty())
            {
                if (_tradeByStringIdInfos.TryGetValue(tradeStringId, out info))
                {
                    return(false);
                }

                var queue = _securityPnLs.SafeAdd(trade.SecurityId, security => new PnLQueue(security));

                info = queue.Process(trade);

                _tradeByStringIdInfos.Add(tradeStringId, info);
                _realizedPnL += info.PnL;
                return(true);
            }

            return(false);
        }
Exemple #7
0
 /// <summary>
 /// Создать инструмент по идентификатору.
 /// </summary>
 /// <param name="id">Идентификатор инструмента.</param>
 /// <returns>Созданный инструмент.</returns>
 public override Security CreateSecurity(string id)
 {
     return(_securities.SafeAdd(id, key =>
     {
         var security = base.CreateSecurity(key);
         _securityList.Add(security);
         return security;
     }));
 }
            /// <summary>
            /// Запустить ожидание для ключа.
            /// </summary>
            /// <param name="key">Ключ.</param>
            public void StartTimeOut(T key)
            {
                if (key.IsNull(true))
                {
                    throw new ArgumentNullException("key");
                }

                _registeredKeys.SafeAdd(key, s => TimeOut);
            }
        /// <summary>
        /// Обновить профиль новым значением.
        /// </summary>
        /// <param name="value">Значение.</param>
        public void Update(ICandleBuilderSourceValue value)
        {
            if (value.OrderDirection == null)
            {
                return;
            }

            _volumeProfileInfo.SafeAdd(value.Price, key => new PriceLevel(key)).Update(value);
        }
Exemple #10
0
        /// <summary>
        /// To process the message, containing market data or trade. If the trade was already processed earlier, previous information returns.
        /// </summary>
        /// <param name="message">The message, containing market data or trade.</param>
        /// <returns>Information on new trade.</returns>
        public PnLInfo ProcessMessage(Message message)
        {
            if (message == null)
            {
                throw new ArgumentNullException(nameof(message));
            }

            switch (message.Type)
            {
            case MessageTypes.Reset:
            {
                Reset();
                return(null);
            }

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

                switch (trade.ExecutionType)
                {
                case ExecutionTypes.Trade:
                {
                    // TODO
                    if (trade.PortfolioName.IsEmpty())
                    {
                        return(null);
                    }

                    lock (_portfolioManagers.SyncRoot)
                    {
                        var manager = _portfolioManagers.SafeAdd(trade.PortfolioName, pf => new PortfolioPnLManager(pf));

                        PnLInfo info;

                        if (manager.ProcessMyTrade(trade, out info))
                        {
                            _realizedPnL += info.PnL;
                        }

                        return(info);
                    }
                }
                }

                break;
            }
            }

            foreach (var pnLManager in _portfolioManagers.CachedValues)
            {
                pnLManager.ProcessMessage(message);
            }

            return(null);
        }
Exemple #11
0
        IEnumerable <Security> ISecurityProvider.Lookup(Security criteria)
        {
            if (criteria.IsLookupAll())
            {
                return(_securities.CachedValues);
            }

            return(_registry
                   .Securities
                   .Lookup(criteria)
                   .Select(security => _securities.SafeAdd(security.Id, id => security))
                   .ToArray());
        }
Exemple #12
0
        private void AddExport(Security security, MarketDataTypes type)
        {
            if (security == null)
            {
                throw new ArgumentNullException("security");
            }

            _exports.SafeAdd(security).SafeAdd(type);

            if (ConnectionState == ConnectionStates.Connected)
            {
                base.SubscribeMarketData(security, type);
            }
        }
Exemple #13
0
            public void StartTimeOut(long transactionId, TimeSpan timeOut)
            {
                if (transactionId == 0)
                {
                    //throw new ArgumentNullException(nameof(transactionId));
                    return;
                }

                if (timeOut == default)
                {
                    return;
                }

                _registeredIds.SafeAdd(transactionId, s => timeOut);
            }
        IExtendedInfoStorageItem IExtendedInfoStorage.Create(string storageName, Tuple <string, Type>[] fields)
        {
            if (storageName.IsEmpty())
            {
                throw new ArgumentNullException(nameof(storageName));
            }

            var fileName = Path.Combine(_path, storageName + ".csv");

            return(_items.SafeAdd(storageName, key =>
            {
                var item = new CsvExtendedInfoStorageItem(this, fileName, fields);
                item.Init();
                return item;
            }));
        }
        private void ProcessConnectMessage(IMessageAdapter innerAdapter, ConnectMessage message)
        {
            if (message.Error != null)
            {
                this.AddErrorLog(LocalizedStrings.Str625Params, innerAdapter.GetType().Name, message.Error);
            }

            var adapter = _hearbeatAdapters[innerAdapter];

            foreach (var supportedMessage in adapter.SupportedMessages)
            {
                _connectedAdapters.SafeAdd(supportedMessage).Add(adapter);
            }

            SendOutMessage(message);
        }
            public void StartTimeOut(long transactionId, TimeSpan timeOut)
            {
                if (transactionId == 0)
                {
                    //throw new ArgumentNullException(nameof(transactionId));
                    return;
                }

                if (timeOut == default)
                {
                    return;
                }

                _logReceiver.AddInfoLog("Lookup timeout {0} started for {1}.", timeOut, transactionId);
                _registeredIds.SafeAdd(transactionId, s => timeOut);
            }
Exemple #17
0
        private void ProcessAccount(AccountInfo account)
        {
            bool isNew;

            _accounts.SafeAdd(account.AccountId, key => account, out isNew);

            if (!isNew)
            {
                return;
            }

            SendOutMessage(new PortfolioMessage
            {
                PortfolioName = account.AccountId,
                State         = account.RmsInfo == null ? null : account.RmsInfo.Status.ToPortfolioState(),
            });
        }
Exemple #18
0
        public Security TryAddSecurity(string id, Func <string, Tuple <string, ExchangeBoard> > idConvert, out bool isNew)
        {
            if (idConvert == null)
            {
                throw new ArgumentNullException(nameof(idConvert));
            }

            return(_securities.SafeAdd(id, key =>
            {
                var s = EntityFactory.CreateSecurity(key);

                if (s == null)
                {
                    throw new InvalidOperationException(LocalizedStrings.Str1102Params.Put(key));
                }

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

                var info = idConvert(key);

                if (s.Board == null)
                {
                    s.Board = info.Item2;
                }

                if (s.Code.IsEmpty())
                {
                    s.Code = info.Item1;
                }

                if (s.Name.IsEmpty())
                {
                    s.Name = info.Item1;
                }

                if (s.Class.IsEmpty())
                {
                    s.Class = info.Item2.Code;
                }

                return s;
            }, out isNew));
        }
Exemple #19
0
        public Tuple <Portfolio, bool, bool> ProcessPortfolio(string name, Func <Portfolio, bool> changePortfolio = null)
        {
            if (name.IsEmpty())
            {
                throw new ArgumentNullException("name");
            }

            bool isNew;

            var portfolio = _portfolios.SafeAdd(name, key =>
            {
                var p = EntityFactory.CreatePortfolio(key);

                if (p == null)
                {
                    throw new InvalidOperationException(LocalizedStrings.Str1104Params.Put(name));
                }

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

                //TODO p.Connector = this;
                return(p);
            }, out isNew);

            var isChanged = false;

            if (changePortfolio != null)
            {
                isChanged = changePortfolio(portfolio);
            }

            if (isNew)
            {
                return(Tuple.Create(portfolio, true, false));
            }

            if (changePortfolio != null && isChanged)
            {
                return(Tuple.Create(portfolio, false, true));
            }

            return(Tuple.Create(portfolio, false, false));
        }
Exemple #20
0
        IEnumerable <Security> ISecurityProvider.Lookup(Security criteria)
        {
            if (criteria == null)
            {
                throw new ArgumentNullException("criteria");
            }

            if (criteria.Code == "*")
            {
                return(_securities.CachedValues);
            }

            return(_registry
                   .Securities
                   .Lookup(criteria)
                   .Select(security => _securities.SafeAdd(security.Id, id => security))
                   .ToArray());
        }
Exemple #21
0
        /// <summary>
        /// To calculate trade profitability. If the trade was already processed earlier, previous information returns.
        /// </summary>
        /// <param name="trade">Trade.</param>
        /// <returns>Information on new trade.</returns>
        public virtual PnLInfo ProcessMyTrade(ExecutionMessage trade)
        {
            if (trade == null)
            {
                throw new ArgumentNullException("trade");
            }

            lock (_portfolioManagers.SyncRoot)
            {
                var manager = _portfolioManagers.SafeAdd(trade.PortfolioName, pf => new PortfolioPnLManager(pf));

                PnLInfo info;

                if (manager.ProcessMyTrade(trade, out info))
                {
                    _realizedPnL += info.PnL;
                }

                return(info);
            }
        }
Exemple #22
0
        /// <summary>
        /// Рассчитать прибыльность сделки. Если сделка уже ранее была обработана, то возвращается предыдущая информация.
        /// </summary>
        /// <param name="trade">Сделка.</param>
        /// <param name="info">Информация о новой сделке.</param>
        /// <returns><see langword="true"/>, если получена новая сделка, иначе, <see langword="false"/>.</returns>
        public bool ProcessMyTrade(ExecutionMessage trade, out PnLInfo info)
        {
            if (trade == null)
            {
                throw new ArgumentNullException("trade");
            }

            if (_tradeInfos.TryGetValue(trade.TradeId, out info))
            {
                return(false);
            }

            var queue = _securityPnLs.SafeAdd(trade.SecurityId, security => new PnLQueue(security));

            info = queue.Process(trade);

            _tradeInfos.Add(trade.TradeId, info);
            _realizedPnL += info.PnL;

            return(true);
        }
        /// <summary>
        /// To get the snapshot storage.
        /// </summary>
        /// <param name="dataType">Market data type.</param>
        /// <param name="arg">The parameter associated with the <paramref name="dataType" /> type. For example, <see cref="CandleMessage.Arg"/>.</param>
        /// <returns>The snapshot storage.</returns>
        public ISnapshotStorage GetSnapshotStorage(Type dataType, object arg)
        {
            return(_snapshotStorages.SafeAdd(DataType.Create(dataType, arg), key =>
            {
                SnapshotStorage storage;

                if (dataType == typeof(Level1ChangeMessage))
                {
                    storage = new SnapshotStorage <SecurityId, Level1ChangeMessage>(_path, new Level1BinarySnapshotSerializer());
                }
                else if (dataType == typeof(QuoteChangeMessage))
                {
                    storage = new SnapshotStorage <SecurityId, QuoteChangeMessage>(_path, new QuotesBinarySnapshotSerializer());
                }
                else if (dataType == typeof(PositionChangeMessage))
                {
                    storage = new SnapshotStorage <SecurityId, PositionChangeMessage>(_path, new PositionBinarySnapshotSerializer());
                }
                else if (dataType == typeof(ExecutionMessage))
                {
                    switch ((ExecutionTypes)arg)
                    {
                    case ExecutionTypes.Transaction:
                        storage = new SnapshotStorage <string, ExecutionMessage>(_path, new TransactionBinarySnapshotSerializer());
                        break;

                    default:
                        throw new ArgumentOutOfRangeException(nameof(arg), arg, LocalizedStrings.Str1219);
                    }
                }
                else
                {
                    throw new ArgumentOutOfRangeException(nameof(dataType), dataType, LocalizedStrings.Str1018);
                }

                return storage;
            }));
        }
Exemple #24
0
 /// <inheritdoc />
 public FileInfoMessage GetFileInfo(long id)
 {
     return(_cache.SafeAdd(id, key => Invoke(f => f.GetFileInfo2(NullableSessionId ?? Guid.Empty, id))));
 }
Exemple #25
0
 /// <summary>
 /// To get the file data.
 /// </summary>
 /// <param name="id">File ID.</param>
 /// <returns>The file data.</returns>
 public FileData GetFileInfo(long id)
 {
     return(_cache.SafeAdd(id, key => Invoke(f => f.GetFileInfo(TryGetSession ?? Guid.Empty, id))));
 }
Exemple #26
0
 /// <summary>
 /// Получить информацию о пользователе.
 /// </summary>
 /// <param name="userId">Идентификатор пользователя.</param>
 /// <returns>Информация о пользователе.</returns>
 public User GetUser(long userId)
 {
     return(_users.SafeAdd(userId, key => Invoke(f => f.GetUser(SessionId, userId))));
 }
Exemple #27
0
 /// <inheritdoc />
 public FileInfoMessage GetFileInfo(long id)
 {
     return(_cache.SafeAdd(id, key => Invoke(f => f.GetFileInfo2(SessionId, id)).TypedClone()));
 }
Exemple #28
0
 /// <summary>
 /// Создать портфель по номеру счета.
 /// </summary>
 /// <param name="name">Номер счета.</param>
 /// <returns>Созданный портфель.</returns>
 public override Portfolio CreatePortfolio(string name)
 {
     return(_portfolios.SafeAdd(name, key => base.CreatePortfolio(key)));
 }
Exemple #29
0
        /// <inheritdoc />
        public PnLInfo ProcessMessage(Message message, ICollection <PortfolioPnLManager> changedPortfolios)
        {
            if (message == null)
            {
                throw new ArgumentNullException(nameof(message));
            }

            switch (message.Type)
            {
            case MessageTypes.Reset:
            {
                Reset();
                return(null);
            }

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

                lock (_managersByPf.SyncRoot)
                {
                    var manager = _managersByPf.SafeAdd(regMsg.PortfolioName, pf => new PortfolioPnLManager(pf));
                    _managersByTransId.Add(regMsg.TransactionId, manager);
                }

                return(null);
            }

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

                switch (execMsg.ExecutionType)
                {
                case ExecutionTypes.Transaction:
                {
                    var transId = execMsg.TransactionId == 0
                                                                ? execMsg.OriginalTransactionId
                                                                : execMsg.TransactionId;

                    PortfolioPnLManager manager = null;

                    if (execMsg.HasOrderInfo())
                    {
                        lock (_managersByPf.SyncRoot)
                        {
                            if (!_managersByTransId.TryGetValue(transId, out manager))
                            {
                                if (!execMsg.PortfolioName.IsEmpty())
                                {
                                    manager = _managersByPf.SafeAdd(execMsg.PortfolioName, key => new PortfolioPnLManager(key));
                                }
                                else if (execMsg.OrderId != null)
                                {
                                    manager = _managersByOrderId.TryGetValue(execMsg.OrderId.Value);
                                }
                                else if (!execMsg.OrderStringId.IsEmpty())
                                {
                                    manager = _managersByOrderStringId.TryGetValue(execMsg.OrderStringId);
                                }
                            }

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

                            if (execMsg.OrderId != null)
                            {
                                _managersByOrderId.TryAdd(execMsg.OrderId.Value, manager);
                            }
                            else if (!execMsg.OrderStringId.IsEmpty())
                            {
                                _managersByOrderStringId.TryAdd(execMsg.OrderStringId, manager);
                            }
                        }
                    }

                    if (execMsg.HasTradeInfo())
                    {
                        lock (_managersByPf.SyncRoot)
                        {
                            if (manager == null && !_managersByTransId.TryGetValue(transId, out manager))
                            {
                                return(null);
                            }

                            if (!manager.ProcessMyTrade(execMsg, out var info))
                            {
                                return(null);
                            }

                            _realizedPnL += info.PnL;
                            changedPortfolios?.Add(manager);
                            return(info);
                        }
                    }

                    break;
                }

                case ExecutionTypes.Tick:
                {
                    if (!UseTick)
                    {
                        return(null);
                    }

                    break;
                }

                case ExecutionTypes.OrderLog:
                {
                    if (!UseOrderLog)
                    {
                        return(null);
                    }

                    break;
                }

                default:
                    return(null);
                }

                break;
            }

            case MessageTypes.Level1Change:
            {
                if (!UseLevel1)
                {
                    return(null);
                }

                break;
            }

            case MessageTypes.QuoteChange:
            {
                if (!UseOrderBook)
                {
                    return(null);
                }

                break;
            }

            //case MessageTypes.PortfolioChange:
            case MessageTypes.PositionChange:
            {
                break;
            }

            default:
                return(null);
            }

            foreach (var manager in _managersByPf.CachedValues)
            {
                if (manager.ProcessMessage(message))
                {
                    changedPortfolios?.Add(manager);
                }
            }

            return(null);
        }
Exemple #30
0
 /// <summary>
 /// To get the file data.
 /// </summary>
 /// <param name="id">File ID.</param>
 /// <returns>The file data.</returns>
 public FileData GetFile(long id)
 {
     return(_cache.SafeAdd(id, key => Invoke(f => f.GetFile(AuthenticationClient.Instance.TryGetSession ?? Guid.Empty, id))));
 }