public void TestIndex()
 {
     var dictionary = new SynchronizedDictionary<string, string>();
     dictionary["1"] = "1";
     Assert.AreEqual(dictionary["1"],"1");
     Assert.AreEqual(dictionary["2"], null);
     string val1;
     dictionary.TryGetValue("3", out val1);
     Assert.AreEqual(val1,null);
     dictionary.TryGetValue("1", out val1);
     Assert.AreEqual(val1, "1");
 }
Exemple #2
0
        internal void ProcessResponse(BaseResponse response)
        {
            var handler = _handlerBunch.TryGetValue(response.GetType());

            //if (handler.IsNull())
            //	throw new ArgumentException("Ответ '{0}' не содержит обработчика.".Put(t.Name));

            if (handler != null)
            {
                handler(response);
            }
        }
Exemple #3
0
        /// <summary>
        /// Check message on alert conditions.
        /// </summary>
        /// <param name="message">Message.</param>
        public void Process(Message message)
        {
            if (message == null)
            {
                throw new ArgumentNullException(nameof(message));
            }

            var schema = _schemas.TryGetValue(message.GetType());

            var type = schema?.AlertType;

            if (type == null)
            {
                return;
            }

            var canAlert = schema.Rules.All(rule =>
            {
                var value = rule.Property.GetValue(message, null);

                switch (rule.Operator)
                {
                case ComparisonOperator.Equal:
                    return(rule.Value.Equals(value));

                case ComparisonOperator.NotEqual:
                    return(!rule.Value.Equals(value));

                case ComparisonOperator.Greater:
                    return(OperatorRegistry.GetOperator(rule.Property.PropertyType).Compare(rule.Value, value) == 1);

                case ComparisonOperator.GreaterOrEqual:
                    return(OperatorRegistry.GetOperator(rule.Property.PropertyType).Compare(rule.Value, value) >= 0);

                case ComparisonOperator.Less:
                    return(OperatorRegistry.GetOperator(rule.Property.PropertyType).Compare(rule.Value, value) == -1);

                case ComparisonOperator.LessOrEqual:
                    return(OperatorRegistry.GetOperator(rule.Property.PropertyType).Compare(rule.Value, value) <= 0);

                case ComparisonOperator.Any:
                    return(true);

                default:
                    throw new ArgumentOutOfRangeException();
                }
            });

            if (canAlert)
            {
                PushAlert((AlertTypes)type, schema.Caption, schema.Message, message.LocalTime);
            }
        }
            private void OnConnectorMarketDataSubscriptionSucceeded(Security security, MarketDataTypes type)
            {
                var types = _unsubscribeActions.TryGetValue(security);

                if (types == null)
                {
                    return;
                }

                if (!types.Remove(type))
                {
                    return;
                }

                var subscribers = GetSubscribers(type);

                if (TryUnSubscribe(subscribers, security))
                {
                    SendUnSubscribeMessage(security, type);
                }
            }
        private void TraderOnNewTrades(IEnumerable <Trade> trades)
        {
            foreach (var group in trades.GroupBy(t => t.Security))
            {
                var wnd = _tradesWindows.TryGetValue(group.Key);

                if (wnd != null)
                {
                    wnd.TradeGrid.Trades.AddRange(group);
                }
            }
        }
            public void TryInvokeMouse(MarketDepthColumns column, MouseAction action, ModifierKeys modifierKey)
            {
                var value = _mouseActions.TryGetValue(Tuple.Create(action, modifierKey));

                if (value != null)
                {
                    value.Process(column, _parent.SelectedQuote);
                }

                //if (value != null && _parent.SelectedQuote != null && _parent.SelectedQuote.Price != 0)
                //	new MarketDepthMouseActionCommand(action, modifierKey, column, _parent.SelectedQuote).Process(_parent);
            }
        private void TraderOnMarketDepthsChanged(IEnumerable <MarketDepth> depths)
        {
            foreach (var depth in depths)
            {
                var wnd = _quotesWindows.TryGetValue(depth.Security);

                if (wnd != null)
                {
                    wnd.DepthCtrl.UpdatingDepth = depth;
                }
            }
        }
        Task <string> IOneOffKeyPairGrain.Decrypt(string name, string cipherText, bool fOAEP)
        {
            string result = null;

            if (_cache.TryGetValue(name, out CachedObject <KeyPair> cachedObject))
            {
                result = RSACryptoTextProvider.Decrypt(cachedObject.Value.PrivateKey, cipherText, fOAEP);
                _cache.Remove(name);
            }

            return(Task.FromResult(result));
        }
        /// <inheritdoc />
        protected override void OnInnerAdapterNewOutMessage(Message message)
        {
            switch (message.Type)
            {
            case MessageTypes.QuoteChange:
            {
                var quoteMsg = (QuoteChangeMessage)message;

                var info = _filteredMarketDepths.TryGetValue(quoteMsg.SecurityId);

                if (info != null)
                {
                    var filteredQuoteMsg = info.Process(quoteMsg);
                    base.OnInnerAdapterNewOutMessage(filteredQuoteMsg);
                }

                break;
            }

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

                if (execMsg.ExecutionType != ExecutionTypes.Transaction)
                {
                    break;
                }

                if (execMsg.OrderState == OrderStates.Active || execMsg.OrderState == OrderStates.Done)
                {
                    var info = _filteredMarketDepths.TryGetValue(execMsg.SecurityId);
                    info?.Process(execMsg);
                }

                break;
            }
            }

            base.OnInnerAdapterNewOutMessage(message);
        }
        private void TraderOnNewMessage(Message msg, MessageDirections dir)
        {
            if (dir == MessageDirections.Out && msg.Type == MessageTypes.Level1Change)
            {
                var level1Msg = (Level1ChangeMessage)msg;
                var wnd       = _level1Windows.TryGetValue(level1Msg.SecurityId.SecurityCode);

                if (wnd != null)
                {
                    wnd.Level1Grid.Messages.Add(level1Msg);
                }
            }
        }
