public MainWindow()
		{
			InitializeComponent();
			Instance = this;

			Title = Title.Put("Multi connection");

			_ordersWindow.MakeHideable();
			_myTradesWindow.MakeHideable();
			_tradesWindow.MakeHideable();
			_securitiesWindow.MakeHideable();
			_stopOrdersWindow.MakeHideable();
			_portfoliosWindow.MakeHideable();

			var logManager = new LogManager();
			logManager.Application.LogLevel = LogLevels.Debug;
			logManager.Listeners.Add(new FileLogListener("sample.log"));

			var entityRegistry = ConfigManager.GetService<IEntityRegistry>();
			var storageRegistry = ConfigManager.GetService<IStorageRegistry>();

			Connector = new Connector(entityRegistry, storageRegistry);
			logManager.Sources.Add(Connector);

			InitConnector();
		}
Exemple #2
0
		public NewOrderTest(Connector connector, FilterableSecurityProvider securityProvider)
		{
			InitializeComponent();

			_connector = connector;

			Portfolios.Connector = connector;
			Securities.SecurityProvider = securityProvider;
		}
Exemple #3
0
		private Connector InitReconnectionSettings(Connector trader)
		{
			// инициализируем механизм переподключения
			trader.ReConnectionSettings.WorkingTime = ExchangeBoard.Forts.WorkingTime;
			trader.Restored += () => this.GuiAsync(() =>
			{
				// разблокируем кнопку Экспорт (соединение было восстановлено)
				ChangeConnectStatus(true);
				MessageBox.Show(this, LocalizedStrings.Str2958);
			});

			return trader;
		}
		private void Test_Click(object sender, RoutedEventArgs e)
		{
			if (!CheckIsValid())
				return;

			BusyIndicator.IsBusy = true;
			Test.IsEnabled = false;

			var connector = new Connector();
			connector.Adapter.InnerAdapters.Add(_editableAdapter);

			connector.Connected += () =>
			{
				connector.Dispose();

				GuiDispatcher.GlobalDispatcher.AddSyncAction(() =>
				{
					new MessageBoxBuilder()
						.Text(LocalizedStrings.Str1560)
						.Owner(this)
						.Show();

					BusyIndicator.IsBusy = false;
					Test.IsEnabled = true;
				});
			};

			connector.ConnectionError += error =>
			{
				connector.Dispose();

				GuiDispatcher.GlobalDispatcher.AddSyncAction(() =>
				{
					new MessageBoxBuilder()
						.Text(LocalizedStrings.Str1561 + Environment.NewLine + error)
						.Error()
						.Owner(this)
						.Show();

					BusyIndicator.IsBusy = false;
					Test.IsEnabled = true;
				});
			};

			connector.Connect();
		}
		public MainWindow()
		{
			InitializeComponent();

			this.LayoutManager = new LayoutManager(this, ProgrammaticDockSite);
			LayoutManager._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)};
			var securityStorage = storageRegistry.GetSecurityStorage();

			Connector = new Connector {EntityFactory = new StorageEntityFactory(securityStorage)};
			ConfigManager.RegisterService(new FilterableSecurityProvider(securityStorage));
			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.NewSecurities += _secView.SecurityGrid.Securities.AddRange;

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

					if (ctrl != null)
						ctrl.UpdateDepth(depth);
				}
			};
		}
