Ejemplo n.º 1
0
        /// <summary>
        /// To shift the expiration of internal instruments <see cref="ContinuousSecurity.ExpirationJumps"/> to a size equas to <paramref name="offset" />.
        /// </summary>
        /// <param name="offset">The size of the expiration shift.</param>
        public void Offset(TimeSpan offset)
        {
            lock (_expirationJumps.SyncRoot)
            {
                var dict = new PairSet <Security, DateTimeOffset>();

                foreach (var security in InnerSecurities)
                {
                    if (security.ExpiryDate == null)
                    {
                        throw new InvalidOperationException(LocalizedStrings.Str698Params.Put(security.Id));
                    }

                    var expiryDate = (DateTimeOffset)security.ExpiryDate + offset;

                    if (expiryDate > security.ExpiryDate)
                    {
                        throw new ArgumentOutOfRangeException(nameof(offset), offset, LocalizedStrings.Str699Params.Put(security.Id, expiryDate, security.ExpiryDate));
                    }

                    dict.Add(security, expiryDate);
                }

                _expirationJumps.Clear();
                _expirationJumps.AddRange(dict);
            }
        }
Ejemplo n.º 2
0
        public MarketDataConfirmWindow()
        {
            InitializeComponent();

            foreach (var type in Enumerator.GetValues <SecurityTypes>())
            {
                var checkBox = new CheckBox {
                    Content = type.GetDisplayName()
                };
                checkBox.Checked   += CheckBoxOnChecked;
                checkBox.Unchecked += CheckBoxOnChecked;

                SecTypes.Children.Add(checkBox);
                _checkBoxes.Add(checkBox, type);
            }
        }
Ejemplo n.º 3
0
        void IPersistable.Save(SettingsStorage settings)
        {
            var ps = new PairSet <Tuple <string, Type>, IContentWindow>();

            foreach (var control in _controls)
            {
                ps.Add(Tuple.Create(control.Id, control.Control.GetType()), control);
            }

            settings.SaveUISettings(DockSite, ps);

            if (EmulationService != null)
            {
                settings.SetValue("EmulationService", EmulationService.Save());
            }
        }
        /// <summary>
        /// Создать <see cref="AlertSettingsWindow"/>.
        /// </summary>
        public AlertSettingsWindow()
        {
            InitializeComponent();

            _buttons.Add(AlertTypes.Sound, IsSound);
            _buttons.Add(AlertTypes.Speech, IsSpeech);
            _buttons.Add(AlertTypes.Popup, IsPopup);
            _buttons.Add(AlertTypes.Sms, IsSms);
            _buttons.Add(AlertTypes.Email, IsEmail);
            _buttons.Add(AlertTypes.Log, IsLog);

            RulesCtrl.ItemsSource = _rules;

            var client = new NotificationClient();

            if (AuthenticationClient.Instance.IsLoggedIn)
            {
                try
                {
                    TestSms.Content   = ((string)TestSms.Content).Put(client.SmsCount);
                    TestEmail.Content = ((string)TestEmail.Content).Put(client.EmailCount);
                    return;
                }
                catch (Exception ex)
                {
                    ex.LogError();
                }

                TestSms.Content = TestEmail.Content = LocalizedStrings.Str152;
            }
            else
            {
                TestSms.Content = TestEmail.Content = LocalizedStrings.NotAuthorized;
            }

            TestSms.Foreground = TestEmail.Foreground = Brushes.Red;
            TestSms.FontWeight = TestEmail.FontWeight = FontWeights.Bold;
            IsSms.IsEnabled    = IsEmail.IsEnabled = TestSms.IsEnabled = TestEmail.IsEnabled = false;
        }
        private void CollectConflictsBetweenFragments(
            ValidationContext context,
            List <Conflict> conflicts,
            Dictionary <SelectionSet, CachedField> cachedFieldsAndFragmentNames,
            PairSet comparedFragmentPairs,
            bool areMutuallyExclusive,
            string fragmentName1,
            string fragmentName2)
        {
            // No need to compare a fragment to itself.
            if (fragmentName1 == fragmentName2)
            {
                return;
            }

            // Memoize so two fragments are not compared for conflicts more than once.
            if (comparedFragmentPairs.Has(fragmentName1, fragmentName2, areMutuallyExclusive))
            {
                return;
            }

            comparedFragmentPairs.Add(fragmentName1, fragmentName2, areMutuallyExclusive);

            var fragment1 = context.GetFragment(fragmentName1);
            var fragment2 = context.GetFragment(fragmentName2);

            if (fragment1 == null || fragment2 == null)
            {
                return;
            }

            var cachedField1 =
                GetReferencedFieldsAndFragmentNames(
                    context,
                    cachedFieldsAndFragmentNames,
                    fragment1);

            var fieldMap1      = cachedField1.NodeAndDef;
            var fragmentNames1 = cachedField1.Names;

            var cachedField2 =
                GetReferencedFieldsAndFragmentNames(
                    context,
                    cachedFieldsAndFragmentNames,
                    fragment2);

            var fieldMap2      = cachedField2.NodeAndDef;
            var fragmentNames2 = cachedField2.Names;

            // (F) First, collect all conflicts between these two collections of fields
            // (not including any nested fragments).
            CollectConflictsBetween(
                context,
                conflicts,
                cachedFieldsAndFragmentNames,
                comparedFragmentPairs,
                areMutuallyExclusive,
                fieldMap1,
                fieldMap2);

            // (G) Then collect conflicts between the first fragment and any nested
            // fragments spread in the second fragment.
            for (var j = 0; j < fragmentNames2.Count; j++)
            {
                CollectConflictsBetweenFragments(
                    context,
                    conflicts,
                    cachedFieldsAndFragmentNames,
                    comparedFragmentPairs,
                    areMutuallyExclusive,
                    fragmentName1,
                    fragmentNames2[j]);
            }

            // (G) Then collect conflicts between the second fragment and any nested
            // fragments spread in the first fragment.
            for (var i = 0; i < fragmentNames1.Count; i++)
            {
                CollectConflictsBetweenFragments(
                    context,
                    conflicts,
                    cachedFieldsAndFragmentNames,
                    comparedFragmentPairs,
                    areMutuallyExclusive,
                    fragmentNames1[i],
                    fragmentName2);
            }
        }
