Announcement

Collapse

Looking for a User App or Add-On built by the NinjaTrader community?

Visit NinjaTrader EcoSystem and our free User App Share!

Have a question for the NinjaScript developer community? Open a new thread in our NinjaScript File Sharing Discussion Forum!
See more
See less

Partner 728x90

Collapse

react to order errors from indicator using addon approach

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

    react to order errors from indicator using addon approach

    I coded an Indicator and I'm taking trades using the createOrder() method. I also created target and stoploss orders that are linked to the entry orders. when the market moves fast however I at times get two error messages: 1) Order can't be submitted, order state is CancelPending, 2) StopLoss order can't be placed above/below the market. I tried to catch these errors with following code in the OnOrderUpdate() Stream:

    else if (_LongProfitTargetOrder != null && _LongProfitTargetOrder == e.Order)
    {
    if (e.Order.OrderState == OrderState.Rejected || e.Order.OrderState == OrderState.CancelPending)
    {
    _myAccount.Cancel(new[] { _entryLong, _LongStopLossOrder, _LongProfitTargetOrder });
    }

    But that didn't work. RealTimeErrorHandling doesn't seem to work because I'm not coding a strategy.

    Any suggestions on how I can react to these errors without having an open position with no stop or target?

    Thank you!​

    #2
    Hello HappyTrader76,

    For a buy stop order, such as when exiting a short position or entering a long position, the stop price must be above the current ask price.
    For a sell stop order, such as when exiting a long position or entering a short position, the stop price must be below the current bid price.

    Order methods that submit / change stop orders where the stop price must be on the correct side of the ask or bid:Resolving the error

    There are different approaches to avoiding the invalid order price.

    For the examples below, consider a variable holding your calculated stop price. This could be a price from a custom calculation, or one obtained from an indicator. In these examples 100 will be used as a place holder.
    Code:
    stopPrice = 100; // ← price you have calculated to use as the stop price
    Using Math.Max() / Math.Min() to ensure the calculated stopPrice is above/below the ask/bid:
    Code:
    // ensure sell stop order is below the bid
    stopPrice = Math.Min(stopPrice, GetCurrentBid() - 1 * TickSize);
    ExitLongStopMarket(stopPrice);

    Code:
    // ensure buy stop order is above the ask
    stopPrice = Math.Max(stopPrice, GetCurrentAsk() + 1 * TickSize);
    ExitShortStopMarket(stopPrice);​
    Using a condition to submit a market order to exit immediately, instead of a stop order, if the stopPrice is ahead of the market:
    Code:
    // if calculated exit sell stopPrice is less than the bid use stopPrice for stop
    // otherwise exit long position immediately with a market order
    if (Position.MarketPosition == MarketPosition.Long)
    {
    // if the stopPrice value is a valid price, use the stopPrice
    if (stopPrice < GetCurrentBid())
    {
    ExitLongStopMarket(stopPrice);
    }
    // otherwise exit immediately with a market order
    else
    {
    ExitLong();
    }
    }
    
    // if calculated exit buy stopPrice is greater than the ask use stopPrice
    // other wise exit short position immediately with a market order
    if (Position.MarketPosition == MarketPosition.Short)
    {
    if (stopPrice > GetCurrentAsk())
    {
    ExitShortStopMarket(stopPrice);
    }
    else
    {
    ExitShort();
    }
    }​
    Chelsea B.NinjaTrader Customer Service

    Comment


      #3
      I'll give it a try. Thank you Chelsea!

      Comment


        #4
        The second approach using the if .. statement did the trick. Thank you!

        Followup question: If I flatten my account at the end of the day using _myAccount.Flatten(Instrument.All) that works great but my Addon should start trading again the next morning when I'm inside my defined time window. It worked well before I implemented the Flatten() method. Somehow the Flatten() method prevents my code from taking new trades.
        Is there something like a Reset that I have to perform to be able to start trading again?
        Thank you!

        Comment


          #5
          Hello HappyTrader76,

          Calling Account.Flatten() does not prevent new orders.

          Are you certain the script is not continuing to call Account.Flatten() and trying to flatten everytime an order is made?
          Are there any errors appearing on the Log tab of the Control Center?

          Attached is a simple test script.
          HappyTrader76AccountFlattenNewOrderTest_NT8.zip

          Below is a link to a video demonstrating that calling Account.Flatten() does not prevent new entries.



          Chelsea B.NinjaTrader Customer Service

          Comment


            #6
            Hello ChelseaB,
            Thank you for the hint. I'm trying to find out if that is the case. It could very well be. In my strategy I have a Timewindow method to make sure I only take trades during the two time windows:

            private bool TimeWindow()
            {
            return ((ToTime(Time[0]) >= StartTime1 && ToTime(Time[0]) < EndTime1) || (ToTime(Time[0]) >= StartTime2 && ToTime(Time[0]) < EndTime2));
            }

            Then in OnBarUpdate() I implemented this code:

            if (ToTime(Time[0]) >= EndTime2)
            {
            FlattenPositions();
            }

            private void FlattenPositions()
            {
            _myAccount.Flatten(Instrument.All);
            ​}

            I noticed that my Indicator (I'm using the Addon approach) who had an open position and was flattened didn't take trades the next day. The other indicators who didn't have any open positions took trades as they should. I'm not really sure what's wrong. I would think once the new day started ToTime(Time[0]) would be smaller than EndTime2 which is at the end of the trading day.
            Any suggestions?


            Comment


              #7
              Hello HappyTrader76,

              I would suggest that you add debugging prints to understand the behavior.

              Below is a link to support article on adding debugging prints to understand behavior.


              Print the time of the bar and all values compared in the condition and include labels.

              Save the output to a text file and attach to your next post.
              I will be happy to assist with analyzing the output.
              Chelsea B.NinjaTrader Customer Service

              Comment


                #8
                Hello ChelseaB
                Thank you for your efforts. From your video I could already improve something in my code. I solved the problem by only flattening if _myAccount.Positions.Counter != 0, and then I reset my Orders to null. Now it works just fine. Than you again for your help!

                Comment


                  #9
                  Hello ChelseaB,
                  Next up is handling multiple contracts or Partfills. to start working i started with orderstate.filled and couldn't get my stoploss to work anymore. I added a print and that showed that the code took the right path. The Log shows that the stoplossorder reached state="accepted" but never working. It seems that I don't get a stop price but I can't find the bug. Any help would be appreciated.
                  Attached Files

                  Comment


                    #10
                    I'm afraid the pictures didn't get sent properly... Click image for larger version

Name:	Screenshot 2024-06-18 135650.png
Views:	13
Size:	25.8 KB
ID:	1307617 Click image for larger version

Name:	Screenshot 2024-06-18 135712.png
Views:	12
Size:	9.5 KB
ID:	1307618 Click image for larger version

Name:	Screenshot 2024-06-18 134933.png
Views:	13
Size:	166.4 KB
ID:	1307619

                    Comment


                      #11
                      Hello HappyTrader76,

                      Possibly you want e.Order.OrderState?


                      Use prints to understand the behavior.

                      Print the e.Order.ToString() at the top of the <Account>.OrderUpdate event handler method.

                      One line above the condition that submits the order print all values in the condition with labels for each value and comparison operator.

                      Save the output by right-clicking the output window and selecting Save as.

                      Attach the output text file to your next post.


                      Depending on the broker the order may be Accepted or may be Working. Check for both if you are looking for a working state.

                      You may find the ProfitCaseStopTrailIndicatorExample example linked below helpful.
                      Chelsea B.NinjaTrader Customer Service

                      Comment

                      Latest Posts

                      Collapse

                      Topics Statistics Last Post
                      Started by David Hill, 07-18-2024, 07:41 AM
                      4 responses
                      24 views
                      0 likes
                      Last Post David Hill  
                      Started by aban1alpha, Today, 02:01 PM
                      0 responses
                      2 views
                      0 likes
                      Last Post aban1alpha  
                      Started by jaybedreamin, Today, 01:08 PM
                      0 responses
                      2 views
                      0 likes
                      Last Post jaybedreamin  
                      Started by Rheiverson, 07-18-2024, 04:28 PM
                      2 responses
                      19 views
                      0 likes
                      Last Post Rheiverson  
                      Started by p1kn1t, Today, 11:32 AM
                      0 responses
                      12 views
                      0 likes
                      Last Post p1kn1t
                      by p1kn1t
                       
                      Working...
                      X