Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

Possible BIG bug when using StopTargetHandling.ByStrategyPosition

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

    Possible BIG bug when using StopTargetHandling.ByStrategyPosition

    It will take some time to build a little example from the problem I'm facing building my strategy, but let me get the ball rolling by explaining simply what the problem is and make sure I'm not misunderstanding the logic:

    Using the Managed Methods approach, in Initialize() for my strategy, I'll put:

    StopTargetHandling = StopTargetHandling.ByStrategyPosition;

    Yes, this is "undocumented", but you can just as well set it in the Strategy Tab when you insert your strategy into the chart, so, whichever way you prefer. Same thing.

    What the above does is allow me to add to my position during the course of a trade and have all the contracts entered (I'm trading futures), tagged with the same "fromEntrySignal", ADDED TO ONE STOP AND ONE TARGET so I only have to manage those two other positions during the trade to exit.

    For example, in a long position, my initial stop order creation would look like this:

    stopOrder = ExitLongStop(0, true, initial_quantity_of_first_entry, stop_price, "Stop", "Long");

    and my initial target order creation would look like this:

    targetOrder = ExitLongLimit(0, true, initial_quantity_of_first_entry, target_price, "Target", "Long");

    For simplicity, let's say all the add-on orders before the stop or target is hit look like simple market orders:

    entryOrder = EnterLong(add_quantity, "Long");

    Notice above that I'm letting NT know that all these are associated with the "fromEntrySignal".

    HERE'S THE PROBLEM:

    Let's say I have collected 4 unique positions with the quantity of each position equal to 1 contract.

    While the trade is still active, I can move the stop around like this:

    ExitLongStop(0, true, Position.Quantity, new_stop_price, "Stop", "Long");

    And I can move the target around like this:

    ExitLongLimit(0, true, Position.Quantity, new_target_price, "Target", "Long");

    What happens when the stop gets hit first?

    Perfection! All 4 contracts exit properly. Yippee!

    What happens when the target gets hit first?

    I only get ONLY ONE CONTRACT EXITED and I'M STILL LONG THREE CONTRACTS! HUH?! No way, I should get an exit of all 4 contracts.

    NinjaTrader support, is my reasoning correct? If so, all that's left is for me to prove it to you in code, right? I found someone else talking about this in these forums in 2008. That would make this a 6 yr old huge gaping bug if I'm right. Seriously, I hope I'm missing something because, otherwise, I have to go to the unmanaged world or write extra code to bail on the remaining target contracts with an EXTRA ROUNDTRIP ExitLong("Long") or ExitShort("Short") call and neither of those alternatives is a fun place to be.
    Last edited by hygm; 08-01-2014, 08:39 AM.

    #2
    Hi hygm,

    Thanks for your post.

    First, I want to mention that using StopTargetHandling.ByStrategyPosition is a supported feature of NinjaScript.

    This is outlined in the help guide on the Managed Approach in the section 'How to close a position'.
    http://www.ninjatrader.com/support/h...d_approach.htm

    However, this only applies when using SetStopLoss and SetProfitTarget, so this will not apply to your custom exits.


    I'd like you to add a few things to your code to investigate further.

    First, please add TraceOrders = true; to the Initialize() method.

    Then add a print of the Position.Quantity as that exit limit is set.
    Print(Position.Quantity);

    The output of this will go to the Output Window. (Tools -> Output Window...)

    Please post the output that is created after the script is re-run.
    Chelsea B.NinjaTrader Customer Service

    Comment


      #3
      Yeah, like I thought, this is going to require me to produce a simplified coding example for you which spells it out. That, in itself, with pretty pics takes a few hours of my time, but, as was said by Richard Gere in "An Officer and a Gentleman"..."I got no place else to go!".

      I've already tested this with what you suggested in my strategy and the Position.Quantity, in this example, is correct at 4. With TraceOrders = true, you get the exit with a Quantity = 1 (shouldn't this be 4?) and the proper FromSignalEntry and SignalName. I also noticed that the Quantity did NOT increase in the saved-off targetOrder variable (pointing to the target order's IOrder) as the contracts were being added to the target before any exits. I didn't check the stopOrder quantity accumulation but will do.

      Notice I mentioned that the stop order logic is working like a dream and both stop and target orders use Position.Quantity, a read-only variable of the overall position size which I cannot alter. They both use Position.Quantity to move either the stop or target order around.

      Okay, the ball is in my court. I will post some sample code of a market replay with sample pics of the good exit with the stop and the partial exit (should be full exit) with the target.

      Comment


        #4
        Hi hygm,

        Instead of screenshots, an example script would work.

        This should be pretty easy to create, just reduce your code down to only what is needed to enter the order, set the exits, and then move the limit.

        I'll test this on my end and see if I can figure out what is going on.

        Let me know what instrument and interval you are using for your testing when you post the example script.

        To export your script do the following:
        1. Click File -> Utilities -> Export NinjaScript
        2. Enter a unique name for the file in the value for 'File name:'
        3. Select the strategy from the objects list on the left -> click the right facing arrow ">" to add the strategy to the export
        4. Click the 'Export' button -> click 'yes' to add any referenced indicators to the export -> click OK to clear the export location message


        By default your exported file will be in the following location:
        • (My) Documents/NinjaTrader 7/bin/Custom/ExportNinjaScript/<export_file_name.zip>


        Below is a link to the help guide on Exporting NinjaScripts.
        http://www.ninjatrader.com/support/h...nt7/export.htm
        Chelsea B.NinjaTrader Customer Service

        Comment


          #5
          Okay, after more testing, here's the resolution to all of this:

          1. If you use SetStopLoss() and SetProfitTarget() in the managed orders API with the StopTargetHandling option set to ByStrategyPosition then YES, any additional order executions from the initial entry will automatically increase the size of your stop and target orders to equal the total position size of your entries (i.e., Position.Quantity).

          HOWEVER

          2. If you DON'T use SetStopLoss() and SetProfitTarget(), but instead, use the ExitLongStop() / ExitLongLimit() pair to manage your stop and target orders for long trades or the ExitShortStop() / ExitShortLimit() pair to manage your stop and target orders for short trades, THEN YOU MUST MANUALLY AMEND THEM AFTER EACH NEW EXECUTION TO SET THEIR NEW RESPECTIVE QUANTITIES TO POSITION.QUANTITY.

          This is where my original explanation is flawed: I assumed that the FromEntrySignal association took care of the automatic increment of the stop and target orders when the StopTargetHandling option is set to ByStrategyPosition. It doesn't. Better said, if you don't use SetStopLoss() and SetProfitTarget(), you're on your own to have your stop and target order bracket match the size of your total position as new executions arrive to the OnExecution() function.
          Last edited by hygm; 08-03-2014, 12:01 AM.

          Comment


            #6
            Hi hygm,

            The Stop & target submission will only apply to stop losses and profit targets. This is mentioned in post #2.

            However, this only applies when using SetStopLoss and SetProfitTarget, so this will not apply to your custom exits.
            Chelsea B.NinjaTrader Customer Service

            Comment


              #7
              Chelsea,

              Given that I'm still using:

              StopTargetHandling = StopTargetHandling.ByStrategyPosition;

              and have additional orders, all of which are intended to exit at the same target, using ExitLongLimit() for a long trade and ExitShortLimit() for a short trade (both using the liveUntilCanceled argument set to true) then, for example, out of 4 contracts accumulated:

              Why does the 1st contract exit at my target limit order and the remaining 3 turn into market orders to exit?

              Is there no other way to get all 4 collected contracts (i.e., 4 separate positions tied to 1 limit order of 4 contracts) to exit at the limit price without using the SetStopLoss() / SetProfitTarget() pair if my intention is to stay with the managed API?

              Comment


                #8
                Hello hygm,

                If you are using Exit orders instead of stop losses and profit targets, you need to completely ignore the StopTargetHandling.

                This will not be involved.


                Regarding your exits, are you using entry signals?
                What signal names are you giving the entries?
                What fromEntrySignals are you giving the exits?

                An ExitLongLimit cannot be converted to a market order.

                Do you have TraceOrders enabled?
                How do you know that the orders exiting the position are market orders?

                Do you have prints and output that we can see?
                Chelsea B.NinjaTrader Customer Service

                Comment


                  #9
                  Chelsea,

                  Totally my bad and I apologize. I need to use "TraceOrders = true" ALL the time during debug. Thank you for reminding me!

                  I had a spurious ExitLong() / ExitShort() logic when I detected a targetOrder had been hit. It got exposed when I had a partial fill of the limit order with multiple contracts. Well, on a positive note, I know now how to get out of a long on a partial fill as an option in my strategy (tongue in cheek).

                  Comment

                  Latest Posts

                  Collapse

                  Topics Statistics Last Post
                  Started by Geovanny Suaza, 02-11-2026, 06:32 PM
                  0 responses
                  639 views
                  0 likes
                  Last Post Geovanny Suaza  
                  Started by Geovanny Suaza, 02-11-2026, 05:51 PM
                  0 responses
                  366 views
                  1 like
                  Last Post Geovanny Suaza  
                  Started by Mindset, 02-09-2026, 11:44 AM
                  0 responses
                  107 views
                  0 likes
                  Last Post Mindset
                  by Mindset
                   
                  Started by Geovanny Suaza, 02-02-2026, 12:30 PM
                  0 responses
                  569 views
                  1 like
                  Last Post Geovanny Suaza  
                  Started by RFrosty, 01-28-2026, 06:49 PM
                  0 responses
                  572 views
                  1 like
                  Last Post RFrosty
                  by RFrosty
                   
                  Working...
                  X