Ejemplo n.º 6
0
        private void ProcessOrderRegister(OrderRegisterMessage message)
        {
            var draft = _client.CreateDraft();

            draft.Comments = message.Comment;
            draft.Account  = _client.Accounts[message.PortfolioName];
            draft.Contract = _client.Contracts[message.SecurityId.SecurityCode];
            draft.Route    = _client.Routes[message.SecurityId.BoardCode];
            draft.Side     = message.Side.ToOec();
            draft.Quantity = (int)message.Volume;

            draft.ClearExtData();
            draft.Price  = (double)message.Price;
            draft.Price2 = 0;

            if (message.OrderType == OrderTypes.Conditional)
            {
                var cond      = (OpenECryOrderCondition)message.Condition;
                var stopPrice = (double)(cond.StopPrice ?? 0);

                switch (cond.AssetType)
                {
                case OpenECryOrderCondition.AssetTypeEnum.All:
                    switch (cond.StopType)
                    {
                    case OpenECryStopType.StopLimit:
                        draft.Type   = OrderType.StopLimit;
                        draft.Price2 = draft.Price;
                        draft.Price  = stopPrice;
                        break;

                    case OpenECryStopType.StopMarket:
                        draft.Type   = OrderType.Stop;
                        draft.Price  = stopPrice;
                        draft.Price2 = 0;
                        break;

                    default:
                        throw new ArgumentException(LocalizedStrings.Str2553Params.Put(cond.StopType));
                    }
                    break;

                case OpenECryOrderCondition.AssetTypeEnum.Equity:
                case OpenECryOrderCondition.AssetTypeEnum.Future:

                    //if (!draft.Contract.IsEquityAsset && !draft.Contract.IsFuture)
                    //	throw new NotSupportedException(LocalizedStrings.Str2554);

                    switch (cond.StopType)
                    {
                    case OpenECryStopType.TrailingStopLimit:
                        draft.Type   = OrderType.TrailingStopLimit;
                        draft.Price2 = draft.Price;
                        draft.Price  = stopPrice;
                        break;

                    case OpenECryStopType.TrailingStopMarket:
                        draft.Type   = OrderType.TrailingStopLoss;
                        draft.Price  = stopPrice;
                        draft.Price2 = 0;
                        break;

                    default:
                        throw new ArgumentException(LocalizedStrings.Str2553Params.Put(cond.StopType));
                    }

                    if (cond.AssetType == OpenECryOrderCondition.AssetTypeEnum.Equity)
                    {
                        draft.SetEquityTSData((double)(cond.Delta ?? 0), cond.IsPercentDelta ?? false, cond.TriggerType.ToOec());
                    }
                    else
                    {
                        draft.SetTSData((double)(cond.ReferencePrice ?? 0), (double)(cond.Delta ?? 0));
                    }

                    break;

                default:
                    throw new ArgumentException(LocalizedStrings.Str2555Params.Put(cond.AssetType));
                }
            }
            else
            {
                draft.Type = message.OrderType.ToOec();
            }

            draft.Flags = OrderFlags.None;
            draft.Start = OEC.API.Version.MinimumStart;
            draft.End   = OEC.API.Version.MaximumEnd;

            switch (message.TimeInForce)
            {
            case null:
            case TimeInForce.PutInQueue:
            {
                draft.Flags = OrderFlags.GTC;

                if (message.ExpiryDate != null && message.ExpiryDate.Value.DateTime != DateTime.Today)
                {
                    draft.End = message.ExpiryDate.Value.UtcDateTime;
                }

                break;
            }

            case TimeInForce.MatchOrCancel:
                draft.Flags = OrderFlags.FOK;
                break;

            case TimeInForce.CancelBalance:
                draft.Flags = OrderFlags.IOC;
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }

            if (message.VisibleVolume != null && message.VisibleVolume < message.Volume)
            {
                draft.SetIcebergData((int)message.VisibleVolume.Value);
            }

            var invalid = draft.GetInvalidParts();

            if (invalid != OrderParts.None)
            {
                throw new OpenECryException(LocalizedStrings.Str2556Params.Put(invalid));
            }

            var newOrder = _client.SendOrder(draft);

            _orderTransactions.Add(newOrder, message.TransactionId);
            ProcessOrder(newOrder, message.TransactionId);
        }
