Ejemplo n.º 1
0
        public static bool GetIsAutoStart(this StrategyContainer strategy)
        {
            if (strategy == null)
            {
                throw new ArgumentNullException("strategy");
            }

            return(strategy.StrategyInfo.StrategyType != null && strategy.StrategyInfo.StrategyType.GetAttribute <AutoStartAttribute>() != null);
        }
Ejemplo n.º 2
0
        public static void SetIsInitialization(this StrategyContainer strategy, bool isInitialization)
        {
            if (strategy.Strategy != null)
            {
                strategy.Strategy.SetIsInitialization(isInitialization);
            }

            strategy.Environment.SetValue("IsInitializationMode", isInitialization);
        }
Ejemplo n.º 3
0
        public static bool GetIsInteracted(this StrategyContainer strategy)
        {
            if (strategy == null)
            {
                throw new ArgumentNullException(nameof(strategy));
            }

            return(strategy.StrategyInfo.StrategyType != null && strategy.StrategyInfo.StrategyType.GetAttribute <InteractedStrategyAttribute>() != null);
        }
Ejemplo n.º 4
0
        public static void InitStrategy(this StrategyContainer container)
        {
            var info = container.StrategyInfo;

            switch (info.Type)
            {
            case StrategyInfoTypes.SourceCode:
            case StrategyInfoTypes.Analytics:
            {
                if (info.StrategyType != null)
                {
                    container.Strategy = info.StrategyType.CreateInstance <Strategy>();
                }

                break;
            }

            case StrategyInfoTypes.Diagram:
            {
                GuiDispatcher.GlobalDispatcher.AddAction(() =>
                    {
                        var strategy = (DiagramStrategy)container.Strategy;

                        if (strategy == null)
                        {
                            container.Strategy = strategy = new DiagramStrategy();
                        }

                        try
                        {
                            strategy.Composition = ConfigManager.GetService <CompositionRegistry>().Deserialize(info.Body.LoadSettingsStorage());
                        }
                        catch (Exception ex)
                        {
                            strategy.AddErrorLog(LocalizedStrings.Str3175Params, ex);
                        }
                    });

                break;
            }

            case StrategyInfoTypes.Terminal:
            case StrategyInfoTypes.Assembly:
            {
                if (info.StrategyType != null)
                {
                    container.Strategy = info.StrategyType.CreateInstance <Strategy>();
                }

                break;
            }

            default:
                throw new ArgumentOutOfRangeException();
            }
        }
Ejemplo n.º 5
0
		public CandleChartPanel()
		{
			InitializeComponent();

			var cmdSvc = ConfigManager.GetService<IStudioCommandService>();
			cmdSvc.Register<ChartDrawCommand>(this, false, cmd => _bufferedChart.Draw(cmd.Values));
			cmdSvc.Register<ChartAddAreaCommand>(this, false, cmd => _bufferedChart.AddArea(cmd.Area));
			cmdSvc.Register<ChartRemoveAreaCommand>(this, false, cmd => _bufferedChart.RemoveArea(cmd.Area));
			cmdSvc.Register<ChartAddElementCommand>(this, false, cmd => _bufferedChart.AddElement(cmd.Area, cmd.Element));
			cmdSvc.Register<ChartRemoveElementCommand>(this, false, cmd => _bufferedChart.RemoveElement(cmd.Area, cmd.Element));
			cmdSvc.Register<ChartClearAreasCommand>(this, false, cmd => _bufferedChart.ClearAreas());
			cmdSvc.Register<ChartResetElementsCommand>(this, false, cmd => _bufferedChart.Reset(cmd.Elements));
			cmdSvc.Register<ChartAutoRangeCommand>(this, false, cmd => _bufferedChart.IsAutoRange = cmd.AutoRange);
			cmdSvc.Register<ResetedCommand>(this, true, cmd => OnReseted());
			cmdSvc.Register<BindStrategyCommand>(this, true, cmd =>
			{
				if (!cmd.CheckControl(this))
					return;

				if (_strategy == cmd.Source)
					return;

				_strategy = cmd.Source;

				SetChart(true);

				ChartPanel.IsInteracted = _strategy != null && _strategy.GetIsInteracted();

				if (_settingsStorage != null)
					ChartPanel.Load(_settingsStorage);

				TryCreateDefaultSeries();
			});
			
			ChartPanel.SettingsChanged += () => new ControlChangedCommand(this).Process(this);
			ChartPanel.RegisterOrder += order => new RegisterOrderCommand(order).Process(this);
			ChartPanel.SubscribeCandleElement += OnChartPanelSubscribeCandleElement;
			ChartPanel.SubscribeIndicatorElement += OnChartPanelSubscribeIndicatorElement;
			ChartPanel.SubscribeOrderElement += OnChartPanelSubscribeOrderElement;
			ChartPanel.SubscribeTradeElement += OnChartPanelSubscribeTradeElement;
			ChartPanel.UnSubscribeElement += OnChartPanelUnSubscribeElement;

			var indicatorTypes = ConfigManager
				.GetService<IAlgoService>()
				.IndicatorTypes;

			ChartPanel.MinimumRange = 200;
			ChartPanel.IndicatorTypes.AddRange(indicatorTypes);

			_bufferedChart = new BufferedChart(ChartPanel);

			WhenLoaded(() => new RequestBindSource(this).SyncProcess(this));
		}