Exemple #6
0
		private void ConnectClick(object sender, RoutedEventArgs e)
		{
			if (!_isConnected)
			{
				if (Connector == null)
				{
					var isDde = IsDde.IsChecked == true;

					if (SmartLogin.Text.IsEmpty())
					{
						MessageBox.Show(this, LocalizedStrings.Str2965);
						return;
					}
					if (SmartPassword.Password.IsEmpty())
					{
						MessageBox.Show(this, LocalizedStrings.Str2966);
						return;
					}
					if (isDde && QuikPath.Text.IsEmpty())
					{
						MessageBox.Show(this, LocalizedStrings.Str2967);
						return;
					}

					// создаем агрегирующее подключение (+ сразу инициализируем настройки переподключения)
					Connector = InitReconnectionSettings(new Connector());

					// добавляем подключения к SmartCOM и Quik
					var quikTs = new LuaFixTransactionMessageAdapter(Connector.TransactionIdGenerator)
					{
						Login = "******",
						Password = "******".To<SecureString>(),
						Address = QuikTrader.DefaultLuaAddress,
						TargetCompId = "StockSharpTS",
						SenderCompId = "quik",
						ExchangeBoard = ExchangeBoard.Forts,
						Version = FixVersions.Fix44_Lua,
						RequestAllPortfolios = true,
						MarketData = FixMarketData.None,
						TimeZone = TimeHelper.Moscow
					};
					var quikMd = new FixMessageAdapter(Connector.TransactionIdGenerator)
					{
						Login = "******",
						Password = "******".To<SecureString>(),
						Address = QuikTrader.DefaultLuaAddress,
						TargetCompId = "StockSharpMD",
						SenderCompId = "quik",
						ExchangeBoard = ExchangeBoard.Forts,
						Version = FixVersions.Fix44_Lua,
						RequestAllSecurities = true,
						MarketData = FixMarketData.MarketData,
						TimeZone = TimeHelper.Moscow
					};
					quikMd.RemoveTransactionalSupport();

					Connector.Adapter.InnerAdapters[quikMd] = 1;
					Connector.Adapter.InnerAdapters[quikTs] = 1;

					var smartCom = new SmartComMessageAdapter(Connector.TransactionIdGenerator)
					{
						Login = SmartLogin.Text,
						Password = SmartPassword.Password.To<SecureString>(),
						Address = SmartAddress.SelectedAddress,
					};
					Connector.Adapter.InnerAdapters[smartCom] = 0;

					// очищаем из текстового поля в целях безопасности
					//SmartPassword.Clear();

					var logManager = new LogManager();
					logManager.Listeners.Add(new FileLogListener("sample.log"));
					logManager.Sources.Add(Connector);

					// подписываемся на событие успешного соединения
					Connector.Connected += () =>
					{
						// возводим флаг, что соединение установлено
						_isConnected = true;

						// разблокируем кнопку Экспорт
						this.GuiAsync(() => ChangeConnectStatus(true));
					};

					// подписываемся на событие разрыва соединения
					Connector.ConnectionError += error => this.GuiAsync(() =>
					{
						// заблокируем кнопку Экспорт (так как соединение было потеряно)
						ChangeConnectStatus(false);

						MessageBox.Show(this, error.ToString(), LocalizedStrings.Str2959);	
					});

					// подписываемся на ошибку обработки данных (транзакций и маркет)
					Connector.Error += error =>
						this.GuiAsync(() => MessageBox.Show(this, error.ToString(), LocalizedStrings.Str2955));

					// подписываемся на ошибку подписки маркет-данных
					Connector.MarketDataSubscriptionFailed += (security, type, error) =>
						this.GuiAsync(() => MessageBox.Show(this, error.ToString(), LocalizedStrings.Str2956Params.Put(type, security)));

					Connector.NewSecurities += securities => _securitiesWindow.SecurityPicker.Securities.AddRange(securities);
					Connector.NewOrders += orders => _ordersWindow.OrderGrid.Orders.AddRange(orders);

					// подписываемся на событие о неудачной регистрации заявок
					Connector.OrdersRegisterFailed += OrdersFailed;
					// подписываемся на событие о неудачном снятии заявок
					Connector.OrdersCancelFailed += OrdersFailed;

					// подписываемся на событие о неудачной регистрации стоп-заявок
					Connector.StopOrdersRegisterFailed += OrdersFailed;
					// подписываемся на событие о неудачном снятии стоп-заявок
					Connector.StopOrdersCancelFailed += OrdersFailed;

					// устанавливаем поставщик маркет-данных
					_securitiesWindow.SecurityPicker.MarketDataProvider = Connector;

					ShowSecurities.IsEnabled = ShowOrders.IsEnabled = true;
				}

				Connector.Connect();
			}
			else
			{
				Connector.Disconnect();
			}
		}
		public MainWindow()
		{
			InitializeComponent();

			Title = TypeHelper.ApplicationNameWithVersion;

			InitializeDataSource();

			Directory.CreateDirectory(BaseApplication.AppDataPath);

			var compositionsPath = Path.Combine(BaseApplication.AppDataPath, "Compositions");
			var strategiesPath = Path.Combine(BaseApplication.AppDataPath, "Strategies");
			var logsPath = Path.Combine(BaseApplication.AppDataPath, "Logs");

			_settingsFile = Path.Combine(BaseApplication.AppDataPath, "settings.xml");

			var logManager = new LogManager();
			logManager.Listeners.Add(new FileLogListener
			{
				Append = true,
				LogDirectory = logsPath,
				MaxLength = 1024 * 1024 * 100 /* 100mb */,
				MaxCount = 10,
				SeparateByDates = SeparateByDateModes.SubDirectories,
			});
			logManager.Listeners.Add(new GuiLogListener(Monitor));

			_strategiesRegistry = new StrategiesRegistry(compositionsPath, strategiesPath);
			logManager.Sources.Add(_strategiesRegistry);
			_strategiesRegistry.Init();

			_layoutManager = new LayoutManager(DockingManager);
			_layoutManager.Changed += SaveSettings;
			logManager.Sources.Add(_layoutManager);

			var entityRegistry = ConfigManager.GetService<IEntityRegistry>();
			var storageRegistry = ConfigManager.GetService<IStorageRegistry>();

			_connector = new Connector(entityRegistry, storageRegistry)
			{
				StorageAdapter =
				{
					DaysLoad = TimeSpan.Zero
				}
			};
			_connector.Connected += ConnectorOnConnectionStateChanged;
			_connector.Disconnected += ConnectorOnConnectionStateChanged;
			_connector.ConnectionError += ConnectorOnConnectionError;
			logManager.Sources.Add(_connector);

			ConfigManager.RegisterService(logManager);
			ConfigManager.RegisterService(_strategiesRegistry);
			ConfigManager.RegisterService(_layoutManager);
			ConfigManager.RegisterService<IConnector>(_connector);
			ConfigManager.RegisterService<ISecurityProvider>(_connector);

			SolutionExplorer.Compositions = _strategiesRegistry.Compositions;
			SolutionExplorer.Strategies = _strategiesRegistry.Strategies;
		}