Exemple #11
0
 public static byte[] file_GetCache(string fileKey, string filePath)
 {
     byte[] v = new byte[] { };
     if (_dbFileCache.TryGetValue(filePath, out v) == false)
     {
         if (File.Exists(filePath))
         {
             v = File.ReadAllBytes(filePath);
             _dbFileCache.Add(fileKey, v);
         }
     }
     return(v);
 }
Exemple #12
0
        private void ProcessBuilders(ExecutionMessage execMsg)
        {
            if (execMsg.IsSystem == false)
            {
                return;
            }

            foreach (var subscriptionId in execMsg.GetSubscriptionIds())
            {
                if (!_subscriptionIds.TryGetValue(subscriptionId, out var tuple))
                {
                    // can be non OL->MB subscription
                    //this.AddDebugLog("OL processing {0}/{1} not found.", execMsg.SecurityId, subscriptionId);
                    continue;
                }

                if (tuple.First)
                {
                    var sync = tuple.Third;

                    IOrderLogMarketDepthBuilder builder = tuple.Second;

                    try
                    {
                        QuoteChangeMessage depth;

                        lock (sync)
                            depth = builder.Update(execMsg)?.TypedClone();

                        this.AddDebugLog("OL->MD processing {0}={1}.", execMsg.SecurityId, depth != null);

                        if (depth != null)
                        {
                            depth.SetSubscriptionIds(subscriptionId: subscriptionId);
                            base.OnInnerAdapterNewOutMessage(depth);
                        }
                    }
                    catch (Exception ex)
                    {
                        // если ОЛ поврежден, то не нарушаем весь цикл обработки сообщения
                        // а только выводим сообщение в лог
                        base.OnInnerAdapterNewOutMessage(ex.ToErrorMessage());
                    }
                }
                else
                {
                    this.AddDebugLog("OL->TICK processing {0}.", execMsg.SecurityId);
                    base.OnInnerAdapterNewOutMessage(execMsg.ToTick());
                }
            }
        }
        public static TValue FindOrCreate <TKey, TValue>(this SynchronizedDictionary <TKey, TValue> items, TKey key, Func <TValue> factory)
        {
            TValue value = default(TValue);

            using (items.Lock.CreateWriterScope())
            {
                if (!items.TryGetValue(key, out value))
                {
                    items.Add(key, value = factory());
                }

                return(value);
            }
        }