Ejemplo n.º 6
0
			public StrategyConnector(StrategyContainer strategy, DateTimeOffset startDate, DateTimeOffset stopDate, TimeSpan useCandlesTimeFrame, bool onlyInitialize)
			{
				if (strategy == null)
					throw new ArgumentNullException(nameof(strategy));

				UpdateSecurityLastQuotes = false;
				UpdateSecurityByLevel1 = false;

				var entityRegistry = ConfigManager.GetService<IStudioEntityRegistry>();

				_strategy = strategy;
				_useCandlesTimeFrame = useCandlesTimeFrame;
				_onlyInitialize = onlyInitialize;
				_sessionStrategy = entityRegistry.ReadSessionStrategyById(strategy.Strategy.Id);

				if (_sessionStrategy == null)
					throw new InvalidOperationException("sessionStrategy = null");

				Id = strategy.Id;
				Name = strategy.Name + " Connector";

				_realConnector = (StudioConnector)ConfigManager.GetService<IStudioConnector>();
				_realConnector.NewMessage += RealConnectorNewMessage;

				_securityProvider = new StudioSecurityProvider();

				var storageRegistry = new StudioStorageRegistry { MarketDataSettings = strategy.MarketDataSettings };

				//EntityFactory = new StorageEntityFactory(entityRegistry, storageRegistry);

				Adapter.InnerAdapters.Add(_historyMessageAdapter = new HistoryMessageAdapter(TransactionIdGenerator, _securityProvider)
				{
					StartDate = startDate,
					StopDate = stopDate,
					StorageRegistry = storageRegistry
				});
				//_historyMessageAdapter.UpdateCurrentTime(startDate);
				var transactionAdapter = new PassThroughMessageAdapter(TransactionIdGenerator);
				transactionAdapter.AddTransactionalSupport();
				Adapter.InnerAdapters.Add(transactionAdapter);

				_historyMessageAdapter.MarketTimeChangedInterval = useCandlesTimeFrame;

				// при инициализации по свечкам, время меняется быстрее и таймаут должен быть больше 30с.
				ReConnectionSettings.TimeOutInterval = TimeSpan.MaxValue;

				//_historyMessageAdapter.BasketStorage.InnerStorages.AddRange(GetExecutionStorages());

				this.LookupById(strategy.Security.Id);

				new ChartAutoRangeCommand(true).Process(_strategy);
			}
