private void OnStrategyChanged(DiagramStrategy strategy)
		{
			_strategy = strategy;

			_strategy.OrderRegistering += OnStrategyOrderRegistering;
			_strategy.OrderReRegistering += OnStrategyOrderReRegistering;
			_strategy.OrderRegisterFailed += OnStrategyOrderRegisterFailed;

			_strategy.StopOrderRegistering += OnStrategyOrderRegistering;
			_strategy.StopOrderReRegistering += OnStrategyOrderReRegistering;
			_strategy.StopOrderRegisterFailed += OnStrategyOrderRegisterFailed;

			_strategy.NewMyTrades += OnStrategyNewMyTrade;

			_strategy.PositionManager.NewPosition += OnStrategyNewPosition;
			_strategy.PositionManager.Positions.ForEach(OnStrategyNewPosition);

			_strategy.PnLChanged += OnStrategyPnLChanged;
			_strategy.Reseted += OnStrategyReseted;

			_strategy.SetChart(ChartPanel);

			PropertyGrid.SelectedObject = _strategy;
			StatisticParameterGrid.StatisticManager = _strategy.StatisticManager;
		}
        private void OnStrategyPropertyChanged(DiagramStrategy strategy)
        {
            if (strategy != null)
            {
                strategy.PropertyChanged     += OnStrategyPropertyChanged;
                strategy.ProcessStateChanged += OnStrategyProcessStateChanged;

                var composition = strategy.Composition;

                Debugger        = new DiagramDebugger(composition);
                Debugger.Break += OnDebuggerBreak;
                Debugger.CompositionChanged += OnDebuggerCompositionChanged;

                NoStrategyLabel.Visibility = Visibility.Hidden;
                DiagramEditor.Composition  = composition;

                ShowElementProperties(null);
            }
            else
            {
                Debugger = null;

                NoStrategyLabel.Visibility = Visibility.Visible;
                DiagramEditor.Composition  = new CompositionDiagramElement {
                    Name = string.Empty
                };
            }

            DiagramEditor.Composition.IsModifiable = false;
        }
        private void OnStrategyChanged(DiagramStrategy strategy)
        {
            _strategy = strategy;

            _strategy.OrderRegistering    += OnStrategyOrderRegistering;
            _strategy.OrderReRegistering  += OnStrategyOrderReRegistering;
            _strategy.OrderRegisterFailed += OnStrategyOrderRegisterFailed;

            _strategy.StopOrderRegistering    += OnStrategyOrderRegistering;
            _strategy.StopOrderReRegistering  += OnStrategyOrderReRegistering;
            _strategy.StopOrderRegisterFailed += OnStrategyOrderRegisterFailed;

            _strategy.NewMyTrades += OnStrategyNewMyTrade;

            _strategy.PositionManager.NewPosition += OnStrategyNewPosition;
            _strategy.PositionManager.Positions.ForEach(OnStrategyNewPosition);

            _strategy.PnLChanged += OnStrategyPnLChanged;
            _strategy.Reseted    += OnStrategyReseted;

            _strategy.SetChart(ChartPanel);

            PropertyGrid.SelectedObject             = _strategy;
            StatisticParameterGrid.StatisticManager = _strategy.StatisticManager;
        }
        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();
            }
        }
Beispiel #5
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();
            }
        }
Beispiel #6
0
        private void OpenLive(CompositionItem item)
        {
            var strategy = new DiagramStrategy
            {
                Composition = _strategiesRegistry.Clone(item.Element)
            };

            var content = new LiveStrategyControl
            {
                Strategy = strategy
            };

            _layoutManager.OpenDocumentWindow(content);
        }
