Exemplo n.º 1
0
        public CsvMarketDataSerializer(SecurityId securityId, ExecutionTypes?executionType, Encoding encoding = null)
        {
            if (securityId.IsDefault() && typeof(TData) != typeof(NewsMessage))
            {
                throw new ArgumentNullException("securityId");
            }

            SecurityId     = securityId;
            _executionType = executionType;
            _encoding      = encoding ?? Encoding.UTF8;

            if (typeof(TData) == typeof(QuoteChangeMessage))
            {
                return;
            }

            _format = GetFormat(executionType).Put(_timeFormat);

            var timeFormat = ":" + _timeFormat;

            if (_isLevel1)
            {
                return;
            }

            _members = _info.SafeAdd(Tuple.Create(typeof(TData), executionType), key =>
                                     _format
                                     .Split(';')
                                     .Select(s =>
                                             MemberProxy.Create(typeof(TData),
                                                                s.Substring(1, s.Length - 2).Replace(timeFormat, string.Empty)))
                                     .ToArray());
        }
Exemplo n.º 2
0
            ISecurityRemoteExtendedStorage IRemoteExtendedStorage.GetSecurityStorage(SecurityId securityId)
            {
                if (securityId.IsDefault())
                {
                    throw new ArgumentNullException(nameof(securityId));
                }

                return(_securityStorages.SafeAdd(securityId, key => new SecurityRemoteExtendedStorage(this, key)));
            }
Exemplo n.º 3
0
        /// <summary>
        /// Create storage for <see cref="IMarketDataStorage"/>.
        /// </summary>
        /// <param name="securityId">Security ID.</param>
        /// <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>
        /// <param name="format">Format type.</param>
        /// <returns>Storage for <see cref="IMarketDataStorage"/>.</returns>
        public override IMarketDataStorageDrive GetStorageDrive(SecurityId securityId, Type dataType, object arg, StorageFormats format)
        {
            if (securityId.IsDefault())
            {
                throw new ArgumentNullException("securityId");
            }

            return(_drives.SafeAdd(Tuple.Create(securityId, dataType, arg, format),
                                   key => new LocalMarketDataStorageDrive(GetFileName(dataType, arg), GetSecurityPath(securityId), format, this)));
        }
Exemplo n.º 4
0
        /// <summary>
        /// Read instrument by identifier.
        /// </summary>
        /// <param name="securities">Instrument storage collection.</param>
        /// <param name="securityId">Identifier.</param>
        /// <returns>Instrument.</returns>
        public static Security ReadBySecurityId(this IStorageEntityList <Security> securities, SecurityId securityId)
        {
            if (securities == null)
            {
                throw new ArgumentNullException(nameof(securities));
            }

            if (securityId.IsDefault())
            {
                throw new ArgumentNullException(nameof(securityId));
            }

            return(securities.ReadById(securityId.ToStringId()));
        }
            public LocalSecurityMarketDataStorage(LocalMarketDataStorage parent, SecurityId securityId)
            {
                if (parent == null)
                {
                    throw new ArgumentNullException("parent");
                }

                if (securityId.IsDefault())
                {
                    throw new ArgumentNullException("securityId");
                }

                _parent     = parent;
                _securityId = securityId;
            }
Exemplo n.º 6
0
        /// <summary>
        /// To get the path to the folder with market data for the instrument.
        /// </summary>
        /// <param name="securityId">Security ID.</param>
        /// <returns>The path to the folder with market data.</returns>
        public string GetSecurityPath(SecurityId securityId)
        {
            if (securityId.IsDefault())
            {
                throw new ArgumentNullException("securityId");
            }

            var id = securityId.ToStringId();

            var folderName = id.SecurityIdToFolderName();

            return(UseAlphabeticPath
                                ? IOPath.Combine(Path, id.Substring(0, 1), folderName)
                                : IOPath.Combine(Path, folderName));
        }
Exemplo n.º 7
0
        private void ProcessMessage(SecurityId adapterId, Message message)
        {
            adapterId.SetNativeId(null);

            if (!adapterId.IsDefault())
            {
                var stockSharpId = Storage.TryGetStockSharpId(StorageName, adapterId);

                if (stockSharpId != null)
                {
                    message.ReplaceSecurityId(stockSharpId.Value);
                }
            }

            base.OnInnerAdapterNewOutMessage(message);
        }
