← Zurück

Ошибка System.NullReferenceException при остановке стратегии по событию EmulationTrader.StateChanged

В приведенном ниже коде после вызова в строке 69 метода _strategy.Stop() (вызывается по событию emulationTrader.StateChanged и emulationTrader.State == EmulationStates.Stopped) возникает исключение:

System.NullReferenceException: "Ссылка на объект не указывает на экземпляр объекта." в StockSharp.Algo.Strategies.StrategyRule1.#=qF$yf77tmtH$TvNML53EvZg==() в StockSharp.Algo.Strategies.StrategyRule1.#=qVglstR9JVctzN17DnJAaPfHj9iNnwhfXbPC1$b$3qw3SLh7n4Hpmv5nShgBwlzYEcwNHS_D3gh9j5MHWQBLReA==() в StockSharp.Algo.Strategies.Strategy.TryRemoveRule(IStrategyRule rule) в StockSharp.Algo.Strategies.Strategy.#=qX6B$QsicmbQ_icD7jMLo1roy1zPAXEXpc6ha7KohGhE=(ProcessStates #=qfQBdUVWCnfk7Bnhkdda8Ow==) в StockSharp.Algo.Strategies.Strategy.Stop() в TradeStrategy.MainWindow.StopTestingStartegy() в C:\Trade\TradeStrategy\TradeStrategy\MainWindow.xaml.cs:строка 344 в TradeStrategy.MainWindow.<StartTestingStartegy>b__1c() в C:\Trade\TradeStrategy\TradeStrategy\MainWindow.xaml.cs:строка 319 в 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) в System.Windows.Threading.Dispatcher.WrappedInvoke(Delegate callback, Object args, Int32 numArgs, Delegate catchHandler) в System.Windows.Threading.DispatcherOperation.InvokeImpl() в System.Threading.ExecutionContext.runTryCode(Object userData) в System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData) в System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx) в System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state) в System.Windows.Threading.DispatcherOperation.Invoke() в System.Windows.Threading.Dispatcher.ProcessQueue() в System.Windows.Threading.Dispatcher.WndProcHook(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) в System.Windows.Threading.Dispatcher.WrappedInvoke(Delegate callback, Object args, Int32 numArgs, Delegate catchHandler) в System.Windows.Threading.Dispatcher.InvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Int32 numArgs) в MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam) в MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg) в System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame) в System.Windows.Application.RunInternal(Window window) в System.Windows.Application.Run() в TradeStrategy.App.Main() в C:\Trade\TradeStrategy\TradeStrategy\obj\x86\Debug\App.g.cs:строка 0 в System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args) в Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly() в System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx) в System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state) в System.Threading.ThreadHelper.ThreadStart()


    public void StartTestingStartegy() {
      var security = new Security {
        Id = "RIM2@RTS", // по идентификатору инструмента будет искаться папка с историческими маркет данными
        Code = "RIM2",
        Name = "RTS-6.12",
        MinStepSize = 5,
        MinStepPrice = 2,
        Exchange = Exchange.Test,
      };

      var portfolio = new Portfolio { Name = "test account", BeginAmount = 30000m };

      var storageRegistry = new StorageRegistry(new InMemoryStorage()) {
        BasePath = "C:\\Trade\\Hydra\\"
      };

      // Устанавливаем значение таймфрейма
      var timeFrame = TimeSpan.FromSeconds(int.Parse(editTimeFrame.Text));

      emulationTrader = new EmulationTrader(new[] { security }, new[] { portfolio }) {
        MarketTimeChangedInterval = timeFrame,
        StorageRegistry = storageRegistry,
        WorkingTime = Exchange.Rts.WorkingTime,
        UseMarketDepth = false,
      };

      emulationTrader.DepthGenerators[security] = new TrendMarketDepthGenerator(security) {
        // стакан для инструмента в истории обновляется 1 раз в секунду
        Interval = TimeSpan.FromMilliseconds(1000),
        MaxSpreadStepCount = 2        
      };
      
      _candleManager = new CandleManager(emulationTrader);
      var candleSeries = new CandleSeries(typeof(TimeFrameCandle), security, timeFrame);
      _candleManager.Start(candleSeries);

      _strategy = new TresureStrategy(candleSeries, timeFrame) {
        Trader = emulationTrader,
        Portfolio = portfolio,
        // Задаем интсрумент по которому должна работать стратегия
        Security = security,
      };

      _logManager.Sources.Add(_strategy);
      _logManager.Sources.Add(emulationTrader);

      emulationTrader.StateChanged += () => {
        if (emulationTrader.State == EmulationStates.Stopped) {
          this.GuiAsync(() => {
            LoggingHelper.AddInfoLog(emulationTrader, "Testing is completed");
            StopTestingStartegy();            
          });
        } else if (emulationTrader.State == EmulationStates.Started) {
          // запускаем стратегию когда эмулятор запустился
          _strategy.Start();
          _isTestStrategyStarted = true;
          btnTest.Content = "Stop strategy";
        }
      };
      emulationTrader.Connect();
      emulationTrader.StartExport();
,
      var startTime = new DateTime(2012, 4, 20);
      var stopTime = new DateTime(2012, 4, 21);
      emulationTrader.Start(startTime, stopTime);
    }
 
    public void StopTestingStartegy() {
      _strategy.Stop();      
      _isTestStrategyStarted = true;
      btnTest.Content = "Start strategy";
    }

До возникновения исключения переопределенная часть метода стратегии OnStopping() выполняется успешно, но OnStopped() не успевает вызыватся. После возникновения ошибки, если нажать в отладчике F5 (продолжить), успешно отрабатывает и метод OnStopped() стратегии

War dieses Thema hilfreich?

Thema teilen

Kommentare (2)

Anmelden oder Konto erstellen, Melden Sie sich an oder registrieren Sie sich, um einen Kommentar zu hinterlassen

Alexander
Alexander

Возьмите свежую версию с codeplex, из сорсов, dev\References.

paveld
paveld Autor

Alexander Mukhanchikov: Возьмите свежую версию с codeplex, из сорсов, dev\References. Взял stocksharp-17261.zip, пока все нормально