Exemple #14
0
        public MainWindow()
        {
            InitializeComponent();

            LayoutManager = new LayoutManager(this, ProgrammaticDockSite)
            {
                LayoutFile = Path.Combine(_settingsFolder, "layout.xml")
            };

            ConnectCommand  = new DelegateCommand(Connect, CanConnect);
            SettingsCommand = new DelegateCommand(Settings, CanSettings);

            Directory.CreateDirectory(_settingsFolder);

            var storageRegistry = new StorageRegistry {
                DefaultDrive = new LocalMarketDataDrive(_settingsFolder)
            };

            Connector = new Connector();
            var storageAdapter = new StorageMessageAdapter(Connector.Adapter, new EntityRegistry(), storageRegistry);

            ConfigManager.RegisterService <ISecurityProvider>(new FilterableSecurityProvider(storageRegistry.GetSecurityStorage()));
            ConfigManager.RegisterService <IConnector>(Connector);
            ConfigManager.RegisterService <IMarketDataProvider>(Connector);

            _connectionFile = Path.Combine(_settingsFolder, "connection.xml");

            if (File.Exists(_connectionFile))
            {
                Connector.Adapter.Load(new XmlSerializer <SettingsStorage>().Deserialize(_connectionFile));
            }

            _secView = new SecuritiesView(this)
            {
                SecurityGrid = { MarketDataProvider = Connector }
            };

            Connector.MarketDepthsChanged += depths =>
            {
                foreach (var depth in depths)
                {
                    var ctrl = Depths.TryGetValue(depth.Security);

                    if (ctrl != null)
                    {
                        ctrl.UpdateDepth(depth);
                    }
                }
            };
        }
Exemple #15
0
            private void UnSubscribeStrategyEvents(Strategy strategy)
            {
                _logManager.Sources.Remove(strategy);

                var strategyEvent = _events.TryGetValue(strategy);

                if (strategyEvent == null)
                {
                    return;
                }

                strategyEvent.Dispose();
                _events.Remove(strategy);
            }
        private void DepthClick(object sender, RoutedEventArgs e)
        {
            foreach (var security in SecurityPicker.SelectedSecurities)
            {
                var wnd = _quotesWindows.TryGetValue(security);

                if (wnd == null)
                {
                    // create order book window
                    wnd = new QuotesWindow
                    {
                        Title = security.Id + " " + LocalizedStrings.MarketDepth
                    };
                    _quotesWindows.Add(security, wnd);

                    // subscribe on order book flow
                    Trader.RegisterMarketDepth(security);

                    wnd.Show();
                    wnd.DepthCtrl.UpdateDepth(Trader.GetMarketDepth(security));
                }
                else
                {
                    Trader.UnRegisterMarketDepth(security);

                    _quotesWindows.Remove(security);

                    wnd.Close();
                }

                if (!_mdInitialized)
                {
                    Trader.MarketDepthChanged += TraderOnMarketDepthChanged;
                    _mdInitialized             = true;
                }
            }
        }