Exemplo n.º 8
0
        /// <summary>
        /// Initializes a new instance of the <see cref="CsvMarketDataSerializer{T}"/>.
        /// </summary>
        /// <param name="securityId">Security ID.</param>
        /// <param name="executionType">The type of execution.</param>
        /// <param name="candleArg">Candle arg.</param>
        /// <param name="encoding">Encoding.</param>
        public CsvMarketDataSerializer(SecurityId securityId, ExecutionTypes?executionType = null, object candleArg = null, Encoding encoding = null)
        {
            if (securityId.IsDefault() && !_isNews)
            {
                throw new ArgumentNullException(nameof(securityId));
            }

            SecurityId     = securityId;
            _executionType = executionType;
            _candleArg     = candleArg;
            _encoding      = encoding ?? _utf;

            if (_isQuotes)
            {
                return;
            }

            _format = GetFormat(executionType).Replace(":{0}", ".UtcDateTime:" + _timeFormat);

            if (_isLevel1)
            {
                return;
            }

            const string timeFormat = ":" + _timeFormat;

            _members = _info.SafeAdd(Tuple.Create(typeof(TData), executionType), key =>
                                     _format
                                     .Split(';')
                                     .Skip(_skipColumns)
                                     .Select(s =>
                                             MemberProxy.Create(typeof(TData),
                                                                s.Substring(1, s.Length - 2).Replace(timeFormat, string.Empty)))
                                     .Concat(_isNews ? new[] { MemberProxy.Create(typeof(TData), "SecurityId") } : Enumerable.Empty <MemberProxy>())
                                     .ToArray());

            if (typeof(TData) == typeof(ExecutionMessage))
            {
                switch (executionType)
                {
                case ExecutionTypes.Tick:
                case ExecutionTypes.OrderLog:
                    _toId = lines => lines[_skipColumns].To <long>();
                    break;
                }
            }
        }
        private void OnStorageMappingChanged(string storageName, SecurityId securityId, SecurityId adapterId)
        {
            if (!InnerAdapter.StorageName.CompareIgnoreCase(storageName))
            {
                return;
            }

            // if adapter code is empty means mapping removed
            // also mapping can be changed (new adapter code for old security code)

            _securityIds.RemoveByValue(securityId);

            if (!adapterId.IsDefault())
            {
                _securityIds.Add(securityId, adapterId);
            }
        }
Exemplo n.º 10
0
        protected MarketDataStorage(SecurityId securityId, object arg, Func <TData, DateTimeOffset> getTime, Func <TData, SecurityId> getSecurityId, Func <TData, TId> getId, IMarketDataSerializer <TData> serializer, IMarketDataStorageDrive drive)
        {
            if (securityId.IsDefault())
            {
                throw new ArgumentException(LocalizedStrings.Str1025, nameof(securityId));
            }

            SecurityId = securityId;

            AppendOnlyNew = true;

            _getTime       = getTime ?? throw new ArgumentNullException(nameof(getTime));
            _getSecurityId = getSecurityId ?? throw new ArgumentNullException(nameof(getSecurityId));
            _getId         = getId ?? throw new ArgumentNullException(nameof(getId));
            Drive          = drive ?? throw new ArgumentNullException(nameof(drive));
            Serializer     = serializer ?? throw new ArgumentNullException(nameof(serializer));
            _arg           = arg;
        }
Exemplo n.º 11
0
        private void ProcessMessage <TMessage>(SecurityId adapterId, TMessage message)
            where TMessage : Message
        {
            if (!adapterId.IsDefault())
            {
                SecurityId?stockSharpId;

                lock (_syncRoot)
                    stockSharpId = _securityIds.TryGetKey2(adapterId);

                if (stockSharpId != null)
                {
                    message.ReplaceSecurityId(stockSharpId.Value);
                }
            }

            base.OnInnerAdapterNewOutMessage(message);
        }
Exemplo n.º 12
0
        protected MarketDataStorage(SecurityId securityId, object arg, Func <TData, DateTimeOffset> getTime, Func <TData, SecurityId> getSecurityId, Func <TData, TId> getId, IMarketDataSerializer <TData> serializer, IMarketDataStorageDrive drive)
        {
            if (securityId.IsDefault())
            {
                throw new ArgumentException(LocalizedStrings.Str1025, "securityId");
            }

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

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

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

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

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

            SecurityId = securityId;

            AppendOnlyNew = true;

            _getTime       = getTime;
            _getSecurityId = getSecurityId;
            _getId         = getId;
            Drive          = drive;
            Serializer     = serializer;
            _arg           = arg;
        }
Exemplo n.º 13
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);
            }
        }
