Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

Cancel Order changing results dramatically

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

    Cancel Order changing results dramatically

    I have a very strange problem in my code.

    In this strategy, there are two different stop losses with two different names. Both are often used in the same trade.
    • TrailingStopLong
    • LongAdjustedStop


    The code for LongAdjustedStop gets called when certain criteria are met, and then when the trend starts going in my direction, then LongAdjustedStop is to no longer be used; instead, TrailingStopLong takes over. Currently, in my code, when TrailingStopLong takes over, I have it set to cancel the order for LongAdjustedStop.

    Here is the code for that:

    Code:
    			if (LongLimit != null 
    				&& LongLimit.OrderState == OrderState.Filled)
    			{
    				if (Close[0] > SMA(BarsArray[0], sMAPeriod)[0]+((signalHigh-signalLow)*StopPerc)
    					&& LongAdjustedStop != null)
    				{
    					TrailingStopLong = ExitLongStop(0,true,positionSize, tStopPriceLong,"TrailingStopLong","LongEntryB");
    					Print(Time[0] + " Trailing Stop = " + tStopPriceLong);
    					Print("LongAdjustedStop = " + adjustedStopLong);
    					CancelOrder(LongAdjustedStop);
    					Print("Hooray!!!! LongTrailingStop is initially triggered @   " + tStopPriceLong + Time[0]);
    				}
    			}
    Strangely though, this is producing some different results that I have been working on for quite a while to figure out. Attached is a picture titled OrderCancelled.

    If you look at that picture then you will see two trades. The first trade closed a position using TrailingStopLong at the price of 102.41 (which is correct!). The second trade also closed part of the position using TrailingStopLong at a price of 101.60 which is not correct. In this case, it should have exited using LongAdjustedStop.

    As a result of this error, I decided to not use the "CancelOrder" command in order to leave LongAdjustedStop within the code. Please look at the other attached file called OrderNotCancelled.

    In this picture you see the same trades. But this time, you will find that the first trade exits using LongAdjustedStop at a price of 102.40 which is not correct and the second trade exits with LongAdjustedStop at 101.75'5 which is correct.

    Another element to this that I do not understand is that in the first trade (using the OrderNotCancelled attachment) the proper stop was 102.41 but it was stopped out at 102.40 using the wrong order. From my print statements, the TrailingStopLong is properly being called and trailing and is at the right price at the time that it should be stopped out. You can see that in the attachment called "output window."

    Can somebody please help me fix this part of the code?

    Thank you very very much!
    Attached Files

    #2
    Hello jg123,

    Thank you for your post.
    Originally posted by jg123 View Post
    Code:
    			if (LongLimit != null 
    				&& LongLimit.OrderState == OrderState.Filled)
    			{
    				if (Close[0] > SMA(BarsArray[0], sMAPeriod)[0]+((signalHigh-signalLow)*StopPerc)
    					&& LongAdjustedStop != null)
    				{
    					TrailingStopLong = ExitLongStop(0,true,positionSize, tStopPriceLong,"TrailingStopLong","LongEntryB");
    					Print(Time[0] + " Trailing Stop = " + tStopPriceLong);
    					Print("LongAdjustedStop = " + adjustedStopLong);
    					CancelOrder(LongAdjustedStop);
    					Print("Hooray!!!! LongTrailingStop is initially triggered @   " + tStopPriceLong + Time[0]);
    				}
    			}
    This code would only submit the TrailingStopLong when the entry order was filled, in that event. I am assuming you also set the entry order IOrder object to null. I would suggest adding this to OnBarUpdate() without the if (LongLimit != null && LongLimit.OrderState == OrderState.Filled) condition, and just check for the position being long via Position.MarketPosition: http://www.ninjatrader.com/support/h...etposition.htm

    Comment


      #3
      Thank you Patrick

      This actually isn't an entry order. LongLimit is an exit order. This strategy has two entries and the two stops mentioned in the first post are only supposed to be called when the first entry is exited using LongLimit.

      I have been having issues with the restting of LongLimit back to null so I have been commenting that section out while I work on other parts of the code to get it right. But actually that may be a very good place to start.

      Here is the code that I have for setting LongLimit back to null that has at least two errors in it but I can not figure out where it is.

      Code:
      try {
      			if (LongStopB.OrderState == OrderState.Filled
      				&& LongLimit != null)
      			{
      				LongLimit = null;
      			}
      
      			if (LongAdjustedStop.OrderState == OrderState.Filled
      				&& LongLimit != null
      				&& LongAdjustedStop != null)
      			{
      				LongLimit = null;
      			}
      }
      catch (Exception e)
      {
      	Log("Error is here",LogLevel.Error);
      }			
      			if (TrailingStopLong != null
      				&& TrailingStopLong.OrderState == OrderState.Filled
      				&& LongLimit != null)
      			{
      				TrailingStopLong = null;
      				LongLimit = null;
      			}
      I have left the try/catch in there that shows the two sections that have the error. I keep getting that something is not connected to an object. Are you able to see where I am going wrong with that?

      Comment


        #4
        Hello jg123,

        Thank you for your response.

        Form your snippet of code I cannot tell what would cause this error. Can you provide a test script or your own to test? In addition, can you detail the full message returned?

        Comment


          #5
          Hi Patrick

          Here is the strategy attached. The code snippet is found on lines 432 - 456. Lines 24 - 70 give a detailed explanation of exactly what this strategy is supposed to do if that helps you also.

          The exact error is "Object reference not set to an instance of an object." and it is in OnExecution. This is why I have put the try/catch in there and the try catch is still there.

          Thank you very much for your help.I am really looking forward to what kind of insight you have for me.
          Attached Files

          Comment


            #6
            Hello jg123,

            Thank you for your response.
            I would recommend simplifying the code down to only the items needed to submit the orders in the Try-Catch block. This help to further isolate the issue.

            Comment


              #7
              Hi Patrick

              Thank you for your help

              I have followed your advice and I have simplified everything down to its most basic form and am rebuilding it from there. All of the code is still in strategy but it is all commented out except for what will cause it to run. Then I am not adding anything more until I see that everything is working correctly in its current form and then slowly adding layer by layer. I have already been able to correct a few errors by doing this.

              I have now come across an error that I am not able to figure out.

              Attached is a picture of the USDJPY hourly chart. It is connected to Simulated Data feed and using IB historical data. On 20 May you will find that there are two places that the trade is being stopped out. LongAStop @ 101.30 and LongBStop @ 101.37'5. If you look just a couple of days earlier on 15 May, you will find that they were stopped out at the same place @ 101.65, which is the way that it is supposed to be.

              The following code is what I am using for my initial stop loss, which is what both of these are being stopped out with (There are no other stop losses currently active in the code)

              Code:
              			if(LongEntryA != null
              				&& LongEntryB != null
              				&& LongEntryA.OrderState == OrderState.Filled
              				&& LongEntryB.OrderState == OrderState.Filled)
              			{
              				LongStopA = ExitLongStop(0,true,positionSize,SMA(sMAPeriod)[0] - ((signalHigh - signalLow) * StopPerc),"LongAStop","LongEntryA");		
              				LongStopB = ExitLongStop(0,true,positionSize,SMA(sMAPeriod)[0] - ((signalHigh - signalLow) * StopPerc),"LongBStop","LongEntryB");
              				Print(Time[0] + " Stop orders are placed.");
              				Print(Time[0] + " LongStopA = " + LongStopA);
              				Print(Time[0] + " LongStopB = " + LongStopB);
              			}
              What is most important about this code, in my opinion, is that you can see that it is exactly the same equation used for LongStopA & LongStopB. Therefore, they should be exiting at exactly the same spot.

              I am also attaching the Output file. With that, you can see that at 3:00AM the stop orders were placed and both were set to 101.30. Then at 10:00 AM there is no longer any information for LongStopA but, now, LongStopB is set to 101.375. I can not find anything in my code that would cause this to change - and, if there were, why did it not change both of the orders?

              Finally, I have the following code to create a print statement if the LongStopA and/or LongStopB were filled. This print statement then tells me that the trade was stopped out at its initial stop loss. But, this print statement is not printing after the two trades close even though they, according to the chart, definitely did close. It also resets the profit target order to null if the trades are stopped out.

              here is the code:
              Code:
              			if (LongStopA != null
              				&& LongStopA.OrderState == OrderState.Filled)
              			{
              				Print(Time[0] + " Close at initial Stop Loss - A");
              				LongLimit = null;
              			}
              			
              			if (LongStopB != null
              				&& LongStopB.OrderState == OrderState.Filled)
              			{
              				Print(Time[0] + " Close at initial Stop Loss - B");
              			}
              Again, there is no other code that is active currently in the strategy for it to be stopped out. And, even if there was another stop out code, it would use a different name other than LongStopA or LongStopB.

              Would you be able to help me figure out why LongStopB is different from LongStopA and why the Print statements after they are executed are not printing correctly?

              Thank you very much for your help
              Attached Files

              Comment


                #8
                Hello jg123,

                Thank you for your response.

                I see the following lines in your Output:
                20-May-14 3:00:00 AM Close at initial Stop Loss - A
                20-May-14 3:00:00 AM Close at initial Stop Loss - B
                Were these orders not executed at 3 AM? i.e. what is the time stamp of the bar these orders filled on?

                For the odd price level fills, what Historical Fill Processing are you using? What Slippage is being used?

                Comment


                  #9
                  Thank you Patrick

                  The time stamp for the LongAStop and LongBStop for 20 May is 11:00 AM. I had noticed those lines as well, but i can not see any trades that are closing then. In fact, if anything, that is when the trade is opening.

                  The Historical Fill Processing is currently set to Default. Aside from that, these are Stop orders and if I understand Fill processing correctly, then it only deals with limit orders and stop limit orders. is that correct?

                  Slippage is currently set to 0.

                  Comment


                    #10
                    figured that i may be a good idea to post the strategy. There is still a lot of code in this, but most of it is commented out and only the foundation of the code is made live in this.
                    Attached Files

                    Comment


                      #11
                      i figured out what the problem was for the two different stop prices. it honestly doesn't make sense to me how this would have made a difference in this situation, but it seems to have fixed it. The problem is that there was a cancel order condition for the entry orders that did not reset the entry orders to null. as soon as i did that, it fixed the issue with the two stop prices.

                      thanks for all of your help thusfar. you guys are always so great

                      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