Exemple #17
0
            private void OnConnectorNewMessage(Message message)
            {
                switch (message.Type)
                {
                case MessageTypes.CandleTimeFrame:
                case MessageTypes.CandlePnF:
                case MessageTypes.CandleRange:
                case MessageTypes.CandleRenko:
                case MessageTypes.CandleTick:
                case MessageTypes.CandleVolume:
                {
                    var candleMsg = (CandleMessage)message;
                    var info      = _seriesInfos.TryGetValue(candleMsg.OriginalTransactionId);

                    if (info != null)
                    {
                        ProcessCandle(info, candleMsg);
                    }

                    break;
                }

                case MessageTypes.MarketDataFinished:
                {
                    var msg  = (MarketDataFinishedMessage)message;
                    var info = _seriesInfos.TryGetValue(msg.OriginalTransactionId);

                    if (info == null)
                    {
                        break;
                    }

                    Stopped?.Invoke(info.Series);
                    break;
                }
                }
            }
Exemple #18
0
        public override void Process(CmdTrigger <RealmServerCmdArgs> trigger)
        {
            Dictionary <DynamicObject, GameObject> highlighters;
            var exists = Highlighters.TryGetValue(trigger.Args.Character, out highlighters);
            var create = trigger.Text.NextBool() || (!trigger.Text.HasNext && !exists);

            if (!create)
            {
                if (exists)
                {
                    foreach (var dynObj in highlighters.Keys)
                    {
                        dynObj.Delete();
                    }
                    highlighters.Clear();
                    Highlighters.Remove(trigger.Args.Character);
                }
                trigger.Reply("GO Highlighters OFF");
            }
            else
            {
                if (!exists)
                {
                    Highlighters.Add(trigger.Args.Character, highlighters = new Dictionary <DynamicObject, GameObject>());
                }
                else
                {
                    foreach (var dynObj in highlighters.Keys)
                    {
                        dynObj.Delete();
                    }
                    highlighters.Clear();
                }

                var caster = trigger.Args.Character;

                var gos = caster.GetObjectsInRadius(50f, ObjectTypes.GameObject, false, 0);
                foreach (GameObject go in gos)
                {
                    var map = go.Map;
                    var pos = go.Position;
                    pos.Z += 7 * go.ScaleX;                                                             // make it appear above the object

                    var dO = new DynamicObject(caster, SpellId.ABOUTTOSPAWN, 5, map, pos);
                    highlighters.Add(dO, go);
                }
                trigger.Reply("Highlighting {0} GameObjects", highlighters.Count);
            }
        }
        private void ProcessCandle(CandleMessage message)
        {
            var info = _infos.TryGetValue(message.OriginalTransactionId);

            if (info == null)
            {
                return;
            }

            if (info.SecurityId == default)
            {
                info.SecurityId = message.SecurityId;
            }
            else
            {
                message.SecurityId = info.SecurityId;
            }

            if (info.Arg == null)
            {
                info.Arg = message.Arg;
            }
            else
            {
                message.Arg = info.Arg;
            }

            TryUpdateValue(message, info, c => c.OpenPrice, (c, v) => c.OpenPrice   = v);
            TryUpdateValue(message, info, c => c.HighPrice, (c, v) => c.HighPrice   = v);
            TryUpdateValue(message, info, c => c.LowPrice, (c, v) => c.LowPrice     = v);
            TryUpdateValue(message, info, c => c.ClosePrice, (c, v) => c.ClosePrice = v);
            TryUpdateValue(message, info, c => c.TotalPrice, (c, v) => c.TotalPrice = v);

            TryUpdateValue(message, info, c => c.OpenTime, (c, v) => c.OpenTime   = v);
            TryUpdateValue(message, info, c => c.HighTime, (c, v) => c.HighTime   = v);
            TryUpdateValue(message, info, c => c.LowTime, (c, v) => c.LowTime     = v);
            TryUpdateValue(message, info, c => c.CloseTime, (c, v) => c.CloseTime = v);

            TryUpdateValue(message, info, c => c.OpenVolume, (c, v) => c.OpenVolume         = v);
            TryUpdateValue(message, info, c => c.HighVolume, (c, v) => c.HighVolume         = v);
            TryUpdateValue(message, info, c => c.LowVolume, (c, v) => c.LowVolume           = v);
            TryUpdateValue(message, info, c => c.CloseVolume, (c, v) => c.CloseVolume       = v);
            TryUpdateValue(message, info, c => c.RelativeVolume, (c, v) => c.RelativeVolume = v);
            TryUpdateValue(message, info, c => c.TotalVolume, (c, v) => c.TotalVolume       = v);

            TryUpdateValue(message, info, c => c.UpTicks, (c, v) => c.UpTicks       = v);
            TryUpdateValue(message, info, c => c.DownTicks, (c, v) => c.DownTicks   = v);
            TryUpdateValue(message, info, c => c.TotalTicks, (c, v) => c.TotalTicks = v);
        }
