Ejemplo n.º 1
0
        /// <summary>
        /// Initializes a new instance of the <see cref="StorageExchangeInfoProvider"/>.
        /// </summary>
        /// <param name="entityRegistry">The storage of trade objects.</param>
        public StorageExchangeInfoProvider(IEntityRegistry entityRegistry)
        {
            if (entityRegistry == null)
            {
                throw new ArgumentNullException(nameof(entityRegistry));
            }

            _entityRegistry = entityRegistry;

            var boardCodes = new HashSet <string>();

            var boardList = _entityRegistry.ExchangeBoards as ExchangeBoardList;

            boardCodes.AddRange(boardList != null ? boardList.GetIds() : _entityRegistry.ExchangeBoards.Select(b => b.Code));

            var boards = Boards.Where(b => !boardCodes.Contains(b.Code)).ToArray();

            if (boards.Length > 0)
            {
                boards
                .Select(b => b.Exchange)
                .Distinct()
                .ForEach(Save);

                boards
                .ForEach(Save);
            }

            _entityRegistry.Exchanges.ForEach(e => base.Save(e));
            _entityRegistry.ExchangeBoards.ForEach(b => base.Save(b));
        }
Ejemplo n.º 2
0
		/// <summary>
		/// Initializes a new instance of the <see cref="ExchangeInfoProvider"/>.
		/// </summary>
		/// <param name="entityRegistry">The storage of trade objects.</param>
		public ExchangeInfoProvider(IEntityRegistry entityRegistry)
		{
			if (entityRegistry == null)
				throw new ArgumentNullException(nameof(entityRegistry));

			ExchangeBoard.EnumerateExchanges().ForEach(exchange => _exchanges.Add(exchange.Name, exchange));
			ExchangeBoard.EnumerateExchangeBoards().ForEach(board => _boards.Add(board.Code, board));

			_entityRegistry = entityRegistry;

			var boardCodes = new HashSet<string>();

			var boardList = _entityRegistry.ExchangeBoards as ExchangeBoardList;
			boardCodes.AddRange(boardList != null ? boardList.GetIds() : _entityRegistry.ExchangeBoards.Select(b => b.Code));

			var boards = Boards.Where(b => !boardCodes.Contains(b.Code)).ToArray();

			if (boards.Length > 0)
			{
				boards
					.Select(b => b.Exchange)
					.Distinct()
					.ForEach(Save);

				boards
					.ForEach(Save);
			}

			_entityRegistry.Exchanges.ForEach(e => _exchanges[e.Name] = e);
			_entityRegistry.ExchangeBoards.ForEach(b => _boards[b.Code] = b);
		}
Ejemplo n.º 3
0
		/// <summary>
		/// Initializes a new instance of the <see cref="StorageEntityFactory"/>.
		/// </summary>
		/// <param name="entityRegistry">The storage of trade objects.</param>
		public StorageEntityFactory(IEntityRegistry entityRegistry)
		{
			if (entityRegistry == null)
				throw new ArgumentNullException(nameof(entityRegistry));

			_entityRegistry = entityRegistry;
		}