Exemplo n.º 14
0
        protected MarketDataStorage(SecurityId securityId, object arg, Func <TMessage, DateTimeOffset> getTime, Func <TMessage, SecurityId> getSecurityId, Func <TMessage, TId> getId, IMarketDataSerializer <TMessage> serializer, IMarketDataStorageDrive drive, Func <TMessage, bool> isValid)
        {
            if (securityId.IsDefault())
            {
                throw new ArgumentException(LocalizedStrings.Str1025, nameof(securityId));
            }

            SecurityId = securityId;

            AppendOnlyNew = true;

            _dataType = DataType.Create(typeof(TMessage), arg);

            _getTime       = getTime ?? throw new ArgumentNullException(nameof(getTime));
            _getSecurityId = getSecurityId ?? throw new ArgumentNullException(nameof(getSecurityId));
            _getId         = getId ?? throw new ArgumentNullException(nameof(getId));
            Drive          = drive ?? throw new ArgumentNullException(nameof(drive));
            Serializer     = serializer ?? throw new ArgumentNullException(nameof(serializer));
            _isValid       = isValid ?? throw new ArgumentNullException(nameof(isValid));
        }
Exemplo n.º 15
0
            public RemoteStorageDrive(RemoteMarketDataDrive parent, SecurityId securityId, DataType dataType, StorageFormats format)
            {
                if (securityId.IsDefault())
                {
                    throw new ArgumentNullException(nameof(securityId));
                }

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

                // TODO
                //if (drive == null)
                //	throw new ArgumentNullException(nameof(drive));

                _parent     = parent ?? throw new ArgumentNullException(nameof(parent));
                _securityId = securityId;
                _dataType   = dataType ?? throw new ArgumentNullException(nameof(dataType));
                _format     = format;
            }
Exemplo n.º 16
0
//#pragma warning disable 612
		///// <summary>
		///// Load settings.
		///// </summary>
		///// <param name="storage">Settings storage.</param>
		//public override void Load(SettingsStorage storage)
		//{
		//	base.Load(storage);

		//	UseAlphabeticPath = storage.GetValue<bool>(nameof(UseAlphabeticPath));
		//}

		///// <summary>
		///// Save settings.
		///// </summary>
		///// <param name="storage">Settings storage.</param>
		//public override void Save(SettingsStorage storage)
		//{
		//	base.Save(storage);

		//	storage.SetValue(nameof(UseAlphabeticPath), UseAlphabeticPath);
		//}

		/// <summary>
		/// To get the path to the folder with market data for the instrument.
		/// </summary>
		/// <param name="securityId">Security ID.</param>
		/// <returns>The path to the folder with market data.</returns>
		public string GetSecurityPath(SecurityId securityId)
		{
			if (securityId.IsDefault())
				throw new ArgumentNullException(nameof(securityId));

			var id = securityId.ToStringId();

			var folderName = id.SecurityIdToFolderName();

			return //UseAlphabeticPath
				IOPath.Combine(Path, id.Substring(0, 1), folderName);
			//: IOPath.Combine(Path, folderName);
		}
        /// <summary>
        /// Process <see cref="MessageAdapterWrapper.InnerAdapter"/> output message.
        /// </summary>
        /// <param name="message">The message.</param>
        protected override void OnInnerAdapterNewOutMessage(Message message)
        {
            switch (message.Type)
            {
            case MessageTypes.Connect:
            {
                var pairs = Storage.Get(InnerAdapter.StorageName);

                lock (_syncRoot)
                {
                    foreach (var tuple in pairs)
                    {
                        var securityCode = tuple.Item1;
                        var adapterCode  = tuple.Item2;

                        _securityIds.Add(adapterCode, securityCode);
                    }
                }

                base.OnInnerAdapterNewOutMessage(message);
                break;
            }

            case MessageTypes.Reset:
            {
                lock (_syncRoot)
                {
                    _securityIds.Clear();
                }

                base.OnInnerAdapterNewOutMessage(message);
                break;
            }

            case MessageTypes.Security:
            {
                var secMsg = (SecurityMessage)message;

                var securityCode = secMsg.SecurityId.SecurityCode;
                var boardCode    = secMsg.SecurityId.BoardCode;

                if (securityCode.IsEmpty() || boardCode.IsEmpty())
                {
                    throw new InvalidOperationException();
                }

                var adapterId = new SecurityId
                {
                    SecurityCode = securityCode,
                    BoardCode    = boardCode
                };

                SecurityId securityId;

                lock (_syncRoot)
                    securityId = _securityIds.TryGetValue(adapterId);

                if (!adapterId.IsDefault())
                {
                    secMsg.SecurityId = securityId;
                }

                base.OnInnerAdapterNewOutMessage(message);
                break;
            }

            case MessageTypes.PositionChange:
            {
                var positionMsg = (PositionChangeMessage)message;

                ProcessMessage(positionMsg.SecurityId, positionMsg);
                break;
            }

            case MessageTypes.Execution:
            {
                var execMsg = (ExecutionMessage)message;
                ProcessMessage(execMsg.SecurityId, execMsg);
                break;
            }

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

                ProcessMessage(level1Msg.SecurityId, level1Msg);
                break;
            }

            case MessageTypes.QuoteChange:
            {
                var quoteChangeMsg = (QuoteChangeMessage)message;
                ProcessMessage(quoteChangeMsg.SecurityId, quoteChangeMsg);
                break;
            }

            case MessageTypes.CandleTimeFrame:
            case MessageTypes.CandleRange:
            case MessageTypes.CandlePnF:
            case MessageTypes.CandleRenko:
            case MessageTypes.CandleTick:
            case MessageTypes.CandleVolume:
            {
                var candleMsg = (CandleMessage)message;
                ProcessMessage(candleMsg.SecurityId, candleMsg);
                break;
            }

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

                if (newsMsg.SecurityId != null)
                {
                    ProcessMessage(newsMsg.SecurityId.Value, newsMsg);
                }
                else
                {
                    base.OnInnerAdapterNewOutMessage(message);
                }

                break;
            }

            default:
                base.OnInnerAdapterNewOutMessage(message);
                break;
            }
        }