Exemple #8
0
 public SubscriptionManager(Connector connector)
 {
     _connector = connector ?? throw new ArgumentNullException(nameof(connector));
 }
Exemple #9
0
		private void QuikConnectionMouseDoubleClick(object sender, RoutedEventArgs e)
		{
			if (_connector == null)
			{
				_connector = new Connector();

				if (QuikCheckBox.IsChecked == true)
				{
					var quikTs = new LuaFixTransactionMessageAdapter(_connector.TransactionIdGenerator)
					{
						Login = "******",
						Password = "******".To<SecureString>(),
						Address = QuikTrader.DefaultLuaAddress,
						TargetCompId = "StockSharpTS",
						SenderCompId = "quik",
						ExchangeBoard = ExchangeBoard.Forts,
						Version = FixVersions.Fix44_Lua,
						RequestAllPortfolios = true,
						MarketData = FixMarketData.None,
						TimeZone = TimeHelper.Moscow
					};
					var quikMd = new FixMessageAdapter(_connector.TransactionIdGenerator)
					{
						Login = "******",
						Password = "******".To<SecureString>(),
						Address = QuikTrader.DefaultLuaAddress,
						TargetCompId = "StockSharpMD",
						SenderCompId = "quik",
						ExchangeBoard = ExchangeBoard.Forts,
						Version = FixVersions.Fix44_Lua,
						RequestAllSecurities = true,
						MarketData = FixMarketData.MarketData,
						TimeZone = TimeHelper.Moscow
					};
					quikMd.RemoveTransactionalSupport();

					_connector.Adapter.InnerAdapters[quikMd.ToChannel(_connector, "Quik MD")] = 1;
					_connector.Adapter.InnerAdapters[quikTs.ToChannel(_connector, "Quik TS")] = 1;
				}

				if (SmartComCheckBox.IsChecked == true)
				{
					var smartCom = new SmartComMessageAdapter(_connector.TransactionIdGenerator)
					{
						Login = Login.Text,
						Password = Password.Password.To<SecureString>(),
						Address = Address.SelectedAddress,
					};
					_connector.Adapter.InnerAdapters[smartCom.ToChannel(_connector, "SmartCOM")] = 0;
				}

				if (PlazaCheckBox.IsChecked == true)
				{
					var pool = new PlazaConnectionPool();

					_connector.Adapter.InnerAdapters[new PlazaTransactionMessageAdapter(_connector.TransactionIdGenerator, pool)
					{
						ConnectionPoolSettings =
						{
							IsCGate = true,
						}
					}.ToChannel(_connector, "Plaza TS")] = 0;
					_connector.Adapter.InnerAdapters[new PlazaStreamMessageAdapter(_connector.TransactionIdGenerator, pool)
					{
						ConnectionPoolSettings =
						{
							IsCGate = true,
						}
					}.ToChannel(_connector, "Plaza MD")] = 0;
				}

				if (_connector.Adapter.InnerAdapters.Count == 0)
				{
					MessageBox.Show(this, LocalizedStrings.Str2971);
					return;
				}

				_securityProvider = new FilterableSecurityProvider(_connector);

				_connector.ConnectionError += error => this.GuiAsync(() => MessageBox.Show(this, error.ToString(), LocalizedStrings.Str2959));
				_connector.Connect();
			}
			else
			{
				Disconnect();
			}
		}