Ejemplo n.º 7
0
        /// <inheritdoc />
        protected override void OnInnerAdapterNewOutMessage(Message message)
        {
            if (message.IsBack)
            {
                base.OnInnerAdapterNewOutMessage(message);
                return;
            }

            switch (message.Type)
            {
            case MessageTypes.Connect:
            {
                var mappings = Storage.Get(StorageName);

                lock (_syncRoot)
                {
                    foreach (var mapping in mappings)
                    {
                        _securityIds.Add(mapping.StockSharpId, mapping.AdapterId);
                    }
                }

                base.OnInnerAdapterNewOutMessage(message);
                break;
            }

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

                base.OnInnerAdapterNewOutMessage(message);
                break;
            }

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

                var adapterId = secMsg.SecurityId.SetNativeId(null);

                if (adapterId.IsDefault())
                {
                    throw new InvalidOperationException(secMsg.ToString());
                }

                lock (_syncRoot)
                {
                    if (_securityIds.TryGetValue(adapterId, out var stockSharpId))
                    {
                        secMsg.SecurityId = stockSharpId;
                    }
                }

                base.OnInnerAdapterNewOutMessage(message);
                break;
            }

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

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

                break;
            }

            default:
            {
                if (message is ISecurityIdMessage secIdMsg)
                {
                    ProcessMessage(secIdMsg.SecurityId, message);
                }
                else
                {
                    base.OnInnerAdapterNewOutMessage(message);
                }

                break;
            }
            }
        }
        /// <inheritdoc />
        protected override void OnInnerAdapterNewOutMessage(Message message)
        {
            long TryReplaceOriginId(long id)
            {
                if (id == 0)
                {
                    return(0);
                }

                lock (_sync)
                    return(_replaceId.TryGetValue(id, out var prevId) ? prevId : id);
            }

            var prevOriginId = 0L;
            var newOriginId  = 0L;

            if (message is IOriginalTransactionIdMessage originIdMsg1)
            {
                newOriginId  = originIdMsg1.OriginalTransactionId;
                prevOriginId = originIdMsg1.OriginalTransactionId = TryReplaceOriginId(newOriginId);
            }

            switch (message.Type)
            {
            case MessageTypes.SubscriptionResponse:
            {
                lock (_sync)
                {
                    if (((SubscriptionResponseMessage)message).IsOk())
                    {
                        if (_subscriptionsById.TryGetValue(prevOriginId, out var info))
                        {
                            // no need send response after re-subscribe cause response was handled prev time
                            if (_replaceId.ContainsKey(newOriginId))
                            {
                                if (info.State != SubscriptionStates.Stopped)
                                {
                                    return;
                                }
                            }
                            else
                            {
                                ChangeState(info, SubscriptionStates.Active);
                            }
                        }
                    }
                    else
                    {
                        if (!_historicalRequests.Remove(prevOriginId))
                        {
                            if (_subscriptionsById.TryGetAndRemove(prevOriginId, out var info))
                            {
                                ChangeState(info, SubscriptionStates.Error);

                                _replaceId.Remove(newOriginId);
                            }
                        }
                    }
                }

                break;
            }

            case MessageTypes.SubscriptionOnline:
            {
                lock (_sync)
                {
                    if (!_subscriptionsById.TryGetValue(prevOriginId, out var info))
                    {
                        break;
                    }

                    if (_replaceId.ContainsKey(newOriginId))
                    {
                        // no need send response after re-subscribe cause response was handled prev time

                        if (info.State == SubscriptionStates.Online)
                        {
                            return;
                        }
                    }
                    else
                    {
                        ChangeState(info, SubscriptionStates.Online);
                    }
                }

                break;
            }

            case MessageTypes.SubscriptionFinished:
            {
                lock (_sync)
                {
                    if (_replaceId.ContainsKey(newOriginId))
                    {
                        return;
                    }

                    _historicalRequests.Remove(prevOriginId);

                    if (_subscriptionsById.TryGetValue(newOriginId, out var info))
                    {
                        ChangeState(info, SubscriptionStates.Finished);
                    }
                }

                break;
            }

            default:
            {
                if (message is ISubscriptionIdMessage subscrMsg)
                {
                    lock (_sync)
                    {
                        var ids = subscrMsg.GetSubscriptionIds();

                        if (ids.Length == 0)
                        {
                            if (subscrMsg.OriginalTransactionId != 0 && _historicalRequests.ContainsKey(subscrMsg.OriginalTransactionId))
                            {
                                subscrMsg.SetSubscriptionIds(subscriptionId: subscrMsg.OriginalTransactionId);
                            }
                        }
                        else
                        {
                            lock (_sync)
                            {
                                if (_replaceId.Count > 0)
                                {
                                    subscrMsg.SetSubscriptionIds(ids.Select(id => _replaceId.TryGetValue2(id) ?? id).ToArray());
                                }
                            }
                        }
                    }
                }

                break;
            }
            }

            base.OnInnerAdapterNewOutMessage(message);

            switch (message.Type)
            {
            case ExtendedMessageTypes.ReconnectingFinished:
            {
                ProcessSuspendedMessage supended = null;

                lock (_sync)
                {
                    _replaceId.Clear();
                    _reMapSubscriptions.Clear();

                    _reMapSubscriptions.AddRange(_subscriptionsById.Values.Distinct().Where(i => i.State.IsActive()).Select(i =>
                        {
                            var subscription           = i.Subscription.TypedClone();
                            subscription.TransactionId = TransactionIdGenerator.GetNextId();

                            _replaceId.Add(subscription.TransactionId, i.Subscription.TransactionId);

                            this.AddInfoLog("Re-map subscription: {0}->{1} for '{2}'.", i.Subscription.TransactionId, subscription.TransactionId, i.Subscription);

                            return((Message)subscription);
                        }));

                    if (_reMapSubscriptions.Count > 0)
                    {
                        supended = new ProcessSuspendedMessage(this);
                    }
                }

                if (supended != null)
                {
                    base.OnInnerAdapterNewOutMessage(supended);
                }

                break;
            }
            }
        }
