Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

Close ALl positions button is not working on my strategy

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

    Close ALl positions button is not working on my strategy


    Hi I was wondering if someone can advice what is missing from my code. Long and Short buttons work, however when in the position "Close All" doesnt close anything. Maybe there is a working example i can look at?

    private Chart chartWindow;

    private new System.Windows.Controls.Button btnLongsOn;
    private new System.Windows.Controls.Button btnShortsOn;
    private new System.Windows.Controls.Button btnCloseAll;

    private bool IsToolBarButtonAdded;

    private bool longsOn = true;
    private bool shortsOn = true;​



    Code:
    #region Buttons
    
            private void AddButtonToToolbar()
            {
                chartWindow = Window.GetWindow(this.ChartControl.Parent) as Chart;
    
                if (chartWindow == null)
                {
                    Print("chartWindow == null");
                    return;
                }
    
                Style btnStyle = new Style();
                btnStyle.TargetType = typeof(System.Windows.Controls.Button);
    
                btnStyle.Setters.Add(new Setter(System.Windows.Controls.Button.FontSizeProperty, 11.0));
                btnStyle.Setters.Add(new Setter(System.Windows.Controls.Button.FontFamilyProperty, new FontFamily("Arial")));
                btnStyle.Setters.Add(new Setter(System.Windows.Controls.Button.FontWeightProperty, FontWeights.Bold));
                btnStyle.Setters.Add(new Setter(System.Windows.Controls.Button.MarginProperty, new Thickness(2, 0, 2, 0)));
                btnStyle.Setters.Add(new Setter(System.Windows.Controls.Button.PaddingProperty, new Thickness(4, 2, 4, 2)));
                btnStyle.Setters.Add(new Setter(System.Windows.Controls.Button.ForegroundProperty, Brushes.WhiteSmoke));
                btnStyle.Setters.Add(new Setter(System.Windows.Controls.Button.BackgroundProperty, Brushes.DimGray));
                btnStyle.Setters.Add(new Setter(System.Windows.Controls.Button.IsEnabledProperty, true));
                btnStyle.Setters.Add(new Setter(System.Windows.Controls.Button.HorizontalAlignmentProperty, HorizontalAlignment.Center));
    
                btnLongsOn = new System.Windows.Controls.Button();
                btnShortsOn = new System.Windows.Controls.Button();
                btnCloseAll = new System.Windows.Controls.Button();
    
                btnLongsOn.Content = "Longs On";
                btnShortsOn.Content = "Shorts On";
                btnCloseAll.Content = "Close All";
    
                btnLongsOn.Style = btnStyle;
                btnShortsOn.Style = btnStyle;
                btnCloseAll.Style = btnStyle;
    
                chartWindow.MainMenu.Add(btnLongsOn);
                chartWindow.MainMenu.Add(btnShortsOn);
                chartWindow.MainMenu.Add(btnCloseAll);
    
                btnLongsOn.Visibility = Visibility.Visible;
                btnShortsOn.Visibility = Visibility.Visible;
                btnCloseAll.Visibility = Visibility.Visible;
    
                btnLongsOn.Click += btnLongsOnClick;
                btnShortsOn.Click += btnShortsOnClick;
                btnCloseAll.Click += btnCloseAllClick;
    
                IsToolBarButtonAdded = true;
            }        
    
            private void btnLongsOnClick(object sender, RoutedEventArgs e)
            {
                System.Windows.Controls.Button button = sender as System.Windows.Controls.Button;
    
                if (button != null)
                {                                
                    if (!longsOn)
                    {
                        longsOn = true;                    
                        btnLongsOn.Content = "Longs On";                    
                    }
                    else
                    {
                        longsOn = false;
                        btnLongsOn.Content = "Longs Off";            
                    }
                }
            }        
    
            private void btnShortsOnClick(object sender, RoutedEventArgs e)
            {
                System.Windows.Controls.Button button = sender as System.Windows.Controls.Button;
    
                if (button != null)
                {                                
                    if (!shortsOn)
                    {
                        shortsOn = true;                    
                        btnShortsOn.Content = "Shorts On";                    
                    }
                    else
                    {
                        shortsOn = false;
                        btnShortsOn.Content = "Shorts Off";            
                    }
                }            
            }
    
            private void btnCloseAllClick(object sender, RoutedEventArgs e)
            {
                System.Windows.Controls.Button button = sender as System.Windows.Controls.Button;
    
                if (button != null)
                {
                    Dispatcher.InvokeAsync((() =>
                    {
                        if (Position.MarketPosition == MarketPosition.Long)
                            ExitLong();
                        else if (Position.MarketPosition == MarketPosition.Short)
                            ExitShort();                    
                    }));    
                }
            }
    
            private void DisposeCleanUp()
            {
                if (btnLongsOn != null) chartWindow.MainMenu.Remove(btnLongsOn);
                    btnLongsOn.Click -= btnLongsOnClick;
                if (btnShortsOn != null) chartWindow.MainMenu.Remove(btnShortsOn);
                    btnShortsOn.Click -= btnShortsOnClick;
                if (btnCloseAll != null) chartWindow.MainMenu.Remove(btnCloseAll);
                    btnCloseAll.Click -= btnCloseAllClick;            
            }
    
            #endregion​
    Last edited by tkaboris; 02-10-2023, 01:06 PM.

    #2
    Hello, thanks for writing in. The ExitLong/ExitShort and Position objects are available to all instances of Strategies. Is this code from a Strategy or from an indicator/Addon? You can also use the Print() method to help you debug your script and see why it's not exciting e.g.

    Code:
    Print("Checking position object " + Position.MarketPosition);
    if (Position.MarketPosition == MarketPosition.Long)
    {
       Print("ExitLong");
       ExitLong();
    }
    else if (Position.MarketPosition == MarketPosition.Short)
    {
       Print("ExitShort");
       ExitShort();
    }​​
    If you are running from an Addon use this instead of Print():

    NinjaTrader.Code.Output.Process("my message", PrintTo.OutputTab1);

    Comment


      #3
      thank you, Its Strategy. is this should go in my button region?
      Last edited by tkaboris; 02-10-2023, 01:45 PM.

      Comment


        #4
        Correct, It should go in your btnCloseAllClick method.

        Comment


          #5
          thank you, i have this but its complaining on exitLong line and invalid if else statement
          . I attached pic here https://prnt.sc/j-L1Mrled17o

          private void btnCloseAllClick(object sender, RoutedEventArgs e)
          {
          System.Windows.Controls.Button button = sender as System.Windows.Controls.Button;

          if (button != null)
          {

          Dispatcher.InvokeAsync((() =>
          {
          Print("Checking position object " + Position.MarketPosition);
          if (Position.MarketPosition == MarketPosition.Long)
          Print("ExitLong");
          ExitLong();
          else if (Position.MarketPosition == MarketPosition.Short)
          Print("ExitShort");
          ExitShort();
          }));
          }
          }​

          Comment


            #6
            I got this in Print generated when I was pressing Close All
            Checking position object Long
            Checking position object Long
            Checking position object Long
            Checking position object Long
            Checking position object Long
            Checking position object Long
            Checking position object Long
            Checking position object Long
            Checking position object Long
            Checking position object Flat
            Checking position object Flat​

            Comment


              #7
              I still have this problem where i cant close position from strategy. I hit close all button but its not closing positions

              Code:
               private void btnCloseAllClick(object sender, RoutedEventArgs e)
                      {
                          System.Windows.Controls.Button button = sender as System.Windows.Controls.Button;
              
                          if (button != null)
                          {
                              var unused2 = Dispatcher.InvokeAsync(() =>
                              {
                                  Print("Checking position object " + Position.MarketPosition);
                                  if (Position.MarketPosition == MarketPosition.Long)
                                  {
                                      //var unused1 = ExitLong(Position.Quantity);
                                      Print("ExitLong");
                                      ExitLong();
                                  }
              
                                  else if (Position.MarketPosition == MarketPosition.Short)
                                  {
                                      //var unused = ExitShort(Position.Quantity);
                                      Print("ExitShort");
                                      ExitShort();
                                  }
                              });
                          }
                      }​
              Click image for larger version  Name:	image.png Views:	0 Size:	894.0 KB ID:	1240497Click image for larger version  Name:	image.png Views:	0 Size:	7.6 KB ID:	1240500
              Last edited by tkaboris; 03-15-2023, 11:39 AM.

              Comment


                #8
                Hi Boris, the strategy has IsUnmanaged = true, so you will not be able to use the managed Exit/Entry orders. You must also call SumbitOrderUnmanaged() to close the position.

                Comment


                  #9
                  Can you please help me with syntax?

                  I have for my regular SL this code for longs
                  Code:
                  SubmitOrderUnmanaged(0, OrderAction.Sell, OrderType.StopMarket, filled, 0, sl, oco, "SL");

                  Comment


                    #10
                    Hi Boris, for a market sell order you can pass in the Position.Quantity variable:
                    SubmitOrderUnmanaged(0, OrderAction.Sell, OrderType.Market, Position.Quantity);

                    Comment


                      #11
                      Thank you i did that. When i have pressed close all then i get two hanging orders and this error message
                      Click image for larger version

