Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

Excess Contracts Left Open After Trade Exit

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

    Excess Contracts Left Open After Trade Exit

    Hi,

    I'm coding a strategy for NinjaTrader 8 and encountering an issue with order management.

    I've implemented logic to evaluate the number of contracts for each operation, ensuring I never exceed a specified dollar value per trade. This part is working as intended. However, the problem arises when exiting trades with a certain number of contracts.

    For instance, when attempting to exit a trade with 10 contracts, the strategy sometimes sells 11 contracts instead, leaving an open order on the chart. This open order has an entry point at the previous exit and no Take Profit (TP) or Stop Loss (SL) set. I'm attaching a picture that shows the issue, where an operation with 17 contracts was closed with 18 contracts, leaving one open order.

    Interestingly, if I disable this feature and simply run the strategy with a fixed number of contracts, the problem does not occur. I'm also attaching the log for the operation shown in the picture to help you evaluate the issue.

    Here's the relevant part of my code for managing the operations:

    csharp// Long Entry
    if (Close[2] > entryLevel && Close[1] > entryLevel && Close[0] <= entryLevel && !entradaRealizada && Position.MarketPosition == Cbi.MarketPosition.Flat && !riskManagementTriggered)
    {
    if (SelectedTargetMode == TargetMode.Fib764And1146)
    {
    int contractsTP1 = (contracts + 1) / 2;
    int contractsTP2 = contracts / 2;

    EnterLong(contractsTP1, "Long TP1");
    EnterLong(contractsTP2, "Long TP2");
    }
    else
    {
    EnterLong(contracts, SelectedTargetMode == TargetMode.Fib764 ? "Long TP1" : "Long TP2");
    }
    entradaRealizada = true;
    currentStopPrice = bufferFib0;
    }

    // Manage Long Position
    if (Position.MarketPosition == Cbi.MarketPosition.Long)
    {
    if (SelectedTargetMode == TargetMode.Fib764And1146)
    {
    int contractsTP1 = (contracts + 1) / 2;
    int contractsTP2 = contracts / 2;

    // Verify if the stop price is valid before sending the order
    if (currentStopPrice < GetCurrentBid())
    {
    ExitLongStopMarket(contractsTP1, currentStopPrice, "Stop Loss TP1", "Long TP1");
    ExitLongStopMarket(contractsTP2, currentStopPrice, "Stop Loss TP2", "Long TP2");
    }
    else
    {
    ExitLong(contractsTP1, "Stop Loss TP1", "Long TP1");
    ExitLong(contractsTP2, "Stop Loss TP2", "Long TP2");
    }

    ExitLongLimit(contractsTP1, bufferFib764, "Take Profit TP1", "Long TP1");
    ExitLongLimit(contractsTP2, bufferFib1146, "Take Profit TP2", "Long TP2");
    }
    else
    {
    if (currentStopPrice < GetCurrentBid())
    {
    ExitLongStopMarket(contracts, currentStopPrice, "Stop Loss", SelectedTargetMode == TargetMode.Fib764 ? "Long TP1" : "Long TP2");
    }
    else
    {
    ExitLong(contracts, "Stop Loss", SelectedTargetMode == TargetMode.Fib764 ? "Long TP1" : "Long TP2");
    }

    ExitLongLimit(contracts, SelectedTargetMode == TargetMode.Fib764 ? bufferFib764 : bufferFib1146, "Take Profit", SelectedTargetMode == TargetMode.Fib764 ? "Long TP1" : "Long TP2");
    }

    if (UseBreakEven && Close[0] >= bufferFib764)
    {
    if (currentStopPrice != Position.AveragePrice)
    {
    currentStopPrice = Position.AveragePrice;
    if (currentStopPrice < GetCurrentBid())
    {
    ExitLongStopMarket(contracts, currentStopPrice, "Stop Loss", SelectedTargetMode == TargetMode.Fib764 ? "Long TP1" : "Long TP2");
    }
    else
    {
    ExitLong(contracts, "Stop Loss", SelectedTargetMode == TargetMode.Fib764 ? "Long TP1" : "Long TP2");
    }
    }
    }
    }

    private int CalculateContracts()
    {
    if (Contracts == ContractsMode.MaxLossPerTrade)
    {
    double entryLevel = SelectedEntryMode == EntryMode.Fib382 ? bufferFib382 : bufferFib236;
    double stopLossTicks = Math.Abs(entryLevel - bufferFib0) / TickSize;
    double stopLossAmount = stopLossTicks * TickSize * Instrument.MasterInstrument.PointValue;
    if (stopLossAmount <= 0)
    {
    Print("Error: Stop loss amount is zero or negative. Cannot calculate contracts.");
    return 0;
    }
    int contracts = (int)Math.Floor(MaxLossPerTrade / stopLossAmount);
    return Math.Max(1, contracts);
    }
    return ContractsPerTrade;
    }


    What can I do to fix this issue?

    Thank you for your assistance.
    Attached Files

    #2
    Hello,

    Thank you for your post.

    First, we have a sample script that demonstrates scaling out of a position that you may find helpful.



    You will need to debug the script to determine why it is exiting an excess number of contracts. In particular since you are using a variable for the quantity parameter, it would be helpful to print out the variable.

    To understand why the script is behaving as it is, such as placing orders or not placing orders when expected, it is necessary to add prints to the script that print the values used for the logic of the script to understand how the script is evaluating.

    In the strategy add prints (outside of any conditions) that print the date time of the bar and all values compared in every condition that places an order.

    The prints should include the time of the bar and should print all values from all variables and all hard coded values in all conditions that must evaluate as true for this action to be triggered. It is very important to include a text label for each value and for each comparison operator in the print to understand what is being compared in the condition sets.

    The debugging print output should clearly show what the condition is, what time the conditions are being compared, all values being compared, and how they are being compared.


    Prints will appear in the NinjaScript Output window (New > NinjaScript Output window).


    Further, enable TraceOrders which will let us know if any orders are being ignored and not being submitted when the condition to place the orders is evaluating as true.

    After enabling TraceOrders remove the instance of the strategy from the Configured list in the Strategies window and add a new instance of the strategy from the Available list.


    I am happy to assist you with analyzing the output from the output window.


    Run or backtest the script and when the output from the output window appears save this by right-clicking the output window and selecting Save As... -> give the output file a name and save -> then attach the output text file to your reply.


    Below is a link to a support article that demonstrates using informative prints to understand behavior and includes a link to a video recorded using the Strategy Builder to add prints.

    https://support.ninjatrader.com/s/ar...nd-TraceOrders

    Comment


      #3
      Hello Gaby,

      Thank you for your response and help.

      I have implemented the prints as instructed and performed the backtest to gather the necessary data during the problem. I am attaching the NinjaScript Output Prints with the logs for that period and also a couple of pictures showing the state before and after the problem occurred. As the Output prints file was too big, I cut out some irrelevant data from operations prior to the problem having occurred.

      Please note that the strategy ran smoothly for a while, then entered the trade to reach TP1, moved the SL to BE, and then, instead of closing the entire position when the price reached the BE, opened new operations in the opposite direction.

      I would appreciate your assistance in analyzing the output from the NinjaScript Output window to determine the cause of this behavior.

      If anything else is needed, please, let me know.

      Thank you for your support.

      Clayton
      Attached Files

      Comment


        #4
        Hello,

        Have prints been implemented for all conditions in the script? I am only seeing one single print in the entire output file, however many entries from TraceOrders. Additionally, the print contains no information about the 'contracts' variable which you are passing in for the quantity on all these entry/exit methods.

        Comment


          #5
          Hi Gaby,

          I have implemented prints for all conditions in the script. There might be a misunderstanding with the outputs. I've attached the NinjaScript Outputs for reference.

          Besides, now I can see in the prints the quantity of contracts it allocates at TP1 and TP2. If that's not the information you were referring to, please let me know so I can provide it to you.

          Once again, thank you so much.

          Clayton
          Attached Files

          Comment


            #6
            Hello,

            Thank you for your response.

            I'm still only seeing about 2 prints in here - for example, the one below. But unfortunately, these variables don't tell me anything about the condition.

            If you need assistance creating a print, please provide a condition in your script you would like to see an example print for and I'll gladly assist with creating an example print for you.

            2/12/2025 3:50:01 PMStop Loss TP1,Long TP1 , Short TP1, Stop Loss TP2, Long TP2

            2/12/2025 3:50:02 PM Strategy 'TheCrowStrategiesPrints/350753644': Entered internal SubmitOrderManaged() method at 2/12/2025 3:50:02 PM: BarsInProgress=0 Action=Sell OrderType=Limit Quantity=12 LimitPrice=21794.75 StopPrice=0 SignalName='Take Profit TP1' FromEntrySignal='Long TP1'

            I'm asking for you to also print out the 'contracts' variable that you're supplying to these order methods. For example below you are passing in 'contracts' as the quantity parameter for this exit long call.

            ExitLong(contracts, "Stop Loss", SelectedTargetMode == TargetMode.Fib764 ? "Long TP1" : "Long TP2");

            If you want assistance with a print I'll make the print include that as well.

            Lastly, what time stamp are we looking at here for this behavior? i.e. which timestamp did the unexpected order/behavior occur? ​

            Comment


              #7
              Hi Gaby,

              Thank you for your response.

              I have provided some pictures from before and after of a regular operation and of the operation that has failed. Additionally, I have attached the NinjaScript Output prints from the operation. Due to the large number of prints, I trimmed some of the outputs to keep the file manageable while preserving all significant times of the operation.

              Each line contains a timestamp. This operation is a market replay from February 11, 2025. The operation that was completed successfully started around 3:15 PM and ended at 4:05 PM, while the operation with the problem began around 4:08 PM and encountered the issue at approximately 4:16 PM. All of this is reflected in the prints. The test was conducted using MNQ-03-25 on the 16 Range chart.

              Another piece of information, you will notice that the amount of contracts its leaving in this example coincidentally was the same amount of contracts it has in the in the original operation, but it is not always like this. I've just ran the same market replay e different times at the same point and each time there is a different amount of contracts left. Always failing in this operation, though.
              It fails around 5% of the operations the strategy performs, the majority works correctly.

              Please let me know if any further information is required.

              Thank you again for your assistance. I look forward to your comments.



              Regards,

              Clayton
              Attached Files

              Comment


                #8
                Hello Clayton,

                I'm not seeing the output attached to your response, only the screenshots. Do you mind reposting the output?

                I look forward to your response.

                Comment


                  #9
                  Hi there. Sorry, the file was huge, so I had zipped it.

                  Now I have treated the data, trimming out all irrelevant pieces.

                  Find attached the NinjaScript Output.

                  Cheers

                  Clayton
                  Attached Files

                  Comment


                    #10
                    Hello Clayton,

                    Thank you for the file.

                    Unfortunately, these prints aren't very descriptive. Take the snippet below from your output for example. When I look at this print, it doesn't tell me anything about the condition that these values are from. How are these values being used in the condition? A good descriptive print should tell you exactly what the condition for that print is without having to look at the code.

                    Code:
                    Input Values:
                    Close[0]: 21796
                    Close[1]: 21793.5
                    Close[2]: 21791
                    Entry Level: 21789.683
                    Fibonacci Levels - Fib0: 21796.75, Fib236: 21792.384, Fib382: 21789.683, Fib764: 21782.616, Fib1146: 21775.549
                    Calculating Contracts:
                    Entry Level: 21789.683
                    Stop Loss Ticks: 28.2679999999964
                    Stop Loss Amount: 14.1339999999982
                    I am seeing the information from TraceOrders which indicates your script is submitting orders with quantity 11. However without the info from the prints for the condition, along with what your 'contracts' variable is, it is hard to say why the script is submitting orders with that quantity.

                    If you need assistance with creating a descrptive print, please provide a condition you would like to see an example for.

                    Otherwise, if you would like a consultant to debug this script for you, you can also contact a professional NinjaScript Consultant who would be eager to create or modify this script at your request or assist you with your script. The NinjaTrader Ecosystem has affiliate contacts who provide educational as well as consulting services.

                    Please let me know if you would like a list of affiliate consultants who would be happy to create this script or any others at your request or provide one on one educational services.
                    ​​

                    Comment

                    Latest Posts

                    Collapse

                    Topics Statistics Last Post
                    Started by NullPointStrategies, Today, 05:17 AM
                    0 responses
                    30 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