Exemple #10
0
		private void Disconnect()
		{
			try
			{
				foreach (var security in Strategies.Select(s => s.Security))
				{
					_connector.UnRegisterMarketDepth(security);
				}

				QuikCheckBox.IsEnabled = SmartComCheckBox.IsEnabled = true;
				Strategies.Clear();

				Connection.Background = new SolidColorBrush(Colors.LightCoral);
				ConnectButton.Header = LocalizedStrings.Connect;

				_connector.Disconnect();
				_connector = null;

			}
			catch (Exception ex)
			{
				MessageBox.Show(this, ex.ToString());
			}
		}
        private void Connect()
        {
            if (_connector == null)
            {
	            _connector = new QuikTrader { LogLevel = LogLevels.Debug };

	            _logManager.Sources.Add(_connector);

                _logManager.Listeners.Add(new GuiLogListener(Monitor));

                _connector.Connected += () => 
                {
                    _isConnectClick = false;
                    this.GuiAsync(() => ConnectButton.Content = LocalizedStrings.Disconnect);

                };

                _connector.Disconnected += () => 
                {
                    _isConnectClick = false;
                    this.GuiAsync(() => ConnectButton.Content = LocalizedStrings.Connect);
                };

                SecurityEditor.SecurityProvider = new FilterableSecurityProvider(_connector);
               
                _connector.NewSecurities += securities => { };

                _connector.NewMyTrades += trades =>
                            {
                                trades.ForEach(t =>
                                {
                                    if (Subscriptions.Any(s => s.Security == t.Trade.Security && s.Trades))
                                    {
                                        MyTradeGrid.Trades.Add(t);
                                        SaveToFile(MyTradeToString(t), _myTradesFilePath);
                                    }
                                });
                            };

                _connector.NewTrades += trades =>
                            {
                                TradeGrid.Trades.AddRange(trades);
                                trades.ForEach(t => SaveToFile(TradeToString(t), _tradesFilePath));
                            };

                _connector.NewOrders += orders =>
                            {
                                orders.ForEach(o =>
                                {
                                    if (Subscriptions.Any(s => s.Security == o.Security && s.Orders))
                                    {
                                        OrderGrid.Orders.Add(o);
                                        SaveToFile(OrderToString(o), _ordersFilePath);
                                    }
                                });
                            };

                _connector.OrdersChanged += orders =>
                            {
                                orders.ForEach(o =>
                                {
                                    if (Subscriptions.Any(s => s.Security == o.Security && s.Orders))
                                    {
                                        OrderGrid.Orders.Add(o);
                                        SaveToFile(OrderToString(o), _ordersFilePath);
                                    }
                                });
                            };

                _connector.NewStopOrders += orders =>
                            {
                                orders.ForEach(o =>
                                {
                                    if (Subscriptions.Any(s => s.Security == o.Security && s.Orders))
                                    {
                                        OrderGrid.Orders.Add(o);
                                        SaveToFile(OrderToString(o), _ordersFilePath);
                                    }
                                });
                            };

                _connector.StopOrdersChanged += orders =>
                            {
                                orders.ForEach(o =>
                                {
                                    if (Subscriptions.Any(s => s.Security == o.Security && s.Orders))
                                    {
                                        OrderGrid.Orders.Add(o);
                                        SaveToFile(OrderToString(o), _ordersFilePath);
                                    }
                                });
                            };

                _connector.NewPortfolios += portfolios => PortfolioGrid.Portfolios.AddRange(portfolios);

                _connector.NewPositions += positions =>
                            {
                                positions.ForEach(p => 
                                {
                                    if (Subscriptions.Any(s => s.Security == p.Security ))
                                    {
                                        PortfolioGrid.Positions.Add(p);
                                        SaveToFile(PositionToString(p), _positionsFilePath);
                                    }
                                });
                            };

                _connector.PositionsChanged += positions =>
                {
                    positions.ForEach(p =>
                    {
                        if (Subscriptions.Any(s => s.Security == p.Security))
                        {
                            PortfolioGrid.Positions.Add(p);
                            SaveToFile(PositionToString(p), _positionsFilePath);
                        }
                    });
                };


                _connector.SecuritiesChanged += securities =>
                            {
                                securities.ForEach(s => SaveToFile(Level1ToString(s), _level1FilePath));
                            };

                _connector.MarketDepthsChanged += depths =>
                            {
                                depths.ForEach(d => DepthToFile(d, Path.Combine(_outputFolder, string.Format("{0}_depth.txt", d.Security.Code))));
                            };

                //_connector.ValuesChanged += (a, b, c, d) => { };

            }

            _connector.Connect();
        }