Name:	image.png
Views:	145
Size:	62.6 KB
ID:	1240578

                      Comment


                        #12
                        Hi Boris, could you please post the newest version of your code?

                        Comment


                          #13
                          Yes here it is. I appriciate it
                          Attached Files

                          Comment


                            #14
                            Hi, are you seeing the ChangeOrder() method getting called before this error happens? Add a print near the locations you are calling this method.

                            Comment


                              #15
                              I put print in this area
                              Code:
                              [CODE]if ((UseTrailingStop) && (IsInShortTrade) && (LastClose > Close[0]) && (stopOrder != null))
                                                  {
                                                      double slL = Instrument.MasterInstrument.RoundToTickSize(Close[0] + (StopLoss * TickSize));
                              
                              
                                                      Print(Position.Quantity);
                                                      if(entryOrder != null)ChangeOrder(stopOrder, Position.Quantity, 0, slL);
                              
                                                      LastClose = Close[0];
                              
                              
                                                      if(PrintToOutputScreen)
                                                      Print("Short Trade Trailing Stop         sIL = " + slL + "        Position.Quantity = " + Position.Quantity + "        CurrentBar = " + CurrentBar);
                              
                              
                                                  }    ​
                              [/CODE]

                              I got this in output
                              Enter Long Trade
                              OnOrderUpdate - Start
                              Enter Long Trade Profit Target = 12418.75
                              Enter Long Trade StopLoss = 12403.25
                              OnOrderUpdate - Done
                              orderId='5b6f98173da04d409d7da7d0045c7743' account='Sim101' name='SL' orderState=Submitted instrument='NQ 06-23' orderAction=Sell orderType='Stop Market' limitPrice=0 stopPrice=12403.25 quantity=1 tif=Gtc oco='d0774cd5-ee32-4707-a3de-b8189dda3070' filled=0 averageFillPrice=0 onBehalfOf='' id=94986 time='2023-03-15 19:44:58' gtd='2099-12-01' statementDate='2023-03-15'
                              Long Trade Trailing Stop slL = 12402.75 Position.Quantity = 1 CurrentBar = 74768
                              orderId='5b6f98173da04d409d7da7d0045c7743' account='Sim101' name='SL' orderState=Accepted instrument='NQ 06-23' orderAction=Sell orderType='Stop Market' limitPrice=0 stopPrice=12402.75 quantity=1 tif=Gtc oco='d0774cd5-ee32-4707-a3de-b8189dda3070' filled=0 averageFillPrice=0 onBehalfOf='' id=94986 time='2023-03-15 19:44:58' gtd='2099-12-01' statementDate='2023-03-15'
                              Long Trade Trailing Stop slL = 12403 Position.Quantity = 1 CurrentBar = 74768
                              orderId='5b6f98173da04d409d7da7d0045c7743' account='Sim101' name='SL' orderState=Accepted instrument='NQ 06-23' orderAction=Sell orderType='Stop Market' limitPrice=0 stopPrice=12403 quantity=1 tif=Gtc oco='d0774cd5-ee32-4707-a3de-b8189dda3070' filled=0 averageFillPrice=0 onBehalfOf='' id=94986 time='2023-03-15 19:45:00' gtd='2099-12-01' statementDate='2023-03-15'
                              Long Trade Trailing Stop slL = 12403.5 Position.Quantity = 1 CurrentBar = 74768
                              orderId='5b6f98173da04d409d7da7d0045c7743' account='Sim101' name='SL' orderState=Accepted instrument='NQ 06-23' orderAction=Sell orderType='Stop Market' limitPrice=0 stopPrice=12403.5 quantity=1 tif=Gtc oco='d0774cd5-ee32-4707-a3de-b8189dda3070' filled=0 averageFillPrice=0 onBehalfOf='' id=94986 time='2023-03-15 19:45:01' gtd='2099-12-01' statementDate='2023-03-15'
                              Long Trade Trailing Stop slL = 12404 Position.Quantity = 1 CurrentBar = 74768

                              Comment

                              Latest Posts

                              Collapse

                              Topics Statistics Last Post
                              Started by NullPointStrategies, Yesterday, 05:17 AM
                              0 responses
                              76 views
                              0 likes
                              Last Post NullPointStrategies  
                              Started by argusthome, 03-08-2026, 10:06 AM
                              0 responses
                              146 views
                              0 likes
                              Last Post argusthome  
                              Started by NabilKhattabi, 03-06-2026, 11:18 AM
                              0 responses
                              79 views
                              0 likes
                              Last Post NabilKhattabi  
                              Started by Deep42, 03-06-2026, 12:28 AM
                              0 responses
                              50 views
                              0 likes
                              Last Post Deep42
                              by Deep42
                               
                              Started by TheRealMorford, 03-05-2026, 06:15 PM
                              0 responses
                              54 views
                              0 likes
                              Last Post TheRealMorford  
                              Working...
                              X