Announcement

Collapse

Looking for a User App or Add-On built by the NinjaTrader community?

Visit NinjaTrader EcoSystem and our free User App Share!

Have a question for the NinjaScript developer community? Open a new thread in our NinjaScript File Sharing Discussion Forum!
See more
See less

Partner 728x90

Collapse

Exception when closing positions

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

    Exception when closing positions

    I've written an indicator that works with some of the built in Chart Trader controls. Using the account that is selected in Chart Trader, I am trying to close the positions from within my code (example below). The positions are closed as expected, however I get the exception below along with some other unexpected behavior. The error seems to only happen if the position being closed has an ATM strategy tied to it. Otherwise, everything works as expected. Why would closing an ATM strategy give me this exception?

    Exception:
    Unhandled exception: Exception has been thrown by the target of an invocation.

    Code:
    Code:
    protected override void OnStateChange()
    {
        ChartControl.Dispatcher.InvokeAsync(() =>
        {
            if (State == State.Historical)
                GetMainControls();
        });
    }
    
    private void GetMainControls()
    {
        chartWindow = Window.GetWindow(ChartControl.Parent) as Gui.Chart.Chart;
        chartTraderGrid = (chartWindow.FindFirst("ChartWindowChartTraderCont rol") as Gui.Chart.ChartTrader).Content as System.Windows.Controls.Grid;
    
        accountSelector = chartWindow.FindFirst("ChartTraderControlAccountSe lector") as AccountSelector;
        qudQuantity = chartWindow.FindFirst("ChartTraderControlQuantityS elector") as QuantityUpDown;
        atmStrategySelector = LogicalTreeHelper.FindLogicalNode(chartWindow, "cbxStrategySelector") as NinjaTrader.Gui.NinjaScript.AtmStrategy.AtmStrateg ySelector;
    
        if (accountSelector!=null)
        {
            selectedAccount = accountSelector.SelectedAccount;
            accountSelector.SelectionChanged += (s, e) => selectedAccount = accountSelector.SelectedAccount;
        }
    
        btnClosePosition = new Button()
        {
            Content = "Close",
            Background = Brushes.Orange,
            Foreground = Brushes.White,
        };
        btnClosePosition.Click += btnClosePosition_Click;
    }
    
    protected void btnClosePosition_Click(object sender, RoutedEventArgs e)
    {
        if (selectedAccount==null)
            return;
    
        try{
    
            TriggerCustomEvent(ClosePosition, new[]{Instrument});
        }catch(Exception ex){Log(ex.ToString(),LogLevel.Error);}
    }
    
    private void ClosePosition(object instruments)
    {
        Instrument[] ins = instruments as Instrument[];
        selectedAccount.Flatten(ins);
    }
    Last edited by SystemTrading; 11-09-2021, 11:51 AM.

    #2
    Hello SystemTrading,

    Thank you for your inquiry.

    Have you taken debugging steps to determine the line of code throwing the exception? If not, I would recommend debugging with Visual Studio first to determine exactly what line is throwing it. Can you provide the stack trace for the exception thrown?

    Is the above code in a dispatcher since it involves working with the UI? Also, I see that the selectedAccount is set from an event, but I'm not seeing a check to determine whether this variable is null before actually using it.

    Thanks in advance; I look forward to assisting you further.
    Kate W.NinjaTrader Customer Service

    Comment


      #3
      I have updated the code in the original post to be more complete. In the code shown, the error message occurs at some point AFTER selectedAccount.Flatten() closes the position(s). My try/catch statement is not catching the exception. I've also tried to accomplish the same by iterating all positions in the selectedAccount and using the Position.Close() method, but that also caused the error. Since it seems to be related to the use of the ATM Strategy, I also tried to first iterate AtmStrategy.All to close any ATM strategies, then use one of the methods mentioned above to exit any remaining positions. In all cases, it seemed to place the proper orders, but I still get the error.

      Comment


        #4
        Hello SystemTrading,

        Thank you for your reply.

        I've plugged essentially similar code into an indicator and I'm seeing this operate as I would expect when a position is open using an ATM Strategy - do you see the same on your end? I would compare this to what you've got in your script and go from there.

        Please let us know if we may be of further assistance to you.

        Attached Files
        Kate W.NinjaTrader Customer Service

        Comment


          #5
          Thanks for the help Kate. I was finally able to locate and correct the issue. If it's helpful for anyone, my problem was a missing null check in the SelectionChanged event of the ATMStrategySelector.

          Code:
          if (atmStrategySelector!=null)
          {
              selectedATMStrategy = atmStrategySelector.SelectedAtmStrategy;
              atmStrategySelector.SelectionChanged += (s, e) =>
              {
                  // I was missing the following line of code
                  if (atmStrategySelector!=null && atmStrategySelector.SelectedAtmStrategy!=null)
                  {
                      selectedATMStrategy = atmStrategySelector.SelectedAtmStrategy;
                      timeInForce = atmStrategySelector.SelectedAtmStrategy.TimeInForc e;
                  }
                  else selectedATMStrategy = null;
              };
          }

          Comment

          Latest Posts

          Collapse

          Topics Statistics Last Post
          Started by Mizzouman1, Today, 07:35 AM
          4 responses
          18 views
          0 likes
          Last Post Mizzouman1  
          Started by philmg, Today, 01:17 PM
          1 response
          6 views
          0 likes
          Last Post NinjaTrader_ChristopherJ  
          Started by cre8able, Today, 01:01 PM
          1 response
          7 views
          0 likes
          Last Post NinjaTrader_ChelseaB  
          Started by manitshah915, Today, 12:59 PM
          1 response
          5 views
          0 likes
          Last Post NinjaTrader_Erick  
          Started by ursavent, Today, 12:54 PM
          1 response
          7 views
          0 likes
          Last Post NinjaTrader_Jesse  
          Working...
          X