Beispiel #7
0
        public override void Load(SettingsStorage storage)
        {
            var compositionId = storage.GetValue <Guid>("CompositionId");
            var registry      = ConfigManager.GetService <StrategiesRegistry>();
            var composition   = (CompositionDiagramElement)registry.Strategies.FirstOrDefault(c => c.TypeId == compositionId);

            Strategy = new DiagramStrategy
            {
                Id          = storage.GetValue <Guid>("StrategyId"),
                Composition = registry.Clone(composition)
            };

            base.Load(storage);
        }
        private void OnStrategyChanged(DiagramStrategy oldStrategy, DiagramStrategy newStrategy)
        {
            if (oldStrategy != null)
            {
                StatisticsGrid.StatisticManager = null;

                ConfigManager
                .GetService <LogManager>()
                .Sources
                .Remove(oldStrategy);

                oldStrategy.Composition = null;

                oldStrategy.ParametersChanged -= RaiseChanged;

                oldStrategy.OrderRegistering    += OnStrategyOrderRegistering;
                oldStrategy.OrderReRegistering  += OnStrategyOrderReRegistering;
                oldStrategy.OrderRegisterFailed += OnStrategyOrderRegisterFailed;

                oldStrategy.StopOrderRegistering    += OnStrategyOrderRegistering;
                oldStrategy.StopOrderReRegistering  += OnStrategyOrderReRegistering;
                oldStrategy.StopOrderRegisterFailed += OnStrategyOrderRegisterFailed;

                oldStrategy.NewMyTrades += OnStrategyNewMyTrade;
            }

            DiagramDebuggerControl.Strategy = newStrategy;

            if (newStrategy == null)
            {
                return;
            }

            StatisticsGrid.StatisticManager = newStrategy.StatisticManager;

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

            newStrategy.ParametersChanged += RaiseChanged;

            newStrategy.OrderRegistering    += OnStrategyOrderRegistering;
            newStrategy.OrderReRegistering  += OnStrategyOrderReRegistering;
            newStrategy.OrderRegisterFailed += OnStrategyOrderRegisterFailed;

            newStrategy.StopOrderRegistering    += OnStrategyOrderRegistering;
            newStrategy.StopOrderReRegistering  += OnStrategyOrderReRegistering;
            newStrategy.StopOrderRegisterFailed += OnStrategyOrderRegisterFailed;

            newStrategy.NewMyTrades += OnStrategyNewMyTrade;

            newStrategy.PnLChanged += () =>
            {
                var pnl = new EquityData
                {
                    Time  = newStrategy.CurrentTime,
                    Value = newStrategy.PnL - newStrategy.Commission ?? 0
                };

                var unrealizedPnL = new EquityData
                {
                    Time  = newStrategy.CurrentTime,
                    Value = newStrategy.PnLManager.UnrealizedPnL
                };

                var commission = new EquityData
                {
                    Time  = newStrategy.CurrentTime,
                    Value = newStrategy.Commission ?? 0
                };

                _pnlCurve.Add(pnl);
                _unrealizedPnLCurve.Add(unrealizedPnL);
                _commissionCurve.Add(commission);
            };

            newStrategy.PositionChanged += () => _posItems.Add(new EquityData
            {
                Time  = newStrategy.CurrentTime,
                Value = newStrategy.Position
            });

            newStrategy.SetChart(_bufferedChart);
        }
		public override void Load(SettingsStorage storage)
		{
			var compositionId = storage.GetValue<Guid>("CompositionId");
			var registry = ConfigManager.GetService<StrategiesRegistry>();
			var composition = (CompositionDiagramElement)registry.Strategies.FirstOrDefault(c => c.TypeId == compositionId);

			Strategy = new DiagramStrategy
			{
				Id = storage.GetValue<Guid>("StrategyId"),
				Composition = registry.Clone(composition)
			};

			base.Load(storage);
		}
		private void OnStrategyChanged(DiagramStrategy oldStrategy, DiagramStrategy newStrategy)
		{
			if (oldStrategy != null)
			{
				ConfigManager
					.GetService<LogManager>()
					.Sources
					.Remove(oldStrategy);

				oldStrategy.ParametersChanged -= RaiseChanged;

				oldStrategy.OrderRegistering += OnStrategyOrderRegistering;
				oldStrategy.OrderReRegistering += OnStrategyOrderReRegistering;
				oldStrategy.OrderRegisterFailed += OnStrategyOrderRegisterFailed;

				oldStrategy.StopOrderRegistering += OnStrategyOrderRegistering;
				oldStrategy.StopOrderReRegistering += OnStrategyOrderReRegistering;
				oldStrategy.StopOrderRegisterFailed += OnStrategyOrderRegisterFailed;

				oldStrategy.NewMyTrades += OnStrategyNewMyTrade;
			}

			DiagramDebuggerControl.Strategy = newStrategy;

			if (newStrategy == null)
				return;

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

			newStrategy.ParametersChanged += RaiseChanged;

			newStrategy.OrderRegistering += OnStrategyOrderRegistering;
			newStrategy.OrderReRegistering += OnStrategyOrderReRegistering;
			newStrategy.OrderRegisterFailed += OnStrategyOrderRegisterFailed;

			newStrategy.StopOrderRegistering += OnStrategyOrderRegistering;
			newStrategy.StopOrderReRegistering += OnStrategyOrderReRegistering;
			newStrategy.StopOrderRegisterFailed += OnStrategyOrderRegisterFailed;

			newStrategy.NewMyTrades += OnStrategyNewMyTrade;

			newStrategy.PnLChanged += () =>
			{
				var pnl = new EquityData
				{
					Time = newStrategy.CurrentTime,
					Value = newStrategy.PnL - newStrategy.Commission ?? 0
				};

				var unrealizedPnL = new EquityData
				{
					Time = newStrategy.CurrentTime,
					Value = newStrategy.PnLManager.UnrealizedPnL
				};

				var commission = new EquityData
				{
					Time = newStrategy.CurrentTime,
					Value = newStrategy.Commission ?? 0
				};

				_pnlCurve.Add(pnl);
				_unrealizedPnLCurve.Add(unrealizedPnL);
				_commissionCurve.Add(commission);
			};

			newStrategy.PositionChanged += () => _posItems.Add(new EquityData
			{
				Time = newStrategy.CurrentTime,
				Value = newStrategy.Position
			});

			newStrategy.SetChart(_bufferedChart);
		}
		private void OnStrategyPropertyChanged(DiagramStrategy strategy)
		{
			if (strategy != null)
			{
				strategy.PropertyChanged += OnStrategyPropertyChanged;
				strategy.ProcessStateChanged += OnStrategyProcessStateChanged;

				var composition = strategy.Composition;

				Debugger = new DiagramDebugger(composition);
				Debugger.Break += OnDebuggerBreak;
				Debugger.CompositionChanged += OnDebuggerCompositionChanged;

				NoStrategyLabel.Visibility = Visibility.Hidden;
				DiagramEditor.Composition = composition;

				ShowElementProperties(null);
			}
			else
			{
				Debugger = null;

				NoStrategyLabel.Visibility = Visibility.Visible;
				DiagramEditor.Composition = new CompositionDiagramElement { Name = string.Empty };
			}

			DiagramEditor.Composition.IsModifiable = false;
		}
		private void OpenLive(CompositionItem item)
		{
			var strategy = new DiagramStrategy
			{
				Composition = _strategiesRegistry.Clone(item.Element)
			};

			var content = new LiveStrategyControl
			{
				Strategy = strategy
			};

			_layoutManager.OpenDocumentWindow(content);
		}
