Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

ExitLong()

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

    ExitLong()

    I have a button that is supposed to Close my existing positions. Over the many times I have been testing the code out for other parts of the strategy, I have found that when I try to cancel it while there are positions open, it gives me an error and disables the strategy. After using Print() statements, I have narrowed it down to which section of code is giving me trouble:

    Print("Position.Quantity: " + Position.Quantity);
    if (Position.MarketPosition == MarketPosition.Long && Position.Quantity != 0)
    {
    Print("Trying to exit long");
    ExitLong();
    Print("After exit");
    }​

    My output is as follows (with traceOrders ON):

    Position.Quantity: 8
    Trying to exit long
    12/9/2024 11:46:59 AM Strategy 'PullBackStrategy/278923525': Entered internal SubmitOrderManaged() method at 12/9/2024 11:46:59 AM: BarsInProgress=0 Action=Sell OrderType=Market Quantity=0 LimitPrice=0 StopPrice=0 SignalName='' FromEntrySignal='LongPullback 1'
    Strategy 'PullBackStrategy/278923525': Error on calling 'OnOrderUpdate' method on bar 4321: You are accessing an index with a value that is invalid since it is out-of-range. I.E. accessing a series [barsAgo] with a value of 5 when there are only 4 bars on the chart.
    Disabling NinjaScript strategy 'PullBackStrategy/278923525'
    After exit​

    It says I am accessing an index with a value that is not valid...but it is crashing on the ExitLong();

    I have tried inserting Position.Quantity and adding my entry signals, but it does not work. I have commented the ExitLong(); code out and it stopped producing the error. It closed out my pending target and stop orders, but as expected, the open position remains open.

    I am entering the trades using EnterLong() and adding the stop and target orders later, but they are all using that original entry signal.

    I am at a loss on what to do. Any help would be greatly appreciated.

    #2
    Hello rockmanx00,

    Orders are placed in reference to a bar series.

    As this is from the .Click event of a button which is a non-data-driven method, may I confirm you have called TriggerCustomEvent() first?
    Chelsea B.NinjaTrader Customer Service

    Comment


      #3
      I am not. I believe I got the code from https://ninjatrader.com/support/help...collection.htm. Either that or it was from a stratey sample I have labeled: LONGSHORTToolbarButtonsB9. So i'm using System.Windows.Control.Button within OnMyButtonClick. and ChartControl.but not Trigger Custom Event.

      So if I'm using these buttons in this manner, how would I go about incorporating TriggerCustomEvent()?

      I'm not sure I understand what you mean by Orders are placed in reference to a bar series...do you mean when you use multiple instruments/ data series as mentioned in the BarsInProgress portion under ExitLong()?

      I can see there are various syntax for ExitLong() that don't have parameters or use the BarsInProgressIndex parameter, so how would I specify this, without needing the rest of the parameters? Would it matter even if I'm trading on the main instrument? Come to think of it, I don't think I'm using another dataseries for this, so there is only the one data set for this strategy. Or am I confusing this for something else?

      Comment


        #4
        I forgot to mention, I also get a pop up error regarding the index being out of bounds. I was playing around and testing this with shorts, but that pop up does not appear. It still crashes and disables the strategy, but I've also noticed that in the case of Longs, it does not get to OnOrderUpdate or OnExecutionUpdate but it does with Shorts.

        Comment


          #5
          Hello rockmanx00,

          Orders are submitted to the primary data series which contains the instrument information and pricing information. If a data series is added with AddDataSeries() the barsInProgressIndex is supplied to the order method to choose which bar series the order is submitted to.
          ExitLong(int barsInProgressIndex, int quantity, string signalName, string fromEntrySignal)

          Try the following:
          Code:
          TriggerCustomEvent((Action)() =>
          {
          Print("Position.Quantity: " + Position.Quantity);
          if (Position.MarketPosition == MarketPosition.Long && Position.Quantity != 0)
          {
          Print("Trying to exit long");
          ExitLong();
          Print("After exit");
          }​​
          }, null);
          Does the error still occur?

          Below is a link to an example of calling TriggerCustomEvent() from a button click.
          Chelsea B.NinjaTrader Customer Service

          Comment


            #6
            I am trying to understand how this TriggerCustomEvent() works. Looking at the sample provided, they only use this once and instead of Action() => they use o =>. When I try to add this in my code, it gives an "unexpected character error. Within my OnButtonClick code, the above code is already within "if (button.Name == "CloseAllButton"). Is this the right place to put this code, and if so, what am I supposed to input to make this work?

            Comment


              #7
              Hello rockmanx00,

              TriggerCustomEvent() synchronizes the bar series so the indexes are updated before attempting to access bar data.

              Using the suggested code I provided is this causing an error?
              Chelsea B.NinjaTrader Customer Service

              Comment


                #8
                Yes. I have replaced that section above with the one that you provided and it is making an error on the } from the if statement, above }, null;

                Comment


                  #9
                  I commented out the if statement and the brackets and the error goes away. Also for some reason clicking on the }, it is not sensing that it goes to the {

                  Comment


                    #10
                    I don't know what was up with the code. I had to retype out the If statement and then it was registering the {} properly. I will test out the code and see if it works.

                    Comment


                      #11
                      I am still receiving the same error. It is crashing on ExitLong() and is not going to OnExecutionUpdate at all...

                      Comment


                        #12
                        Hello rockmanx00,

                        This code would be in the .Click event handler.

                        May I have screenshot of the NinjaScript Editor window showing the error and the code?
                        Chelsea B.NinjaTrader Customer Service

                        Comment


                          #13
                          Strategy 'PullBackStrategy/278923527': Error on calling 'OnOrderUpdate' method on bar 4263: You are accessing an index with a value that is invalid since it is out-of-range. I.E. accessing a series [barsAgo] with a value of 5 when there are only 4 bars on the chart.

                          I have managed to get this to work now with shorts. For some reason, when I do a short, it tries to do a Buy to cover, which will take me to OnExecutionUpdate(). There was an unrelated error, and once that was fixed, I was able to close my Long without error and without disabling the strategy. However, in the case of trying to close out a Long Position, it doesn't say the same thing.

                          12/9/2024 11:17:37 AM Strategy 'PullBackStrategy/278923527': Entered internal SubmitOrderManaged() method at 12/9/2024 11:17:37 AM: BarsInProgress=0 Action=Sell OrderType=Market Quantity=0 LimitPrice=0 StopPrice=0 SignalName='' FromEntrySignal=''

                          The short version is this:
                          12/9/2024 11:05:40 AM Strategy 'PullBackStrategy/278923527': Entered internal SubmitOrderManaged() method at 12/9/2024 11:05:40 AM: BarsInProgress=0 Action=BuyToCover OrderType=Market Quantity=6 LimitPrice=0 StopPrice=0 SignalName='' FromEntrySignal=''

                          Oh, and yes. I have inserted the code within the Click event handler
                          Last edited by rockmanx00; 02-03-2025, 01:12 PM.

                          Comment


                            #14
                            Hello rockmanx00,

                            Are you certain that you put the code I suggested and not some other code (like the code you suggested in post # 6)?

                            The same error is occurring?

                            The "After exit" print is not appearing?

                            If you comment that code out the error no longer occurs?
                            Chelsea B.NinjaTrader Customer Service

                            Comment


                              #15
                              Your code, as in the TriggerCustomEvent code? yes. I replaced that and commented out my prior code. Actually I went as far as to delete mine as it's pretty much the same so I can easily undo it if need be.

                              When I press my CloseAll button, the following code occurs towards the end:

                              if (Debug)
                              {
                              Print("Position.MarketPosition: " + Position.MarketPosition);
                              }​

                              TriggerCustomEvent(o =>
                              {
                              Print("Position.Quantity: " + Position.Quantity);
                              if (Position.MarketPosition == MarketPosition.Long && Position.Quantity != 0)
                              {
                              Print("Trying to exit long");
                              ExitLong(Position.Quantity);
                              Print("After exit");
                              }
                              else if (Position.MarketPosition == MarketPosition.Short && Position.Quantity != 0)
                              {
                              Print("Trying to exit short");
                              ExitShort(Position.Quantity);
                              Print("After exit");
                              }
                              }, null);

                              Print("End of CloseAllButton Code");​

                              The output is as follows:

                              Position.MarketPosition: Long
                              Position.Quantity: 6
                              Trying to exit long
                              12/9/2024 11:03:53 AM Strategy 'PullBackStrategy/278923527': Entered internal SubmitOrderManaged() method at 12/9/2024 11:03:53 AM: BarsInProgress=0 Action=Sell OrderType=Market Quantity=6 LimitPrice=0 StopPrice=0 SignalName='' FromEntrySignal=''
                              Strategy 'PullBackStrategy/278923527': Error on calling 'OnOrderUpdate' method on bar 4235: You are accessing an index with a value that is invalid since it is out-of-range. I.E. accessing a series [barsAgo] with a value of 5 when there are only 4 bars on the chart.
                              Disabling NinjaScript strategy 'PullBackStrategy/278923527'
                              After exit
                              End of CloseAllButton Code​

                              Editing out the ExitLong will prevent the crash from occuring. No Pop ups, no errors and the strategy remains enabled. The position still exists of course. This is the output, used at a different part of the chart, so the Position.Quantity is different from before, but is accurate in this case.

                              Position.MarketPosition: Long
                              Position.Quantity: 4
                              Trying to exit long
                              After exit
                              End of CloseAllButton Code​

                              ****
                              I realized that I have since edited it and replaced (Action) () => with (o =>.
                              However, I get a syntax error if I leave that as is....if that helps?
                              Last edited by rockmanx00; 02-03-2025, 01:56 PM.

                              Comment

                              Latest Posts

                              Collapse

                              Topics Statistics Last Post
                              Started by NullPointStrategies, Today, 05:17 AM
                              0 responses
                              39 views
                              0 likes
                              Last Post NullPointStrategies  
                              Started by argusthome, 03-08-2026, 10:06 AM
                              0 responses
                              124 views
                              0 likes
                              Last Post argusthome  
                              Started by NabilKhattabi, 03-06-2026, 11:18 AM
                              0 responses
                              64 views
                              0 likes
                              Last Post NabilKhattabi  
                              Started by Deep42, 03-06-2026, 12:28 AM
                              0 responses
                              41 views
                              0 likes
                              Last Post Deep42
                              by Deep42
                               
                              Started by TheRealMorford, 03-05-2026, 06:15 PM
                              0 responses
                              46 views
                              0 likes
                              Last Post TheRealMorford  
                              Working...
                              X