Ejemplo n.º 4
0
        public void ApplyMod <E, M>(int uid, IEntityRegistry <E> r, M m) where M : IEntityModifier where E : IEntity, IModifiable <M>
        {
            E e = r.GetEntityByUID(uid);

            m.e = e;
            ApplyMod <M>(m);
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ExchangeInfoProvider"/>.
        /// </summary>
        /// <param name="entityRegistry">The storage of trade objects.</param>
        public ExchangeInfoProvider(IEntityRegistry entityRegistry)
        {
            if (entityRegistry == null)
            {
                throw new ArgumentNullException(nameof(entityRegistry));
            }

            ExchangeBoard.EnumerateExchanges().ForEach(exchange => _exchanges.Add(exchange.Name, exchange));
            ExchangeBoard.EnumerateExchangeBoards().ForEach(board => _boards.Add(board.Code, board));

            _entityRegistry = entityRegistry;

            var boardCodes = new HashSet <string>();

            var boardList = _entityRegistry.ExchangeBoards as ExchangeBoardList;

            boardCodes.AddRange(boardList != null ? boardList.GetIds() : _entityRegistry.ExchangeBoards.Select(b => b.Code));

            var boards = Boards.Where(b => !boardCodes.Contains(b.Code)).ToArray();

            if (boards.Length > 0)
            {
                boards
                .Select(b => b.Exchange)
                .Distinct()
                .ForEach(Save);

                boards
                .ForEach(Save);
            }

            _entityRegistry.Exchanges.ForEach(e => _exchanges[e.Name]   = e);
            _entityRegistry.ExchangeBoards.ForEach(b => _boards[b.Code] = b);
        }
Ejemplo n.º 6
0
 /// <summary>
 ///     Extension of Sitecore.Commerce.Plugin.Rules.ModelExtensions.ConvertToAction to allow boolean values
 /// </summary>
 internal static IAction ConvertToActionExtended(
     this ActionModel model,
     IEntityMetadata metaData,
     IEntityRegistry registry,
     IServiceProvider services)
 {
     return(model.Properties.Convert <IAction>(metaData, registry, services));
 }
Ejemplo n.º 7
0
        public PathFindingSystem(IMatcherProvider matcherProvider, IEntityRegistry entityRegistry)
        {
            _subsystemMatcherGroup  = matcherProvider.CreateMatcherGroup <GraphNode, Subsystem, ExitRoutes>();
            _connectionMatcherGroup = matcherProvider.CreateMatcherGroup <GraphNode, Connection, MovementCost>();

            // TODO: handle new match route recalculation
            // TODO: handle graph node events that might affect routing
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Connector"/>.
        /// </summary>
        /// <param name="entityRegistry">The storage of trade objects.</param>
        /// <param name="storageRegistry">The storage of market data.</param>
        /// <param name="snapshotRegistry">Snapshot storage registry.</param>
        /// <param name="initManagers">Initialize managers.</param>
        public Connector(IEntityRegistry entityRegistry, IStorageRegistry storageRegistry, SnapshotRegistry snapshotRegistry,
                         bool initManagers = true)
            : this(entityRegistry.Securities, entityRegistry.PositionStorage, storageRegistry, snapshotRegistry, initManagers)
        {
#pragma warning disable 612
            EntityRegistry = entityRegistry;
#pragma warning restore 612
        }
Ejemplo n.º 9
0
        public void ApplyMod <E, M>(int uid, M m) where M : IEntityModifier where E : IEntity, IModifiable <M>
        {
            IEntityRegistry <E> r = (IEntityRegistry <E>)Registries[typeof(E)];
            E e = r.GetEntityByUID(uid);

            m.e = e;
            ApplyMod <M>(m);
        }
Ejemplo n.º 10
0
 /// <summary>
 /// Initializes a new instance of the <see cref="CsvImporter"/>.
 /// </summary>
 /// <param name="dataType">Data type info.</param>
 /// <param name="fields">Importing fields.</param>
 /// <param name="entityRegistry">The storage of trade objects.</param>
 /// <param name="exchangeInfoProvider">Exchanges and trading boards provider.</param>
 /// <param name="drive">The storage. If a value is <see langword="null" />, <see cref="IStorageRegistry.DefaultDrive"/> will be used.</param>
 /// <param name="storageFormat">The format type. By default <see cref="StorageFormats.Binary"/> is passed.</param>
 public CsvImporter(DataType dataType, IEnumerable <FieldMapping> fields, IEntityRegistry entityRegistry, IExchangeInfoProvider exchangeInfoProvider, IMarketDataDrive drive, StorageFormats storageFormat)
     : base(dataType, fields)
 {
     _entityRegistry       = entityRegistry ?? throw new ArgumentNullException(nameof(entityRegistry));
     _exchangeInfoProvider = exchangeInfoProvider ?? throw new ArgumentNullException(nameof(exchangeInfoProvider));
     _drive         = drive;
     _storageFormat = storageFormat;
 }
Ejemplo n.º 11
0
		public HydraServer(IStorageRegistry storageRegistry, IEntityRegistry entityRegistry, IEnumerable<IHydraTask> tasks)
			: base(storageRegistry, entityRegistry)
		{
			if (tasks == null)
				throw new ArgumentNullException(nameof(tasks));

			_tasks = tasks;
		}
Ejemplo n.º 12
0
        /// <summary>
        /// Initializes a new instance of the <see cref="StorageMessageAdapter"/>.
        /// </summary>
        /// <param name="innerAdapter">The adapter, to which messages will be directed.</param>
        /// <param name="entityRegistry">The storage of trade objects.</param>
        /// <param name="storageRegistry">The storage of market data.</param>
        public StorageMessageAdapter(IMessageAdapter innerAdapter, IEntityRegistry entityRegistry, IStorageRegistry storageRegistry)
            : base(innerAdapter)
        {
            if (entityRegistry == null)
            {
                throw new ArgumentNullException("entityRegistry");
            }

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

            _entityRegistry  = entityRegistry;
            _storageRegistry = storageRegistry;

            Drive = _storageRegistry.DefaultDrive;

            ThreadingHelper.Timer(() =>
            {
                foreach (var pair in GetTicks())
                {
                    GetStorage(pair.Key, typeof(ExecutionMessage), ExecutionTypes.Tick).Save(pair.Value);
                }

                foreach (var pair in GetOrderLog())
                {
                    GetStorage(pair.Key, typeof(ExecutionMessage), ExecutionTypes.OrderLog).Save(pair.Value);
                }

                foreach (var pair in GetTransactions())
                {
                    GetStorage(pair.Key, typeof(ExecutionMessage), ExecutionTypes.Order).Save(pair.Value);
                }

                foreach (var pair in GetOrderBooks())
                {
                    GetStorage(pair.Key, typeof(QuoteChangeMessage), null).Save(pair.Value);
                }

                foreach (var pair in GetLevel1())
                {
                    GetStorage(pair.Key, typeof(Level1ChangeMessage), null).Save(pair.Value);
                }

                foreach (var pair in GetCandles())
                {
                    GetStorage(pair.Key.Item1, pair.Key.Item2, pair.Key.Item3).Save(pair.Value);
                }

                var news = GetNews().ToArray();

                if (news.Length > 0)
                {
                    _storageRegistry.GetNewsMessageStorage(Drive, Format).Save(news);
                }
            }).Interval(TimeSpan.FromSeconds(10));
        }
Ejemplo n.º 13
0
 private static T Convert <T>(
     this IList <PropertyModel> modelProperties,
     IEntityMetadata metaData,
     IEntityRegistry registry,
     IServiceProvider services) where T : IMappableRuleEntity
 {
     if (metaData.Type.GetCustomAttributes(typeof(ObsoleteAttribute), false).Any())
     {
         return(default);
Ejemplo n.º 14
0
 public void RefreshEntityOnModifierUsingUID(IModifier m)
 {
     if (m is IEntityModifier)
     {
         IEntityModifier em = m as IEntityModifier;
         IEntityRegistry r  = GetRegistryByEntityType(em.IntendedEntityType);
         em.e = r.GetUncastEntityByUID(em.e.UID);
     }
 }
Ejemplo n.º 15
0
        /// <summary>
        /// Initializes a new instance of the <see cref="StorageExchangeInfoProvider"/>.
        /// </summary>
        /// <param name="entityRegistry">The storage of trade objects.</param>
        /// <param name="autoInit">Invoke <see cref="Init"/> method.</param>
        public StorageExchangeInfoProvider(IEntityRegistry entityRegistry, bool autoInit = true)
        {
            _entityRegistry = entityRegistry ?? throw new ArgumentNullException(nameof(entityRegistry));

            if (autoInit)
            {
                Init();
            }
        }
Ejemplo n.º 16
0
        /// <summary>
        /// Initializes a new instance of the <see cref="StorageEntityFactory"/>.
        /// </summary>
        /// <param name="entityRegistry">The storage of trade objects.</param>
        public StorageEntityFactory(IEntityRegistry entityRegistry)
        {
            if (entityRegistry == null)
            {
                throw new ArgumentNullException(nameof(entityRegistry));
            }

            _entityRegistry = entityRegistry;
        }
Ejemplo n.º 17
0
		public SecurityEditWindow()
		{
			InitializeComponent();

			if (DesignerProperties.GetIsInDesignMode(this))
				return;

			_entityRegistry = ConfigManager.GetService<IEntityRegistry>();
		}
Ejemplo n.º 18
0
		public MfdSecurityStorage(IEntityRegistry entityRegistry)
		{
			if (entityRegistry == null)
				throw new ArgumentNullException("entityRegistry");

			_entityRegistry = entityRegistry;

			foreach (var security in entityRegistry.Securities)
				TryAddToCache(security);
		}
Ejemplo n.º 19
0
        public HydraServer(IStorageRegistry storageRegistry, IEntityRegistry entityRegistry, IEnumerable <IHydraTask> tasks)
            : base(storageRegistry, entityRegistry)
        {
            if (tasks == null)
            {
                throw new ArgumentNullException("tasks");
            }

            _tasks = tasks;
        }
		public GluingDataPane()
		{
			InitializeComponent();

			_entityRegistry = ConfigManager.GetService<IEntityRegistry>();

			SecurityPicker.SecurityProvider = ConfigManager.TryGetService<FilterableSecurityProvider>();

			MarketData.DataLoading += () => MarketDataBusyIndicator.IsBusy = true;
			MarketData.DataLoaded += () => MarketDataBusyIndicator.IsBusy = false;
		}
Ejemplo n.º 21
0
        public SecurityEditWindow()
        {
            InitializeComponent();

            if (DesignerProperties.GetIsInDesignMode(this))
            {
                return;
            }

            _entityRegistry = ConfigManager.GetService <IEntityRegistry>();
        }
Ejemplo n.º 22
0
        public GluingDataPane()
        {
            InitializeComponent();

            _entityRegistry = ConfigManager.GetService <IEntityRegistry>();

            SecurityPicker.SecurityProvider = ConfigManager.TryGetService <FilterableSecurityProvider>();

            MarketData.DataLoading += () => MarketDataBusyIndicator.IsBusy = true;
            MarketData.DataLoaded  += () => MarketDataBusyIndicator.IsBusy = false;
        }
Ejemplo n.º 23
0
		public SecurityEditWindow()
		{
			InitializeComponent();

			if (this.IsDesignMode())
				return;

			_entityRegistry = ConfigManager.GetService<IEntityRegistry>();

			ExchangeCtrl.ExchangeInfoProvider = ConfigManager.GetService<IExchangeInfoProvider>();
		}
Ejemplo n.º 24
0
        /// <summary>
        /// Initializes a new instance of the <see cref="NativeIdSecurityStorage{T}"/>.
        /// </summary>
        /// <param name="entityRegistry">The storage of trade objects.</param>
        /// <param name="comparer"><typeparamref name="TNativeId"/> comparer.</param>
        protected NativeIdSecurityStorage(IEntityRegistry entityRegistry, IEqualityComparer <TNativeId> comparer)
        {
            if (entityRegistry == null)
            {
                throw new ArgumentNullException(nameof(entityRegistry));
            }

            _entityRegistry  = entityRegistry;
            _cacheByNativeId = new SynchronizedDictionary <TNativeId, Security>(comparer);

            TryAddToCache(entityRegistry.Securities);
        }
Ejemplo n.º 25
0
        public void ApplyModWhere <E, M>(M m, Predicate <E> pkey) where M : IEntityModifier where E : IEntity, IModifiable <M>
        {
            IEntityRegistry <E> r = (IEntityRegistry <E>)Registries[typeof(E)];

            foreach (E e in r.Entities)
            {
                if (pkey.Invoke(e))
                {
                    ApplyMod(e, m);
                }
            }
        }
        public SecurityEditWindow()
        {
            InitializeComponent();

            if (this.IsDesignMode())
            {
                return;
            }

            _entityRegistry = ConfigManager.GetService <IEntityRegistry>();

            ExchangeCtrl.ExchangeInfoProvider = ConfigManager.GetService <IExchangeInfoProvider>();
        }
Ejemplo n.º 27
0
        public NewsPane()
        {
            InitializeComponent();

            Progress.Init(ExportBtn, MainGrid);

            From = DateTime.Today - TimeSpan.FromDays(7);
            To   = DateTime.Today + TimeSpan.FromDays(1);

            _entityRegistry = ConfigManager.GetService <IEntityRegistry>();

            ExportBtn.EnableType(ExportTypes.Bin, false);
        }
Ejemplo n.º 28
0
        public FinamSecurityStorage(IEntityRegistry entityRegistry)
        {
            if (entityRegistry == null)
            {
                throw new ArgumentNullException("entityRegistry");
            }

            _entityRegistry = entityRegistry;

            foreach (var security in entityRegistry.Securities)
            {
                TryAddToCache(security);
            }
        }
Ejemplo n.º 29
0
        //TODO: replace with some sort of global components - or make the simulation or rather 'graph' or something an entity with the layout components on it

        public Simulation(SimulationConfiguration configuration,
                          IEntityRegistry entityRegistry,
                          IMatcherProvider matcherProvider,
                          ISystemRegistry systemRegistry,
                          // TODO: remove zenject dependency when implicit optional collection paramters is implemented
                          IEntityFactoryProvider entityFactoryProvider,
                          CommandQueue commandQueue)
            : base(configuration,
                   entityRegistry,
                   matcherProvider,
                   systemRegistry,
                   entityFactoryProvider,
                   commandQueue)
        {
        }
Ejemplo n.º 30
0
		/// <summary>
		/// Initializes a new instance of the <see cref="StorageEntityFactory"/>.
		/// </summary>
		/// <param name="entityRegistry">The storage of trade objects.</param>
		/// <param name="storageRegistry">The storage of market data.</param>
		public StorageEntityFactory(IEntityRegistry entityRegistry, IStorageRegistry storageRegistry)
		{
			if (entityRegistry == null)
				throw new ArgumentNullException("entityRegistry");

			if (storageRegistry == null)
				throw new ArgumentNullException("storageRegistry");

			_entityRegistry = entityRegistry;
			_storageRegistry = storageRegistry;

			_securityStorage = storageRegistry.GetSecurityStorage();

			_securities = _securityStorage.LookupAll()
				.ToDictionary(s => s.Id, s => s, StringComparer.InvariantCultureIgnoreCase);
		}
Ejemplo n.º 31
0
        /// <summary>
        /// First time database initialization.
        /// </summary>
        /// <param name="entityRegistry">The storage of trade objects.</param>
        /// <param name="databaseRaw">Raw bytes of database file.</param>
        /// <param name="init">Initialization callback.</param>
        /// <returns>Path to the database file.</returns>
        public static string FirstTimeInit(this IEntityRegistry entityRegistry, byte[] databaseRaw, Action <Database> init = null)
        {
            if (entityRegistry == null)
            {
                throw new ArgumentNullException(nameof(entityRegistry));
            }

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

            var database = entityRegistry.Storage as Database;

            return(database?.FirstTimeInit(databaseRaw, init));
        }
Ejemplo n.º 32
0
        /// <summary>
        /// Initializes a new instance of the <see cref="StorageEntityFactory"/>.
        /// </summary>
        /// <param name="entityRegistry">The storage of trade objects.</param>
        /// <param name="storageRegistry">The storage of market data.</param>
        public StorageEntityFactory(IEntityRegistry entityRegistry, IStorageRegistry storageRegistry)
        {
            if (entityRegistry == null)
            {
                throw new ArgumentNullException("entityRegistry");
            }

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

            _entityRegistry  = entityRegistry;
            _storageRegistry = storageRegistry;

            _securityStorage = storageRegistry.GetSecurityStorage();

            _securities = _securityStorage.LookupAll()
                          .ToDictionary(s => s.Id, s => s, StringComparer.InvariantCultureIgnoreCase);
        }
Ejemplo n.º 33
0
		public TerminalConnector(IEntityRegistry entityRegistry, IStorageRegistry storageRegistry) : base(entityRegistry, storageRegistry)
		{
			Connected += OnConnected;
			StorageAdapter.Format = StorageFormats.Csv;
		}
Ejemplo n.º 34
0
 /// <summary>
 /// Initializes a new instance of the <see cref="StorageEntityFactory"/>.
 /// </summary>
 /// <param name="entityRegistry">The storage of trade objects.</param>
 public StorageEntityFactory(IEntityRegistry entityRegistry)
 {
     _entityRegistry = entityRegistry ?? throw new ArgumentNullException(nameof(entityRegistry));
 }
Ejemplo n.º 35
0
 protected ObjectEntity(IEntityRegistry entityRegistry) : base(entityRegistry)
 {
 }
Ejemplo n.º 36
0
		public TerminalConnector(IEntityRegistry entityRegistry, IStorageRegistry storageRegistry) : base(entityRegistry, storageRegistry)
		{
			
		}
Ejemplo n.º 37
0
 protected MobEntity(IEntityRegistry entityRegistry) : base(entityRegistry)
 {
 }
Ejemplo n.º 38
0
        private void InitConnector(IEntityRegistry entityRegistry, SnapshotRegistry snapshotRegistry, INativeIdStorage nativeIdStorage)
        {
            // subscribe on connection successfully event
            Connector.Connected += () =>
            {
                this.GuiAsync(() => ChangeConnectStatus(true));

                if (Connector.Adapter.IsMarketDataTypeSupported(DataType.News) && !Connector.Adapter.IsSecurityNewsOnly)
                {
                    Connector.SubscribeNews();
                }
            };

            // subscribe on connection error event
            Connector.ConnectionError += error => this.GuiAsync(() =>
            {
                ChangeConnectStatus(false);
                MessageBox.Show(this, error.ToString(), LocalizedStrings.Str2959);
            });

            Connector.Disconnected += () => this.GuiAsync(() => ChangeConnectStatus(false));

            // subscribe on error event
            //Connector.Error += error =>
            //	this.GuiAsync(() => MessageBox.Show(this, error.ToString(), LocalizedStrings.Str2955));

            // subscribe on error of market data subscription event
            Connector.MarketDataSubscriptionFailed += (security, msg, error) =>
                                                      this.GuiAsync(() => MessageBox.Show(this, error.ToString(), LocalizedStrings.Str2956Params.Put(msg.DataType, security)));

            Connector.NewSecurity     += _securitiesWindow.SecurityPicker.Securities.Add;
            Connector.NewTrade        += _tradesWindow.TradeGrid.Trades.Add;
            Connector.NewOrderLogItem += _orderLogWindow.OrderLogGrid.LogItems.Add;

            Connector.NewOrder   += _ordersWindow.OrderGrid.Orders.Add;
            Connector.NewMyTrade += _myTradesWindow.TradeGrid.Trades.Add;

            Connector.NewPortfolio += _portfoliosWindow.PortfolioGrid.Positions.Add;
            Connector.NewPosition  += _portfoliosWindow.PortfolioGrid.Positions.Add;

            // subscribe on error of order registration event
            Connector.OrderRegisterFailed += _ordersWindow.OrderGrid.AddRegistrationFail;
            // subscribe on error of order cancelling event
            Connector.OrderCancelFailed += OrderFailed;

            // set market data provider
            _securitiesWindow.SecurityPicker.MarketDataProvider = Connector;

            // set news provider
            _newsWindow.NewsPanel.NewsProvider = Connector;

            Connector.LookupTimeFramesResult += (message, timeFrames, error) =>
            {
                if (error == null)
                {
                    this.GuiAsync(() => _securitiesWindow.UpdateTimeFrames(timeFrames));
                }
            };

            Connector.Adapter.NativeIdStorage = nativeIdStorage;

            try
            {
                nativeIdStorage.Init();
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.ToString());
            }

            if (Connector.StorageAdapter == null)
            {
                return;
            }

            try
            {
                entityRegistry.Init();
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.ToString());
            }

            Connector.Adapter.StorageProcessor.DaysLoad = TimeSpan.FromDays(3);
            Connector.Adapter.StorageProcessor.Mode     = StorageModes.Snapshot;
            Connector.LookupAll();

            snapshotRegistry.Init();

            ConfigManager.RegisterService <IExchangeInfoProvider>(new StorageExchangeInfoProvider(entityRegistry));
            ConfigManager.RegisterService <IMessageAdapterProvider>(new FullInMemoryMessageAdapterProvider(Connector.Adapter.InnerAdapters));

            try
            {
                if (File.Exists(_settingsFile))
                {
                    var ctx = new ContinueOnExceptionContext();
                    ctx.Error += ex => ex.LogError();

                    using (ctx.ToScope())
                        Connector.Load(new XmlSerializer <SettingsStorage>().Deserialize(_settingsFile));
                }
            }
            catch
            {
            }
        }
Ejemplo n.º 39
0
        /// <summary>
        /// Initializes a new instance of the <see cref="SecurityList"/>.
        /// </summary>
        /// <param name="registry">The storage of trade objects.</param>
        public SecurityList(IEntityRegistry registry)
            : base(registry.Storage)
        {
            _registry = registry;

            var database = Storage as Database;

            if (database == null)
            {
                return;
            }

            var readAllByCodeAndType = database.CommandType == CommandType.StoredProcedure
                                ? Query.Execute(Schema, SqlCommandTypes.ReadAll, string.Empty, "CodeAndType")
                                : Query
                                       .Select(Schema)
                                       .From(Schema)
                                       .Where()
                                       .Like(Schema.Fields[_code])
                                       .And()
                                       .OpenBracket()
                                       .IsParamNull(Schema.Fields[_type])
                                       .Or()
                                       .Equals(Schema.Fields[_type])
                                       .CloseBracket();

            _readAllByCodeAndType = database.GetCommand(readAllByCodeAndType, Schema, new FieldList(Schema.Fields[_code], Schema.Fields[_type]), new FieldList());

            var readAllByCodeAndTypeAndExpiryDate = database.CommandType == CommandType.StoredProcedure
                                ? Query.Execute(Schema, SqlCommandTypes.ReadAll, string.Empty, "CodeAndTypeAndExpiryDate")
                                : Query
                                                    .Select(Schema)
                                                    .From(Schema)
                                                    .Where()
                                                    .Like(Schema.Fields[_code])
                                                    .And()
                                                    .OpenBracket()
                                                    .IsParamNull(Schema.Fields[_type])
                                                    .Or()
                                                    .Equals(Schema.Fields[_type])
                                                    .CloseBracket()
                                                    .And()
                                                    .OpenBracket()
                                                    .IsNull(Schema.Fields[_expiryDate])
                                                    .Or()
                                                    .Equals(Schema.Fields[_expiryDate])
                                                    .CloseBracket();

            _readAllByCodeAndTypeAndExpiryDate = database.GetCommand(readAllByCodeAndTypeAndExpiryDate, Schema, new FieldList(Schema.Fields[_code], Schema.Fields[_type], Schema.Fields[_expiryDate]), new FieldList());

            if (database.CommandType == CommandType.Text)
            {
                var readSecurityIds = Query
                                      .Execute("SELECT group_concat(Id, ',') FROM Security");

                _readSecurityIds = database.GetCommand(readSecurityIds, null, new FieldList(), new FieldList());

                var readAllByBoardAndType = Query
                                            .Select(Schema)
                                            .From(Schema)
                                            .Where()
                                            .Equals(Schema.Fields[_board])
                                            .And()
                                            .OpenBracket()
                                            .IsParamNull(Schema.Fields[_type])
                                            .Or()
                                            .Equals(Schema.Fields[_type])
                                            .CloseBracket();

                _readAllByBoardAndType = database.GetCommand(readAllByBoardAndType, Schema, new FieldList(Schema.Fields[_board], Schema.Fields[_type]), new FieldList());

                var readAllByTypeAndExpiryDate = Query
                                                 .Select(Schema)
                                                 .From(Schema)
                                                 .Where()
                                                 .Equals(Schema.Fields[_type])
                                                 .And()
                                                 .OpenBracket()
                                                 .IsNull(Schema.Fields[_expiryDate])
                                                 .Or()
                                                 .Equals(Schema.Fields[_expiryDate])
                                                 .CloseBracket();

                _readAllByTypeAndExpiryDate = database.GetCommand(readAllByTypeAndExpiryDate, Schema, new FieldList(Schema.Fields[_type], Schema.Fields[_expiryDate]), new FieldList());

                var readAllByType = Query
                                    .Select(Schema)
                                    .From(Schema)
                                    .Where()
                                    .Equals(Schema.Fields[_type]);

                _readAllByType = database.GetCommand(readAllByType, Schema, new FieldList(Schema.Fields[_type]), new FieldList());

                RemoveQuery = Query
                              .Delete()
                              .From(Schema)
                              .Where()
                              .Equals(Schema.Fields[_id]);
            }

            ((ICollectionEx <Security>) this).AddedRange   += s => _added?.Invoke(s);
            ((ICollectionEx <Security>) this).RemovedRange += s => _removed?.Invoke(s);
        }
Ejemplo n.º 40
0
        private void InitConnector(IEntityRegistry entityRegistry, SnapshotRegistry snapshotRegistry)
        {
            // subscribe on connection successfully event
            Connector.Connected += () =>
            {
                this.GuiAsync(() => ChangeConnectStatus(true));
            };

            // subscribe on connection error event
            Connector.ConnectionError += error => this.GuiAsync(() =>
            {
                ChangeConnectStatus(false);
                MessageBox.Show(this, error.ToString(), LocalizedStrings.Str2959);
            });

            Connector.Disconnected += () => this.GuiAsync(() => ChangeConnectStatus(false));

            // subscribe on error event
            Connector.Error += error =>
            {
                this.GuiAsync(() => MessageBox.Show(this, error.ToString(), LocalizedStrings.Str2955));
            };

            // subscribe on error of market data subscription event
            Connector.MarketDataSubscriptionFailed += (security, msg, error) =>
            {
                this.GuiAsync(() => MessageBox.Show(this, error.ToString(), LocalizedStrings.Str2956Params.Put(msg.DataType, security)));
            };

            Connector.SecurityReceived += (sub, s) => _securitiesWindow.SecurityPicker.Securities.Add(s);

            Connector.NewOrder += order =>
            {
                _ordersWindow.OrderGrid.Orders.Add(order);
                _securitiesWindow.ProcessOrder(order);
            };

            // display order as own volume in quotes window
            Connector.OrderChanged += _securitiesWindow.ProcessOrder;

            // put the registration error into order's table
            Connector.OrderRegisterFailed += _ordersWindow.OrderGrid.AddRegistrationFail;

            Connector.NewMyTrade += _myTradesWindow.TradeGrid.Trades.Add;

            Connector.PositionReceived += (sub, p) => _portfoliosWindow.PortfolioGrid.Positions.TryAdd(p);

            // set market data provider
            _securitiesWindow.SecurityPicker.MarketDataProvider = Connector;

            if (Connector.StorageAdapter == null)
            {
                return;
            }

            entityRegistry.Init();
            snapshotRegistry.Init();

            Connector.LookupAll();

            ConfigManager.RegisterService <IMessageAdapterProvider>(new FullInMemoryMessageAdapterProvider(Connector.Adapter.InnerAdapters));

            try
            {
                if (File.Exists(_settingsFile) || File.Exists(_settingsFile.MakeLegacy()))
                {
                    var ctx = new ContinueOnExceptionContext();
                    ctx.Error += ex => ex.LogError();

                    using (ctx.ToScope())
                        Connector.LoadIfNotNull(_settingsFile.DeserializeWithMigration <SettingsStorage>());
                }
            }
            catch
            {
            }
        }