Камрады, замучился, пытаясь запустить оптимизатор в 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'ом пока не разобрался, к сожалению, и не могу использовать новые версии, ибо нуб. :-(
评论 (7)
登录 或 创建账户, 登录或注册以发表评论
Ну, как бы up... :-(
код не смотрел, и врятли кто будет(длинно, непонятно), но ошибка говорит об том что у вас подключение находится в состоянии Starting
а надо
Т.е. вам надо либо остановить работу программы и ждать когда станет Started. Либо подписаться на событие успешного подключения connector.Connected. И там выполнять код который выдает ошибку.
Странно то, что connector никогда не переходит в состояние Started, он вообще всё время Stopped! Я просто ради интереса поставил цикл на переход в это состояние (через ThreadHelper.Sleep). Делал connector.Start, connector.StartExport - безрезультатно. И смешно то, что Sample работает! :-(
В SampleHistoryTesting есть код, вам надо также
Иван, если несложно, можете скинуть полный код для MainWindow?
SampleTestingParallel вы же где то взяли, там и SampleHistoryTesting лежит
Спасибо, понял!