Exemple #20
0
        /// <summary>
        /// 检索从业务对象
        /// </summary>
        public TDetail[] FindDetail <TDetail>()
            where TDetail : BusinessBase <TDetail>
        {
            if (_details.TryGetValue(typeof(TDetail), out List <IBusiness> detail))
            {
                List <TDetail> result = new List <TDetail>(detail.Count);
                foreach (IBusiness item in detail)
                {
                    result.Add((TDetail)item);
                }
                return(result.ToArray());
            }

            return(null);
        }
Exemple #21
0
        IEnumerable <Security> ISecurityProvider.Lookup(Security criteria)
        {
            var finamId = criteria.ExtensionInfo == null
                                ? null
                                : (long?)criteria.ExtensionInfo.TryGetValue(FinamHistorySource.SecurityIdField);

            if (finamId == null)
            {
                return(_entityRegistry.Securities.Lookup(criteria));
            }

            var security = _cacheByFinamId.TryGetValue(finamId.Value);

            return(security == null?Enumerable.Empty <Security>() : new[] { security });
        }
        private void TraderOnNewMessage(Message msg)
        {
            if (msg.Type != MessageTypes.Level1Change)
            {
                return;
            }

            var level1Msg = (Level1ChangeMessage)msg;
            var wnd       = _level1Windows.TryGetValue(level1Msg.SecurityId.SecurityCode);

            if (wnd != null)
            {
                wnd.Level1Grid.Messages.Add(level1Msg);
            }
        }
Exemple #23
0
        public static bool check_SessionID_Login_OK(decimal sessionid)
        {
            long idt = 0;

            if (dicSessionID_Login_OK.TryGetValue(sessionid, out idt))
            {
                var d1 = DateTime.ParseExact(idt.ToString(), "yyMMddHHmm00", CultureInfo.InvariantCulture);
                int mi = (int)(DateTime.Now - d1).TotalMinutes;
                if (mi < 60)
                {
                    return(true);
                }
            }
            return(false);
        }
Exemple #24
0
        IEnumerable <Security> ISecurityProvider.Lookup(Security criteria)
        {
            var nativeId = criteria.ExtensionInfo == null
                                ? default(TNativeId)
                                : CreateNativeId(criteria);

            if (nativeId.IsDefault())
            {
                return(_entityRegistry.Securities.Lookup(criteria));
            }

            var security = _cacheByNativeId.TryGetValue(nativeId);

            return(security == null?Enumerable.Empty <Security>() : new[] { security });
        }
        IEnumerable <Security> ISecurityProvider.Lookup(Security criteria)
        {
            var quandlId = criteria.ExtensionInfo == null
                                ? null
                                : Tuple.Create((string)criteria.ExtensionInfo.TryGetValue(QuandlHistorySource.SourceCodeField), (string)criteria.ExtensionInfo.TryGetValue(QuandlHistorySource.SecurityCodeField));

            if (quandlId == null || quandlId.Item1 == null)
            {
                return(_entityRegistry.Securities.Lookup(criteria));
            }

            var security = _cacheByQuandlId.TryGetValue(quandlId);

            return(security == null?Enumerable.Empty <Security>() : new[] { security });
        }
        IEnumerable <Security> ISecurityProvider.Lookup(Security criteria)
        {
            var mfdId = criteria.ExtensionInfo == null
                                ? null
                                : (string)criteria.ExtensionInfo.TryGetValue(MfdHistorySource.SecurityIdField);

            if (mfdId == null)
            {
                return(_entityRegistry.Securities.Lookup(criteria));
            }

            var security = _cacheByMfdId.TryGetValue(mfdId);

            return(security == null?Enumerable.Empty <Security>() : new[] { security });
        }