Beispiel #13
0
        private void StartButtonOnClick(object sender, RoutedEventArgs e)
        {
            _logManager.Sources.Clear();
            _bufferedChart.ClearAreas();

            Curve.Clear();
            PositionCurve.Clear();

            if (HistoryPathTextBox.Text.IsEmpty() || !Directory.Exists(HistoryPathTextBox.Text))
            {
                MessageBox.Show("Wrong path.");
                return;
            }

            if (_connector != null && _connector.State != EmulationStates.Stopped)
            {
                MessageBox.Show("Already launched.");
                return;
            }

            if (Composition == null)
            {
                MessageBox.Show("No strategy selected.");
                return;
            }

            var secGen     = new SecurityIdGenerator();
            var secIdParts = secGen.Split(SecusityTextBox.Text);
            var secCode    = secIdParts.SecurityCode;
            var board      = ExchangeBoard.GetOrCreateBoard(secIdParts.BoardCode);
            var timeFrame  = (TimeSpan)TimeFrameComboBox.SelectedItem;
            var useCandles = (string)MarketDataTypeComboBox.SelectedItem != "Ticks";

            // create test security
            var security = new Security
            {
                Id    = SecusityTextBox.Text,              // sec id has the same name as folder with historical data
                Code  = secCode,
                Board = board,
            };

            // storage to historical data
            var storageRegistry = new StorageRegistry
            {
                // set historical path
                DefaultDrive = new LocalMarketDataDrive(HistoryPathTextBox.Text)
            };

            var startTime = ((DateTime)FromDatePicker.Value).ChangeKind(DateTimeKind.Utc);
            var stopTime  = ((DateTime)ToDatePicke.Value).ChangeKind(DateTimeKind.Utc);

            // ProgressBar refresh step
            var progressStep = ((stopTime - startTime).Ticks / 100).To <TimeSpan>();

            // set ProgressBar bounds
            TicksAndDepthsProgress.Value   = 0;
            TicksAndDepthsProgress.Maximum = 100;

            var level1Info = new Level1ChangeMessage
            {
                SecurityId = security.ToSecurityId(),
                ServerTime = startTime,
            }
            .TryAdd(Level1Fields.PriceStep, secIdParts.SecurityCode == "RIZ2" ? 10m : 1)
            .TryAdd(Level1Fields.StepPrice, 6m)
            .TryAdd(Level1Fields.MinPrice, 10m)
            .TryAdd(Level1Fields.MaxPrice, 1000000m)
            .TryAdd(Level1Fields.MarginBuy, 10000m)
            .TryAdd(Level1Fields.MarginSell, 10000m);

            // test portfolio
            var portfolio = new Portfolio
            {
                Name       = "test account",
                BeginValue = 1000000,
            };

            // create backtesting connector
            _connector = new HistoryEmulationConnector(
                new[] { security },
                new[] { portfolio })
            {
                EmulationAdapter =
                {
                    Emulator             =
                    {
                        Settings         =
                        {
                            // match order if historical price touched our limit order price.
                            // It is terned off, and price should go through limit order price level
                            // (more "severe" test mode)
                            MatchOnTouch = false,
                        }
                    }
                },

                UseExternalCandleSource = useCandles,

                HistoryMessageAdapter =
                {
                    StorageRegistry = storageRegistry,

                    // set history range
                    StartDate = startTime,
                    StopDate  = stopTime,
                },

                // set market time freq as time frame
                MarketTimeChangedInterval = timeFrame,
            };

            //((ILogSource)_connector).LogLevel = DebugLogCheckBox.IsChecked == true ? LogLevels.Debug : LogLevels.Info;

            _logManager.Sources.Add(_connector);

            var candleManager = !useCandles
                                        ? new CandleManager(new TradeCandleBuilderSourceEx(_connector))
                                        : new CandleManager(_connector);

            // create strategy based on 80 5-min и 10 5-min
            var strategy = new DiagramStrategy
            {
                Volume    = 1,
                Portfolio = portfolio,
                Security  = security,
                Connector = _connector,
                //LogLevel = DebugLogCheckBox.IsChecked == true ? LogLevels.Debug : LogLevels.Info,

                Composition = Composition,

                // by default interval is 1 min,
                // it is excessively for time range with several months
                UnrealizedPnLInterval = ((stopTime - startTime).Ticks / 1000).To <TimeSpan>()
            };

            strategy.SetChart(_bufferedChart);
            strategy.SetCandleManager(candleManager);

            _logManager.Sources.Add(strategy);

            strategy.OrderRegistering    += OnStrategyOrderRegistering;
            strategy.OrderReRegistering  += OnStrategyOrderReRegistering;
            strategy.OrderRegisterFailed += OnStrategyOrderRegisterFailed;

            strategy.StopOrderRegistering    += OnStrategyOrderRegistering;
            strategy.StopOrderReRegistering  += OnStrategyOrderReRegistering;
            strategy.StopOrderRegisterFailed += OnStrategyOrderRegisterFailed;

            strategy.NewMyTrades += OnStrategyNewMyTrade;

            var pnlCurve           = Curve.CreateCurve(LocalizedStrings.PnL + " " + strategy.Name, Colors.DarkGreen, EquityCurveChartStyles.Area);
            var unrealizedPnLCurve = Curve.CreateCurve(LocalizedStrings.PnLUnreal + strategy.Name, Colors.Black);
            var commissionCurve    = Curve.CreateCurve(LocalizedStrings.Str159 + " " + strategy.Name, Colors.Red, EquityCurveChartStyles.DashedLine);

            strategy.PnLChanged += () =>
            {
                var pnl = new EquityData
                {
                    Time  = strategy.CurrentTime,
                    Value = strategy.PnL - strategy.Commission ?? 0
                };

                var unrealizedPnL = new EquityData
                {
                    Time  = strategy.CurrentTime,
                    Value = strategy.PnLManager.UnrealizedPnL
                };

                var commission = new EquityData
                {
                    Time  = strategy.CurrentTime,
                    Value = strategy.Commission ?? 0
                };

                pnlCurve.Add(pnl);
                unrealizedPnLCurve.Add(unrealizedPnL);
                commissionCurve.Add(commission);
            };

            var posItems = PositionCurve.CreateCurve(strategy.Name, Colors.DarkGreen);

            strategy.PositionChanged += () => posItems.Add(new EquityData {
                Time = strategy.CurrentTime, Value = strategy.Position
            });

            _connector.NewSecurities += securities =>
            {
                if (securities.All(s => s != security))
                {
                    return;
                }

                // fill level1 values
                _connector.SendInMessage(level1Info);

                //_connector.RegisterMarketDepth(security);
                if (!useCandles)
                {
                    _connector.RegisterTrades(security);
                }

                // start strategy before emulation started
                strategy.Start();

                // start historical data loading when connection established successfully and all data subscribed
                _connector.Start();
            };

            var nextTime = startTime + progressStep;

            // handle historical time for update ProgressBar
            _connector.MarketTimeChanged += d =>
            {
                if (_connector.CurrentTime < nextTime && _connector.CurrentTime < stopTime)
                {
                    return;
                }

                var steps = (_connector.CurrentTime - startTime).Ticks / progressStep.Ticks + 1;
                nextTime = startTime + (steps * progressStep.Ticks).To <TimeSpan>();
                this.GuiAsync(() => TicksAndDepthsProgress.Value = steps);
            };

            _connector.StateChanged += () =>
            {
                switch (_connector.State)
                {
                case EmulationStates.Stopped:
                    strategy.Stop();
                    SetIsEnabled(false);

                    this.GuiAsync(() =>
                    {
                        if (_connector.IsFinished)
                        {
                            TicksAndDepthsProgress.Value = TicksAndDepthsProgress.Maximum;
                            MessageBox.Show("Done.");
                        }
                        else
                        {
                            MessageBox.Show("Cancelled.");
                        }
                    });
                    break;

                case EmulationStates.Started:
                    SetIsEnabled(true);
                    break;
                }
            };

            TicksAndDepthsProgress.Value = 0;

            // raise NewSecurities and NewPortfolio for full fill strategy properties
            _connector.Connect();

            // 1 cent commission for trade
            _connector.SendInMessage(new CommissionRuleMessage
            {
                Rule = new CommissionPerTradeRule {
                    Value = 0.01m
                }
            });
        }
		private void StartButtonOnClick(object sender, RoutedEventArgs e)
		{
			_logManager.Sources.Clear();
			_bufferedChart.ClearAreas();

			Curve.Clear();
			PositionCurve.Clear();

			if (HistoryPathTextBox.Text.IsEmpty() || !Directory.Exists(HistoryPathTextBox.Text))
			{
				MessageBox.Show("Wrong path.");
				return;
			}

			if (_connector != null && _connector.State != EmulationStates.Stopped)
			{
				MessageBox.Show("Already launched.");
				return;
			}

			if (Composition == null)
			{
				MessageBox.Show("No strategy selected.");
				return;
			}

			var secGen = new SecurityIdGenerator();
			var secIdParts = secGen.Split(SecusityTextBox.Text);
			var secCode = secIdParts.SecurityCode;
			var board = ExchangeBoard.GetOrCreateBoard(secIdParts.BoardCode);
			var timeFrame = (TimeSpan)TimeFrameComboBox.SelectedItem;
			var useCandles = (string)MarketDataTypeComboBox.SelectedItem != "Ticks";

			// create test security
			var security = new Security
			{
				Id = SecusityTextBox.Text, // sec id has the same name as folder with historical data
				Code = secCode,
				Board = board,
			};

			// storage to historical data
			var storageRegistry = new StorageRegistry
			{
				// set historical path
				DefaultDrive = new LocalMarketDataDrive(HistoryPathTextBox.Text)
			};

			var startTime = ((DateTime)FromDatePicker.Value).ChangeKind(DateTimeKind.Utc);
			var stopTime = ((DateTime)ToDatePicke.Value).ChangeKind(DateTimeKind.Utc);

			// ProgressBar refresh step
			var progressStep = ((stopTime - startTime).Ticks / 100).To<TimeSpan>();

			// set ProgressBar bounds
			TicksAndDepthsProgress.Value = 0;
			TicksAndDepthsProgress.Maximum = 100;

			var level1Info = new Level1ChangeMessage
			{
				SecurityId = security.ToSecurityId(),
				ServerTime = startTime,
			}
			.TryAdd(Level1Fields.PriceStep, secIdParts.SecurityCode == "RIZ2" ? 10m : 1)
			.TryAdd(Level1Fields.StepPrice, 6m)
			.TryAdd(Level1Fields.MinPrice, 10m)
			.TryAdd(Level1Fields.MaxPrice, 1000000m)
			.TryAdd(Level1Fields.MarginBuy, 10000m)
			.TryAdd(Level1Fields.MarginSell, 10000m);

			// test portfolio
			var portfolio = new Portfolio
			{
				Name = "test account",
				BeginValue = 1000000,
			};

			// create backtesting connector
			_connector = new HistoryEmulationConnector(
				new[] { security },
				new[] { portfolio })
			{
				EmulationAdapter =
				{
					Emulator =
					{
						Settings =
						{
							// match order if historical price touched our limit order price. 
							// It is terned off, and price should go through limit order price level
							// (more "severe" test mode)
							MatchOnTouch = false,
						}
					}
				},

				UseExternalCandleSource = useCandles,

				HistoryMessageAdapter =
				{
					StorageRegistry = storageRegistry,

					// set history range
					StartDate = startTime,
					StopDate = stopTime,
				},

				// set market time freq as time frame
				MarketTimeChangedInterval = timeFrame,
			};

			//((ILogSource)_connector).LogLevel = DebugLogCheckBox.IsChecked == true ? LogLevels.Debug : LogLevels.Info;

			_logManager.Sources.Add(_connector);

			var candleManager = !useCandles
					? new CandleManager(new TradeCandleBuilderSourceEx(_connector))
					: new CandleManager(_connector);

			// create strategy based on 80 5-min и 10 5-min
			var strategy = new DiagramStrategy
			{
				Volume = 1,
				Portfolio = portfolio,
				Security = security,
				Connector = _connector,
				//LogLevel = DebugLogCheckBox.IsChecked == true ? LogLevels.Debug : LogLevels.Info,

				Composition = Composition,

				// by default interval is 1 min,
				// it is excessively for time range with several months
				UnrealizedPnLInterval = ((stopTime - startTime).Ticks / 1000).To<TimeSpan>()
			};

			strategy.SetChart(_bufferedChart);
			strategy.SetCandleManager(candleManager);

			_logManager.Sources.Add(strategy);

			strategy.OrderRegistering += OnStrategyOrderRegistering;
			strategy.OrderReRegistering += OnStrategyOrderReRegistering;
			strategy.OrderRegisterFailed += OnStrategyOrderRegisterFailed;
			
			strategy.StopOrderRegistering += OnStrategyOrderRegistering;
			strategy.StopOrderReRegistering += OnStrategyOrderReRegistering;
			strategy.StopOrderRegisterFailed += OnStrategyOrderRegisterFailed;

			strategy.NewMyTrades += OnStrategyNewMyTrade;

			var pnlCurve = Curve.CreateCurve(LocalizedStrings.PnL + " " + strategy.Name, Colors.DarkGreen, EquityCurveChartStyles.Area);
			var unrealizedPnLCurve = Curve.CreateCurve(LocalizedStrings.PnLUnreal + strategy.Name, Colors.Black);
			var commissionCurve = Curve.CreateCurve(LocalizedStrings.Str159 + " " + strategy.Name, Colors.Red, EquityCurveChartStyles.DashedLine);
			
			strategy.PnLChanged += () =>
			{
				var pnl = new EquityData
				{
					Time = strategy.CurrentTime,
					Value = strategy.PnL - strategy.Commission ?? 0
				};

				var unrealizedPnL = new EquityData
				{
					Time = strategy.CurrentTime,
					Value = strategy.PnLManager.UnrealizedPnL
				};

				var commission = new EquityData
				{
					Time = strategy.CurrentTime,
					Value = strategy.Commission ?? 0
				};

				pnlCurve.Add(pnl);
				unrealizedPnLCurve.Add(unrealizedPnL);
				commissionCurve.Add(commission);
			};

			var posItems = PositionCurve.CreateCurve(strategy.Name, Colors.DarkGreen);

			strategy.PositionChanged += () => posItems.Add(new EquityData { Time = strategy.CurrentTime, Value = strategy.Position });

			_connector.NewSecurities += securities =>
			{
				if (securities.All(s => s != security))
					return;

				// fill level1 values
				_connector.SendInMessage(level1Info);

				//_connector.RegisterMarketDepth(security);
				if (!useCandles)
					_connector.RegisterTrades(security);

				// start strategy before emulation started
				strategy.Start();

				// start historical data loading when connection established successfully and all data subscribed
				_connector.Start();
			};

			var nextTime = startTime + progressStep;

			// handle historical time for update ProgressBar
			_connector.MarketTimeChanged += d =>
			{
				if (_connector.CurrentTime < nextTime && _connector.CurrentTime < stopTime)
					return;

				var steps = (_connector.CurrentTime - startTime).Ticks / progressStep.Ticks + 1;
				nextTime = startTime + (steps * progressStep.Ticks).To<TimeSpan>();
				this.GuiAsync(() => TicksAndDepthsProgress.Value = steps);
			};

			_connector.StateChanged += () =>
			{
				switch (_connector.State)
				{
					case EmulationStates.Stopped:
						strategy.Stop();
						SetIsEnabled(false);

						this.GuiAsync(() =>
						{
							if (_connector.IsFinished)
							{
								TicksAndDepthsProgress.Value = TicksAndDepthsProgress.Maximum;
								MessageBox.Show("Done.");
							}
							else
								MessageBox.Show("Cancelled.");
						});
						break;
					case EmulationStates.Started:
						SetIsEnabled(true);
						break;
				}
			};

			TicksAndDepthsProgress.Value = 0;

			// raise NewSecurities and NewPortfolio for full fill strategy properties
			_connector.Connect();

			// 1 cent commission for trade
			_connector.SendInMessage(new CommissionRuleMessage
			{
				Rule = new CommissionPerTradeRule { Value = 0.01m }
			});
		}