Ejemplo n.º 7
0
		public UniversalGridPanel()
		{
			InitializeComponent();

			ConfigManager
				.GetService<IStudioCommandService>()
				.Register<BindStrategyCommand>(this, true, cmd =>
				{
					if (!cmd.CheckControl(this))
						return;

					if (_strategy == cmd.Source)
						return;

					_strategy = cmd.Source;
					SetGrid(Grid);
				});

			WhenLoaded(() => new RequestBindSource(this).SyncProcess(this));
		}
Ejemplo n.º 8
0
		private void StrategyAdded(StrategyContainer strategyContainer)
		{
			StrategiesCollectionChanged();
		}
		private void StrategyRemoved(StrategyContainer strategy)
		{
			CloseWindow(strategy.Strategy.Id.To<string>(), strategy.SessionType == SessionType.Optimization ? typeof(OptimizatorContent) : typeof(StrategyContent));
		}
		private IStudioControl OpenControl(StrategyContainer strategy, string contentTemplate = null)
		{
			switch (strategy.SessionType)
			{
				case SessionType.Battle:
				case SessionType.Emulation:
					return OpenStrategyControl(strategy, contentTemplate);

				case SessionType.Optimization:
					return OpenOprimizationControl(strategy);

				default:
					throw new ArgumentOutOfRangeException();
			}
		}
		private IStudioControl OpenStrategyControl(StrategyContainer strategy, string contentTemplate)
		{
			return OpenControl(strategy.Strategy.Id.To<string>(), typeof(StrategyContent), strategy, () =>
			{
				var ctrl = new StrategyContent();

				ctrl.SetStrategy(strategy);
				ctrl.LoadTemplate(contentTemplate ?? GetDefaultContentTemplate(strategy.StrategyInfo.Type, strategy.SessionType), false);

				return ctrl;
			});
		}
Ejemplo n.º 12
0
        public static Guid GetStrategyId(this StrategyContainer strategyContainer)
        {
            var container = strategyContainer.Strategy as StrategyContainer;

            return(container == null ? strategyContainer.Strategy.Id : container.GetStrategyId());
        }
		private IStudioControl OpenOprimizationControl(StrategyContainer strategy)
		{
			return OpenControl(strategy.Strategy.Id.To<string>(), typeof(OptimizatorContent), strategy, () =>
			{
				var c = new OptimizatorContent { Strategy = strategy };
				c.SetStrategy(strategy);
				return c;
			});
		}
Ejemplo n.º 14
0
		private void EmulationServiceOnProgressChanged(StrategyContainer strategy, int value)
		{
			ResultsPanel.UpdateProgress(strategy.Strategy, value);
		}
Ejemplo n.º 15
0
		private void Stop(StrategyContainer strategy)
		{
			strategy
				.WhenStopped()
				.Do(() =>
				{
					var candleManager = strategy.GetCandleManager();

					if (candleManager != null)
						candleManager.Dispose();

					strategy.SafeGetConnector().Dispose();
					strategy.Connector = ConfigManager.GetService<IConnector>();
				})
				.Once()
				.Apply();

			strategy.Stop();
		}
Ejemplo n.º 16
0
		private void Start(StrategyContainer strategy, DateTime? startDate, DateTime? stopDate, TimeSpan? candlesTimeFrame, bool onlyInitialize)
		{
			if (Connector == null)
				throw new InvalidOperationException("Connector=null");

			strategy.CheckCanStart();

			var from = startDate ?? DateTime.Today.AddDays(-strategy.HistoryDaysCount);
			var to = stopDate ?? DateTime.Now;

			var strategyConnector = new StrategyConnector(strategy, from, to, candlesTimeFrame ?? TimeSpan.FromMinutes(5), onlyInitialize);

			ConfigManager.GetService<LogManager>().Sources.Add(strategyConnector);

			strategy.Connector = strategyConnector;
			strategy.SetCandleManager(CreateCandleManager(strategyConnector, TimeSpan.FromDays((strategy.HistoryDaysCount + 1) * 2)));
			strategy.SetIsEmulation(false);

			strategy.Start();
			strategyConnector.Connect();
		}
		private void StrategyAdded(StrategyContainer strategy)
		{
			OpenControl(strategy);
		}
