﻿<?xml version="1.0" encoding="utf-8"?>
<?xml-stylesheet type='text/css' href='https://stocksharp.ru/css/style.css'?>
<?xml-stylesheet type='text/css' href='https://stocksharp.ru/css/bbeditor.css'?>
<feed xmlns="http://www.w3.org/2005/Atom">
  <title type="html">Ошибка System.NullReferenceException при остановке стратегии по событию EmulationTrader.StateChanged</title>
  <id>~/topic/2735/oshibka-system_nullreferenceexception-pri-ostanovke-strategii-po-sobytiyu-emulationtrader_statechanged/</id>
  <rights type="text">Copyright @ StockSharp Platform LLC 2010 - 2025</rights>
  <updated>2026-06-20T19:08:24Z</updated>
  <logo>https://stocksharp.ru/images/logo.png</logo>
  <link href="https://stocksharp.ru/handlers/atom.ashx?category=topic&amp;id=2735" rel="self" type="application/rss+xml" />
  <entry>
    <id>https://stocksharp.ru/posts/m/19348/</id>
    <title type="text">Alexander Mukhanchikov: Возьмите свежую версию с codeplex, из сорсов, dev\References. Взял stockshar...</title>
    <published>2012-05-25T20:39:56Z</published>
    <updated>2012-05-25T20:54:29Z</updated>
    <author>
      <name>paveld</name>
      <uri>https://stocksharp.ru/users/6010/</uri>
      <email>info@stocksharp.ru</email>
    </author>
    <content type="html">&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;&lt;a href="@message(19326)" rel="nofollow" target="_blank"&gt;Alexander Mukhanchikov&lt;/a&gt;:&lt;/strong&gt;
Возьмите свежую версию с codeplex, из сорсов, dev\References.
Взял stocksharp-17261.zip, пока все нормально&lt;/p&gt;
&lt;/blockquote&gt;
</content>
    <rights type="html">Copyright @ StockSharp Platform LLC 2010 - 2025</rights>
  </entry>
  <entry>
    <id>https://stocksharp.ru/posts/m/19326/</id>
    <title type="text">Возьмите свежую версию с codeplex, из сорсов, dev\References. </title>
    <published>2012-05-25T08:46:46Z</published>
    <updated>2012-05-25T08:46:46Z</updated>
    <author>
      <name>Alexander</name>
      <uri>https://stocksharp.ru/users/2826/</uri>
      <email>info@stocksharp.ru</email>
    </author>
    <content type="html">&lt;p&gt;Возьмите свежую версию с codeplex, из сорсов, dev\References.&lt;/p&gt;
</content>
    <rights type="html">Copyright @ StockSharp Platform LLC 2010 - 2025</rights>
  </entry>
  <entry>
    <id>https://stocksharp.ru/posts/m/19311/</id>
    <title type="text">В приведенном ниже коде после вызова в строке 69 метода _strategy.Stop() (вызывается по событию emul...</title>
    <published>2012-05-24T21:18:05Z</published>
    <updated>2012-05-24T21:24:41Z</updated>
    <author>
      <name>paveld</name>
      <uri>https://stocksharp.ru/users/6010/</uri>
      <email>info@stocksharp.ru</email>
    </author>
    <content type="html">&lt;p&gt;В приведенном ниже коде после вызова в строке 69 метода _strategy.Stop() (вызывается по событию emulationTrader.StateChanged и emulationTrader.State == EmulationStates.Stopped) возникает исключение:&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;System.NullReferenceException: &amp;quot;Ссылка на объект не указывает на экземпляр объекта.&amp;quot;
в StockSharp.Algo.Strategies.StrategyRule&lt;code&gt;1.#=qF$yf77tmtH$TvNML53EvZg==() в StockSharp.Algo.Strategies.StrategyRule&lt;/code&gt;1.#=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.&amp;lt;StartTestingStartegy&amp;gt;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&amp;amp; handled)
в MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean&amp;amp; 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&amp;amp; 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()&lt;/p&gt;
&lt;/blockquote&gt;
&lt;pre&gt;&lt;code class="language-csharp"&gt;
    public void StartTestingStartegy() {
      var security = new Security {
        Id = &amp;quot;RIM2@RTS&amp;quot;, // по идентификатору инструмента будет искаться папка с историческими маркет данными
        Code = &amp;quot;RIM2&amp;quot;,
        Name = &amp;quot;RTS-6.12&amp;quot;,
        MinStepSize = 5,
        MinStepPrice = 2,
        Exchange = Exchange.Test,
      };

      var portfolio = new Portfolio { Name = &amp;quot;test account&amp;quot;, BeginAmount = 30000m };

      var storageRegistry = new StorageRegistry(new InMemoryStorage()) {
        BasePath = &amp;quot;C:\\Trade\\Hydra\\&amp;quot;
      };

      // Устанавливаем значение таймфрейма
      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 += () =&amp;gt; {
        if (emulationTrader.State == EmulationStates.Stopped) {
          this.GuiAsync(() =&amp;gt; {
            LoggingHelper.AddInfoLog(emulationTrader, &amp;quot;Testing is completed&amp;quot;);
            StopTestingStartegy();            
          });
        } else if (emulationTrader.State == EmulationStates.Started) {
          // запускаем стратегию когда эмулятор запустился
          _strategy.Start();
          _isTestStrategyStarted = true;
          btnTest.Content = &amp;quot;Stop strategy&amp;quot;;
        }
      };
      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 = &amp;quot;Start strategy&amp;quot;;
    }

&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;До возникновения исключения переопределенная часть метода стратегии OnStopping() выполняется успешно, но OnStopped() не успевает вызыватся.
После возникновения ошибки, если нажать в отладчике F5 (продолжить), успешно отрабатывает и метод OnStopped() стратегии&lt;/p&gt;
</content>
    <rights type="html">Copyright @ StockSharp Platform LLC 2010 - 2025</rights>
  </entry>
</feed>