Exemple #27
0
        /// <summary>
        /// To stop data receiving starting through <see cref="Start"/>.
        /// </summary>
        /// <param name="series">Candles series.</param>
        public override void Stop(CandleSeries series)
        {
            if (series == null)
            {
                throw new ArgumentNullException("series");
            }

            var registeredSeries = _registeredSeries.TryGetValue(series.Security);

            if (registeredSeries == null)
            {
                return;
            }

            registeredSeries.Remove(series);

            if (registeredSeries.Count == 0)
            {
                UnRegisterSecurity(series.Security);
                _registeredSeries.Remove(series.Security);
            }

            RaiseStopped(series);
        }
        public override void Process(CmdTrigger <RealmServerCmdArgs> trigger)
        {
            Dictionary <DynamicObject, GameObject> dictionary;
            bool flag = Highlighters.TryGetValue(trigger.Args.Character, out dictionary);

            if (!trigger.Text.NextBool() && (trigger.Text.HasNext || flag))
            {
                if (flag)
                {
                    foreach (WorldObject key in dictionary.Keys)
                    {
                        key.Delete();
                    }
                    dictionary.Clear();
                    Highlighters.Remove(trigger.Args.Character);
                }

                trigger.Reply("GO Highlighters OFF");
            }
            else
            {
                if (!flag)
                {
                    Highlighters.Add(trigger.Args.Character,
                                     dictionary = new Dictionary <DynamicObject, GameObject>());
                }
                else
                {
                    foreach (WorldObject key in dictionary.Keys)
                    {
                        key.Delete();
                    }
                    dictionary.Clear();
                }

                Character character = trigger.Args.Character;
                foreach (GameObject objectsInRadiu in character.GetObjectsInRadius(50f, ObjectTypes.GameObject, false, 0))
                {
                    Map     map      = objectsInRadiu.Map;
                    Vector3 position = objectsInRadiu.Position;
                    position.Z += 7f * objectsInRadiu.ScaleX;
                    DynamicObject key = new DynamicObject(character, SpellId.ABOUTTOSPAWN, 5f, map, position);
                    dictionary.Add(key, objectsInRadiu);
                }

                trigger.Reply("Highlighting {0} GameObjects", (object)dictionary.Count);
            }
        }
        void ICandleSource <Candle> .Stop(CandleSeries series)
        {
            lock (_info.SyncRoot)
            {
                var basketInfo = _info.TryGetValue(series);

                if (basketInfo == null)
                {
                    return;
                }

                basketInfo.Dispose();

                _info.Remove(series);
            }
        }
Exemple #30
0
        /// <summary>
        /// To stop data receiving starting through <see cref="Start"/>.
        /// </summary>
        /// <param name="series">Candles series.</param>
        public virtual void Stop(CandleSeries series)
        {
            if (series == null)
            {
                throw new ArgumentNullException(nameof(series));
            }

            var enumerator = _series.TryGetValue(series);

            if (enumerator == null)
            {
                return;
            }

            enumerator.Stop();
        }
Exemple #31
0
        private SeriesInfo GetInfo(CandleSeries series)
        {
            if (series == null)
            {
                throw new ArgumentNullException("series");
            }

            var info = _info.TryGetValue(series);

            if (info == null)
            {
                throw new InvalidOperationException(LocalizedStrings.Str648Params.Put(series));
            }

            return(info);
        }