BatchEmulator, проблема с тестированием в версии 4.2.43


BatchEmulator, проблема с тестированием в версии 4.2.43
Atom
23.02.2015


Камрады, замучился, пытаясь запустить оптимизатор в 4.2.43.

Брал за основу SampleTestingParallel - фактически только переписал блок

Код

			var strategies = periods
				.Select(period =>
				{
					var series = new CandleSeries(typeof(TimeFrameCandle), security, timeFrame);

					// создаем торговую стратегию
					var strategy = new SmaStrategy(series, new SimpleMovingAverage { Length = period.Item1 }, new SimpleMovingAverage { Length = period.Item2 })
					{
						Volume = 1,
						Security = security,
						Portfolio = portfolio,
						Connector = connector,

						// по-умолчанию интервал равен 1 минут,
						// что для истории в диапазон от нескольких месяцев излишне
						UnrealizedPnLInterval = ((stopTime - startTime).Ticks / 1000).To<TimeSpan>()
					};

					strategy.SetCandleManager(new CandleManager(connector));

					var curveItems = Curve.CreateCurve(LocalizedStrings.Str3026Params.Put(period.Item1, period.Item2), period.Item3);
					strategy.PnLChanged += () =>
					{
						var data = new EquityData
						{
							Time = strategy.CurrentTime,
							Value = strategy.PnL,
						};

						this.GuiAsync(() => curveItems.Add(data));
					};

					Stat.AddStrategies(new[] { strategy });

					return strategy;
				})
				.ToEx(periods.Length);


Переделал в такое:

Код

            double tradeQuantilesStartVal = 0.7;
            long maxMonteCarloIterations = 10000;
            List<Tuple<double, double>> quantileParams = new List<Tuple<double,double>>();

            var generator = new AForge.Math.Random.UniformOneGenerator((int)DateTime.Now.TimeOfDay.TotalSeconds);

            for (int i = 0; i < maxMonteCarloIterations; i++)
            {
                var tradeQuantile = tradeQuantilesStartVal + (1 - tradeQuantilesStartVal)*generator.Next();
                var stoplossQuantile = tradeQuantile + (1 - tradeQuantile) * generator.Next();

                quantileParams.Add(new Tuple<double, double>(tradeQuantile, stoplossQuantile));
            }

            for (int j = 0; j < maxMonteCarloIterations; j++)
            {
                var strategies = new List<Strategy>();
                var series = new CandleSeries(typeof(RangeCandle), security, new Unit(candleSize));


                for (int i = 0; i < maxParallelStrategiesCount; i++)
                {
                    var strategy = new StockBotStrategy(series, new StrategyParameters()
                                                                    {
                                                                        candleSize = 100.0,
                                                                        port = 60000 + i,
                                                                        tradeQuantile = (decimal)quantileParams[j].Item1,
                                                                        stoplossQuantile = (decimal)quantileParams[j].Item2,
                                                                        period = period,
                                                                    })
                                   {
                                       Volume = 1,
                                       Security = security,
                                       Portfolio = portfolio,
                                       Connector = connector,
                                       UnrealizedPnLInterval = ((stopTime - startTime).Ticks / 1000).To<TimeSpan>(),
                                   };

                    strategy.SetCandleManager(new CandleManager(connector));

                    var curveItems = Curve.CreateCurve("", Colors.Black);
                    strategy.PnLChanged += () =>
                    {
                        var data = new EquityData
                        {
                            Time = strategy.CurrentTime,
                            Value = strategy.PnL,
                        };

                        this.GuiAsync(() => curveItems.Add(data));
                    };

                    strategies.Add(strategy);

                    Stat.AddStrategies(new[] { strategy });
                }

                batchEmulation.Start(strategies.ToEx(maxParallelStrategiesCount));


Постоянно получаю ошибку: System.InvalidOperationException не обработано пользовательским кодом
HResult=-2146233079
Message=Нельзя запустить тестирование так как подключение находится в состоянии Starting.
Source=StockSharp.Algo
StackTrace:
в StockSharp.Algo.Testing.HistoryEmulationConnector.Start(DateTime startDate, DateTime stopDate)
в StockSharp.Algo.Strategies.Testing.BatchEmulation.#=qEvP$WOQt9MPu7qFVhUGtqCEHIIWDnjoXf09QUZzlYDA=()
в StockSharp.Algo.Strategies.Testing.BatchEmulation.Start(IEnumerableEx`1 strategies)
в Optimizer.MainWindow.StartBtnClick(Object sender, RoutedEventArgs e) в d:\StockSharp\Optimizer\Optimizer 1.0\MainWindow.xaml.cs:строка 249
в System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)
в System.Windows.UIElement.RaiseEventImpl(DependencyObject sender, RoutedEventArgs args)
в System.Windows.Controls.Button.OnClick()
в System.Windows.Controls.Primitives.ButtonBase.OnMouseLeftButtonUp(MouseButtonEventArgs e)
в System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object target)
в System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)
в System.Windows.UIElement.ReRaiseEventAs(DependencyObject sender, RoutedEventArgs args, RoutedEvent newEvent)
в System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object target)
в System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)
в System.Windows.UIElement.RaiseEventImpl(DependencyObject sender, RoutedEventArgs args)
в System.Windows.UIElement.RaiseTrustedEvent(RoutedEventArgs args)
в System.Windows.Input.InputManager.ProcessStagingArea()
в System.Windows.Input.InputProviderSite.ReportInput(InputReport inputReport)
в System.Windows.Interop.HwndMouseInputProvider.ReportInput(IntPtr hwnd, InputMode mode, Int32 timestamp, RawMouseActions actions, Int32 x, Int32 y, Int32 wheel)
в System.Windows.Interop.HwndMouseInputProvider.FilterMessage(IntPtr hwnd, WindowMessage msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
в System.Windows.Interop.HwndSource.InputFilterMessage(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
в MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
в MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)
в System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
в MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(Object source, Delegate method, Object args, Int32 numArgs, Delegate catchHandler)
InnerException:


В чём может быть проблема?

P.S. GitHub'ом пока не разобрался, к сожалению, и не могу использовать новые версии, ибо нуб. :-(

Теги:


Спасибо:


Rebelion

Фотография
Дата: 24.02.2015
Ответить


Ну, как бы up... :-(
Спасибо:

Иван З.

Фотография
Дата: 24.02.2015
Ответить


код не смотрел, и врятли кто будет(длинно, непонятно), но ошибка говорит об том что у вас подключение находится в состоянии Starting
Код
connector.State == EmulationStates.Starting

а надо
Код
connector.State == EmulationStates.Started

Т.е. вам надо либо остановить работу программы и ждать когда станет Started. Либо подписаться на событие успешного подключения connector.Connected. И там выполнять код который выдает ошибку.

Спасибо:

Rebelion

Фотография
Дата: 24.02.2015
Ответить


Странно то, что connector никогда не переходит в состояние Started, он вообще всё время Stopped! Я просто ради интереса поставил цикл на переход в это состояние (через ThreadHelper.Sleep). Делал connector.Start, connector.StartExport - безрезультатно. И смешно то, что Sample работает! :-(
Спасибо:

Иван З.

Фотография
Дата: 24.02.2015
Ответить


В SampleHistoryTesting есть код, вам надо также
Код
				connector.StateChanged += () =>
				{
					if (connector. State == EmulationStates.Stopped)
					{
						candleManager.Stop(series);
						strategy.Stop();

						logManager.Dispose();
						_connectors.Clear();

						SetIsEnabled(false);

						this.GuiAsync(() =>
						{
							if (connector.IsFinished)
							{
								progressBar.Value = progressBar.Maximum;
								MessageBox.Show(LocalizedStrings.Str3024 + (DateTime.Now - _startEmulationTime));
							}
							else
								MessageBox.Show(LocalizedStrings.cancelled);
						});
					}
					else if (connector.State == EmulationStates.Started)
					{
						SetIsEnabled(true);

						// запускаем стратегию когда эмулятор запустился
						strategy.Start();
						candleManager.Start(series);
					}
				};
Спасибо:

Rebelion

Фотография
Дата: 24.02.2015
Ответить


Иван, если несложно, можете скинуть полный код для MainWindow?
Спасибо:

Иван З.

Фотография
Дата: 24.02.2015
Ответить


SampleTestingParallel вы же где то взяли, там и SampleHistoryTesting лежит
Спасибо:

Rebelion

Фотография
Дата: 24.02.2015
Ответить


Спасибо, понял!
Спасибо:


Добавить файлы через драг-н-дроп, , или вставить из буфера обмена.

loading
clippy