Ejemplo n.º 9
0
        /// <summary>
        /// To record messages.
        /// </summary>
        /// <param name="messages">Debug messages.</param>
        protected override void OnWriteMessages(IEnumerable <LogMessage> messages)
        {
            // pyh: эмуляция года данных происходит за 5 секунд. На выходе 365 файлов лога? Бред.
            //var date = SeparateByDates != SeparateByDateModes.None ? message.Time.Date : default(DateTime);
            var date = SeparateByDates != SeparateByDateModes.None ? DateTime.Today : default(DateTime);

            string       prevFileName = null;
            StreamWriter prevWriter   = null;

            var isDisposing = false;

            foreach (var group in messages.GroupBy(m =>
            {
                if (isDisposing || m.IsDispose)
                {
                    isDisposing = true;
                    return(null);
                }

                var fileName = FileName ?? GetSourceName(m.Source);

                if (prevFileName == fileName)
                {
                    return(prevWriter);
                }

                var key = Tuple.Create(fileName, date);

                var writer = _writers.TryGetValue(key);

                if (writer == null)
                {
                    if (isDisposing)
                    {
                        return(null);
                    }

                    writer = OnCreateWriter(GetFileName(fileName, date));
                    _writers.Add(key, writer);
                }

                prevFileName = fileName;
                prevWriter = writer;
                return(writer);
            }).AsParallel())
            {
                if (isDisposing)
                {
                    Dispose();
                    return;
                }

                var writer = group.Key;

                try
                {
                    foreach (var message in group)
                    {
                        WriteMessage(writer, message);

                        if (MaxLength <= 0 || writer.BaseStream.Position < MaxLength)
                        {
                            continue;
                        }

                        var fileName = _fileNames[writer];
                        _fileNames.Remove(writer);

                        var key = _writers[writer];
                        writer.Dispose();

                        var maxIndex = 0;

                        while (File.Exists(GetRollingFileName(fileName, maxIndex + 1)))
                        {
                            maxIndex++;
                        }

                        for (var i = maxIndex; i > 0; i--)
                        {
                            File.Move(GetRollingFileName(fileName, i), GetRollingFileName(fileName, i + 1));
                        }

                        File.Move(fileName, GetRollingFileName(fileName, 1));

                        if (MaxCount > 0)
                        {
                            maxIndex++;

                            for (var i = MaxCount; i <= maxIndex; i++)
                            {
                                File.Delete(GetRollingFileName(fileName, i));
                            }
                        }

                        writer        = OnCreateWriter(fileName);
                        _writers[key] = writer;
                    }
                }
                finally
                {
                    writer.Flush();
                }
            }
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Создать <see cref="MarketDepthControl"/>.
        /// </summary>
        public MarketDepthControl()
        {
            InitializeComponent();

            _columnIndecies.Add(MarketDepthColumns.OwnBuy, Columns[0]);
            _columnIndecies.Add(MarketDepthColumns.Buy, Columns[1]);
            _columnIndecies.Add(MarketDepthColumns.Price, Columns[2]);
            _columnIndecies.Add(MarketDepthColumns.Sell, Columns[3]);
            _columnIndecies.Add(MarketDepthColumns.OwnSell, Columns[4]);

            var rules = FormatRules;

            rules.Add(_columnIndecies[MarketDepthColumns.OwnBuy], new FormatRule
            {
                //Type = FormatRuleTypes.CellValue,
                Value     = string.Empty,
                Condition = ComparisonOperator.NotEqual,
                Font      = { Weight = FontWeights.Bold }
            });

            rules.Add(_columnIndecies[MarketDepthColumns.OwnSell], new FormatRule
            {
                //Type = FormatRuleTypes.CellValue,
                Value     = string.Empty,
                Condition = ComparisonOperator.NotEqual,
                Font      = { Weight = FontWeights.Bold }
            });

            rules.Add(_columnIndecies[MarketDepthColumns.Buy], new FormatRule
            {
                //Type = FormatRuleTypes.CellValue,
                Condition  = ComparisonOperator.Any,
                Font       = { Weight = FontWeights.Bold },
                Background = Brushes.LightBlue,
                Foreground = Brushes.DarkBlue,
            });

            rules.Add(_columnIndecies[MarketDepthColumns.Sell], new FormatRule
            {
                //Type = FormatRuleTypes.CellValue,
                Condition  = ComparisonOperator.Any,
                Font       = { Weight = FontWeights.Bold },
                Background = Brushes.LightPink,
                Foreground = Brushes.DarkRed,
            });

            rules.Add(_columnIndecies[MarketDepthColumns.Price], new FormatRule
            {
                //Type = FormatRuleTypes.CellValue,
                Condition  = ComparisonOperator.Any,
                Background = Brushes.Beige,
                Foreground = Brushes.Black,
            });

            //rules.Add(_columnIndecies[MarketDepthColumns.Price], new FormatRule
            //{
            //    Type = FormatRuleTypes.PropertyValue,
            //    PropertyName = "IsBest",
            //    Value = true,
            //    Condition = ComparisonOperator.Equal,
            //    Font = new FontInfo { Weight = FontWeights.Bold },
            //});

            MaxDepth = DefaultDepth;

            ItemsSource = _quotes;

            GuiDispatcher.GlobalDispatcher.AddPeriodicalAction(UpdateIfDepthDirty);
        }
        private void ProcessInSubscriptionMessage <TMessage>(TMessage message,
                                                             DataType dataType, SecurityId securityId = default)
            where TMessage : Message, ISubscriptionMessage
        {
            if (message == null)
            {
                throw new ArgumentNullException(nameof(message));
            }

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

            var transId = message.TransactionId;

            Message CreateSendOut()
            => message.Type.IsLookup()
                                        ? message.CreateResult()
                                        : transId.CreateSubscriptionResponse();

            var isSubscribe = message.IsSubscribe;

            Message sendInMsg  = null;
            Message sendOutMsg = null;
            Message onlineMsg  = null;

            lock (_sync)
            {
                if (isSubscribe)
                {
                    if (_replaceId.ContainsKey(transId))
                    {
                        sendInMsg = message;
                    }
                    else if (message.To != null)
                    {
                        _historicalRequests.Add(transId, (ISubscriptionMessage)message.Clone());
                        sendInMsg = message;
                    }
                    else
                    {
                        var key = Tuple.Create(dataType, securityId);

                        if (!_subscriptionsByKey.TryGetValue(key, out var info))
                        {
                            sendInMsg = message;

                            info = new SubscriptionInfo((ISubscriptionMessage)message.Clone());

                            _subscriptionsByKey.Add(key, info);
                        }
                        else
                        {
                            sendOutMsg = CreateSendOut();
                            onlineMsg  = new SubscriptionOnlineMessage {
                                OriginalTransactionId = transId
                            };
                        }

                        _subscriptionsById.Add(transId, info);
                        info.Subscribers.Add(transId);
                    }
                }
                else
                {
                    var originId = message.OriginalTransactionId;

                    TMessage MakeUnsubscribe(TMessage m)
                    {
                        m.IsSubscribe           = false;
                        m.TransactionId         = transId;
                        m.OriginalTransactionId = originId;

                        return(m);
                    }

                    if (_historicalRequests.TryGetValue(originId, out var subscription))
                    {
                        _historicalRequests.Remove(originId);

                        sendInMsg = MakeUnsubscribe((TMessage)subscription);
                    }
                    else if (_subscriptionsById.TryGetValue(originId, out var info))
                    {
                        if (!info.Subscribers.Remove(originId))
                        {
                            sendOutMsg = originId.CreateSubscriptionResponse(new InvalidOperationException(LocalizedStrings.SubscriptionNonExist.Put(originId)));
                        }
                        else
                        {
                            if (info.Subscribers.Count == 0)
                            {
                                _subscriptionsByKey.RemoveByValue(info);
                                _subscriptionsById.Remove(originId);

                                // copy full subscription's details into unsubscribe request
                                sendInMsg = MakeUnsubscribe((TMessage)info.Subscription.Clone());
                            }
                            else
                            {
                                sendOutMsg = CreateSendOut();
                            }
                        }
                    }
                    else
                    {
                        sendOutMsg = originId.CreateSubscriptionResponse(new InvalidOperationException(LocalizedStrings.SubscriptionNonExist.Put(originId)));
                    }
                }
            }

            if (sendInMsg != null)
            {
                this.AddInfoLog("In: {0}", sendInMsg);
                base.OnSendInMessage(sendInMsg);
            }

            if (sendOutMsg != null)
            {
                this.AddInfoLog("Out: {0}", sendOutMsg);
                RaiseNewOutMessage(sendOutMsg);
            }

            if (onlineMsg != null)
            {
                this.AddInfoLog("Out: {0}", onlineMsg);
                RaiseNewOutMessage(onlineMsg);
            }
        }
Ejemplo n.º 12
0
        public static void LoadUISettings(this SettingsStorage storage, DockSite dockSite, PairSet <Tuple <string, Type>, IContentWindow> contents)
        {
            var controlsSettings = storage.GetValue <SettingsStorage[]>("Content");

            foreach (var ctrlSettings in controlsSettings)
            {
                try
                {
                    var id                = ctrlSettings.GetValue <string>("Id");
                    var ctrlType          = ctrlSettings.GetValue <string>("Type").To <Type>();
                    var isToolWindow      = ctrlSettings.GetValue <bool>("IsToolWindow");
                    var dockingWindowName = ctrlSettings.GetValue <string>("DockingWindowName");
                    var controlSettings   = ctrlSettings.GetValue <SettingsStorage>("Settings");
                    var tagType           = ctrlSettings.GetValue <string>("TagType").To <Type>();

                    var    canClose = true;
                    object tag      = null;

                    if (tagType == typeof(StrategyInfo))
                    {
                        tag = ConfigManager.GetService <IStudioEntityRegistry>().Strategies.ReadById(id.To <long>());

                        if (tag == null)
                        {
                            continue;
                        }
                    }
                    else if (tagType != null && tagType.IsSubclassOf(typeof(Strategy)))
                    {
                        var sessionStrategy = ConfigManager.GetService <IStudioEntityRegistry>().ReadSessionStrategyById(id.To <Guid>());

                        if (sessionStrategy != null)
                        {
                            tag = sessionStrategy.Strategy;
                        }

                        if (tag == null)
                        {
                            continue;
                        }
                    }
                    else if (tagType == typeof(CompositionDiagramElement))
                    {
                        tag = ConfigManager.GetService <CompositionRegistry>().DiagramElements.FirstOrDefault(c => c.TypeId == id.To <Guid>());

                        if (tag == null)
                        {
                            continue;
                        }
                    }
                    else if (tagType == typeof(ExpressionIndexSecurity) || tagType == typeof(ContinuousSecurity))
                    {
                        tag = ConfigManager.GetService <IStudioEntityRegistry>().Securities.ReadById(id);

                        if (tag == null)
                        {
                            continue;
                        }
                    }

                    var control = ctrlType.CreateInstance <IStudioControl>();

                    var info = tag as StrategyInfo;
                    if (info != null)
                    {
                        control.DoIf <IStudioControl, StrategyInfoCodeContent>(c =>
                        {
                            canClose       = false;
                            c.StrategyInfo = info;
                        });
                        control.DoIf <IStudioControl, DiagramPanel>(c =>
                        {
                            canClose       = false;
                            c.StrategyInfo = info;
                        });
                        control.DoIf <IStudioControl, StrategyInfoContent>(c => c.StrategyInfo = info);

                        ConfigManager
                        .GetService <IStudioCommandService>()
                        .Bind(control.GetKey(), (IStudioCommandScope)control);
                    }

                    var strategy = tag as StrategyContainer;
                    if (strategy != null)
                    {
                        control.DoIf <IStudioControl, StrategyContent>(c => c.SetStrategy(strategy));
                        control.DoIf <IStudioControl, DiagramDebuggerPanel>(c => c.Strategy = strategy);
                        control.DoIf <IStudioControl, OptimizatorContent>(c => c.SetStrategy(strategy));
                    }

                    var composition = tag as CompositionDiagramElement;
                    if (composition != null)
                    {
                        ((DiagramPanel)control).Composition = composition;
                    }

                    var security = tag as Security;
                    if (security != null)
                    {
                        ((CompositeSecurityPanel)control).Security = security;
                    }

                    var window = isToolWindow
                                                ? (IContentWindow) new ContentToolWindow {
                        Id = id, Tag = tag, Control = control, Name = dockingWindowName, CanClose = canClose
                    }
                                                : new ContentDocumentWindow {
                        Id = id, Tag = tag, Control = control, Name = dockingWindowName, CanClose = canClose
                    };

                    if (isToolWindow)
                    {
                        dockSite.ToolWindows.Add((ToolWindow)window);
                    }
                    else
                    {
                        dockSite.DocumentWindows.Add((DocumentWindow)window);
                    }

                    ((DockingWindow)window).Activate();

                    if (controlSettings != null)
                    {
                        control.Load(controlSettings);
                    }

                    contents.Add(Tuple.Create(id, ctrlType), window);
                }
                catch (Exception e)
                {
                    e.LogError();
                }
            }

            var layout = storage.GetValue <string>("Layout");

            if (layout != null)
            {
                try
                {
                    dockSite.LoadLayout(layout);
                }
                catch (Exception ex)
                {
                    ex.LogError();
                }
            }

            var activeWindow = storage.GetValue <string>("ActiveWindow");

            if (activeWindow != null)
            {
                var id = activeWindow.To <Guid>();

                var window = dockSite
                             .ToolWindows
                             .OfType <DockingWindow>()
                             .Concat(dockSite.DocumentWindows)
                             .FirstOrDefault(w => w.UniqueId == id);

                if (window != null)
                {
                    window.Activate();
                }
            }
        }
Ejemplo n.º 13
0
        /// <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 mappings = Storage.Get(StorageName);

                lock (_syncRoot)
                {
                    foreach (var mapping in mappings)
                    {
                        _securityIds.Add(mapping.StockSharpId, mapping.AdapterId);
                    }
                }

                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?stockSharpId;

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

                if (stockSharpId != null)
                {
                    secMsg.SecurityId = stockSharpId.Value;
                }

                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;
            }
        }
        private bool ProcessInSubscriptionMessage(ISubscriptionMessage message,
                                                  DataType dataType, SecurityId securityId = default)
        {
            if (message == null)
            {
                throw new ArgumentNullException(nameof(message));
            }

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

            var transId = message.TransactionId;

            var isSubscribe = message.IsSubscribe;

            ISubscriptionMessage sendInMsg = null;

            Message[] sendOutMsgs = null;

            lock (_sync)
            {
                if (isSubscribe)
                {
                    if (message.To == null)
                    {
                        var key = Tuple.Create(dataType, securityId);

                        if (!_subscriptionsByKey.TryGetValue(key, out var info))
                        {
                            sendInMsg = message;

                            info = new SubscriptionInfo((ISubscriptionMessage)message.Clone());

                            _subscriptionsByKey.Add(key, info);
                        }
                        else
                        {
                            var resultMsg = message.CreateResult();

                            if (message.Type == MessageTypes.MarketData)
                            {
                                sendOutMsgs = new[]
                                {
                                    message.CreateResponse(),
                                        resultMsg,
                                };
                            }
                            else
                            {
                                sendOutMsgs = new[] { resultMsg };
                            }
                        }

                        _subscriptionsById.Add(transId, info);
                        info.Subscribers.Add(transId);
                    }
                    else
                    {
                        sendInMsg = message;
                    }
                }
                else
                {
                    ISubscriptionMessage MakeUnsubscribe(ISubscriptionMessage m, long subscriptionId)
                    {
                        m.IsSubscribe           = false;
                        m.TransactionId         = transId;
                        m.OriginalTransactionId = subscriptionId;

                        return(m);
                    }

                    var originId = message.OriginalTransactionId;

                    if (_subscriptionsById.TryGetValue(originId, out var info))
                    {
                        if (!info.Subscribers.Remove(originId))
                        {
                            sendOutMsgs = new[]
                            {
                                (Message)originId.CreateSubscriptionResponse(new InvalidOperationException(LocalizedStrings.SubscriptionNonExist.Put(originId)))
                            };
                        }
                        else
                        {
                            if (info.Subscribers.Count == 0)
                            {
                                _subscriptionsByKey.RemoveByValue(info);
                                _subscriptionsById.Remove(originId);

                                if (info.State.IsActive())
                                {
                                    // copy full subscription's details into unsubscribe request
                                    sendInMsg = MakeUnsubscribe((ISubscriptionMessage)info.Subscription.Clone(), info.Subscription.TransactionId);
                                }
                                else
                                {
                                    this.AddWarningLog(LocalizedStrings.SubscriptionInState, originId, info.State);
                                }
                            }
                            else
                            {
                                sendOutMsgs = new[] { message.CreateResult() };
                            }
                        }
                    }
                    else
                    {
                        sendOutMsgs = new[]
                        {
                            (Message)originId.CreateSubscriptionResponse(new InvalidOperationException(LocalizedStrings.SubscriptionNonExist.Put(originId)))
                        };
                    }
                }
            }

            var retVal = true;

            if (sendInMsg != null)
            {
                this.AddInfoLog("In: {0}", sendInMsg);
                retVal = base.OnSendInMessage((Message)sendInMsg);
            }

            if (sendOutMsgs != null)
            {
                foreach (var sendOutMsg in sendOutMsgs)
                {
                    this.AddInfoLog("Out: {0}", sendOutMsg);
                    RaiseNewOutMessage(sendOutMsg);
                }
            }

            return(retVal);
        }