Exemplo n.º 18
0
            public LocalMarketDataStorageDrive(LocalMarketDataDrive parent, SecurityId securityId, string fileName, StorageFormats format, IMarketDataDrive drive)
            {
                if (parent == null)
                {
                    throw new ArgumentNullException("parent");
                }

                if (securityId.IsDefault())
                {
                    throw new ArgumentNullException("securityId");
                }

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

                if (fileName.IsEmpty())
                {
                    throw new ArgumentNullException("fileName");
                }

                _parent                = parent;
                _securityId            = securityId;
                _fileName              = fileName;
                _format                = format;
                _drive                 = drive;
                _fileNameWithExtension = _fileName + GetExtension(_format);

                _datesDict = new Lazy <CachedSynchronizedOrderedDictionary <DateTime, DateTime> >(() =>
                {
                    var retVal = new CachedSynchronizedOrderedDictionary <DateTime, DateTime>();

                    var datesPath = GetDatesCachePath();

                    if (File.Exists(datesPath))
                    {
                        foreach (var date in LoadDates())
                        {
                            retVal.Add(date, date);
                        }
                    }
                    else
                    {
                        var rootDir = Path;

                        var dates = InteropHelper
                                    .GetDirectories(rootDir)
                                    .Where(dir => File.Exists(IOPath.Combine(dir, _fileNameWithExtension)))
                                    .Select(dir => IOPath.GetFileName(dir).ToDateTime(_dateFormat));

                        foreach (var date in dates)
                        {
                            retVal.Add(date, date);
                        }

                        SaveDates(retVal.CachedValues);
                    }

                    return(retVal);
                }).Track();
            }
Exemplo n.º 19
0
		/// <summary>
		/// Получить путь к папке с маркет-данными для инструмента.
		/// </summary>
		/// <param name="securityId">Идентификатор инструмента.</param>
		/// <returns>Путь к папке с маркет-данными.</returns>
		public string GetSecurityPath(SecurityId securityId)
		{
			if (securityId.IsDefault())
				throw new ArgumentNullException("securityId");

			var id = securityId.SecurityCode + "@" + securityId.BoardCode;

			var folderName = id.SecurityIdToFolderName();

			return UseAlphabeticPath
				? IOPath.Combine(Path, id.Substring(0, 1), folderName)
				: IOPath.Combine(Path, folderName);
		}
Exemplo n.º 20
0
		/// <summary>
		/// Создать хранилище для <see cref="IMarketDataStorage"/>.
		/// </summary>
		/// <param name="securityId">Идентификатор инструмента.</param>
		/// <param name="dataType">Тип маркет-данных.</param>
		/// <param name="arg">Параметр, ассоциированный с типом <paramref name="dataType"/>. Например, <see cref="CandleMessage.Arg"/>.</param>
		/// <param name="format">Тип формата.</param>
		/// <returns>Хранилище для <see cref="IMarketDataStorage"/>.</returns>
		public override IMarketDataStorageDrive GetStorageDrive(SecurityId securityId, Type dataType, object arg, StorageFormats format)
		{
			if (securityId.IsDefault())
				throw new ArgumentNullException("securityId");

			return _drives.SafeAdd(Tuple.Create(securityId, dataType, arg, format),
				key => new LocalMarketDataStorageDrive(CreateFileName(dataType, arg), GetSecurityPath(securityId), format, this));
		}
Exemplo n.º 21
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);
		}