Ejemplo n.º 18
0
		private bool CanStop(StrategyContainer strategy)
		{
			return strategy != null && strategy.ProcessState == ProcessStates.Started;
		}
Ejemplo n.º 19
0
		public EmulationService(StrategyContainer strategy)
		{
			if (strategy == null)
				throw new ArgumentNullException("strategy");

			Strategy = strategy;
			Strategies = new[] { strategy }.ToEx(1);

			var storageRegistry = new StudioStorageRegistry { MarketDataSettings = Strategy.MarketDataSettings };

			_basketEmulation = new BatchEmulation(new StudioSecurityProvider(), new Portfolio[0], storageRegistry);

			_basketEmulation.StateChanged += BasketEmulationOnStateChanged;
			_basketEmulation.ProgressChanged += (curr, total) =>
			{
				Progress = total;

				_basketEmulation
					.BatchStrategies
					.OfType<StrategyContainer>()
					.ForEach(s => ProgressChanged.SafeInvoke((StrategyContainer)s.Strategy, curr));
			};

			ConfigManager.GetService<LogManager>().Sources.Add(EmulationConnector);

			EmulationConnector.HistoryMessageAdapter.StorageRegistry = storageRegistry;

			CanStart = true;
		}
Ejemplo n.º 20
0
		private IEnumerable<Strategy> GetStrategies()
		{
			EmulationConnector.AddInfoLog(LocalizedStrings.Str3592);

			var enumerator = Strategies.GetEnumerator();

			while (enumerator.MoveNext())
			{
				var strategy = (StrategyContainer)enumerator.Current;

				strategy.CheckCanStart();

				var container = new StrategyContainer
				{
					Id = strategy.Id,
					StrategyInfo = _infoClone,
					MarketDataSettings = strategy.MarketDataSettings,
					Connector = EmulationConnector,
					//SessionType = SessionType.Optimization,
				};

				container.Environment.AddRange(strategy.Environment);

				container.SetCandleManager(CreateCandleManager());
				container.SetIsEmulation(true);
				container.SetIsInitialization(false);

				container.NameGenerator.Pattern = strategy.NameGenerator.Pattern;
				container.Portfolio = strategy.Portfolio;
				container.Security = strategy.Security;
				container.Strategy = strategy;

				container.UnrealizedPnLInterval = EmulationSettings.UnrealizedPnLInterval ?? ((EmulationSettings.StopTime - EmulationSettings.StartTime).Ticks / 1000).To<TimeSpan>();

				_infoClone.Strategies.Add(container);

				yield return container;
			}

			EmulationConnector.AddInfoLog(LocalizedStrings.Str3593);
		}
Ejemplo n.º 21
0
 public static bool IsDiagramStrategy(this StrategyContainer container)
 {
     return(container.StrategyInfo.Type == StrategyInfoTypes.Diagram);
 }
Ejemplo n.º 22
0
		private void OpenStrategy(StrategyContainer selectedStrategy)
		{
			var strategy = (StrategyContainer)selectedStrategy.Clone();

			strategy.Strategy.Id = selectedStrategy.Strategy.Id;
			strategy.Portfolio = Strategy.Portfolio;
			strategy.SessionType = SessionType.Battle;

			strategy.Reseted += () =>
			{
				var settings = EmulationService.EmulationSettings;
				new StartStrategyCommand(strategy, settings.StartTime, settings.StopTime, null, true).Process(this);
			};

			new OpenStrategyCommand(strategy, Properties.Resources.EmulationStrategyContent).Process(strategy.StrategyInfo);
		}
Ejemplo n.º 23
0
        public static Guid GetStrategyId(this StrategyContainer strategyContainer)
        {
            var container = strategyContainer.Strategy as StrategyContainer;

            return(container?.GetStrategyId() ?? strategyContainer.Strategy.Id);
        }