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

AtmStrategyChangeStopTarget Error Handling

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

    AtmStrategyChangeStopTarget Error Handling

    In fast markets with Calculate.OnEachTick using AtmStrategyChangeStopTarget to change prices will occasionally throw an error such as:

    AtmStrategyChangeStopTarget method error: Order name 'Stop1' is invalid

    What is the Best Practice to handle these errors? Is there a callback such as is used in AtmStrategyCreate? I am not interest in taking Strategy live until all errors are fixed. And this is the last issue.

    #2
    Hello TAJTrades,

    Thanks for your notes.

    To clarify, how exactly are you calling AtmStrategyChangeStopTarget() in your script?

    It may be that you are attempting to call the order before it is in a working state.

    Could you confirm if the entry order has filled before this line of code is called?

    You should wait for 1 tick to pass after the entry fills before attempting to change the stop loss order. This is because the order needs to be created and submitted/accepted/working before attempting to change the order.​

    Here is a forum thread discussing the error which you might find helpful:


    You could view the SampleAtmStrategy reference sample by opening a New > NinjaScript Editor window, opening the Strategies folder, and double-clicking on the SampleAtmStrategy file.

    Atm Strategy Methods: https://ninjatrader.com/support/help...gy_methods.htm
    Using Atm Strategies: https://ninjatrader.com/support/help...strategies.htm
    Brandon H.NinjaTrader Customer Service

    Comment


      #3
      You should wait for 1 tick to pass after the entry fills before attempting to change the stop loss order. This is because the order needs to be created and submitted/accepted/working before attempting to change the order.​
      Fully aware of that.

      The problem seems to occur in very fast market conditions when the strategy reverses Long to Short or Short to Long.

      I am using:

      private void OnExecutionUpdate(object sender, ExecutionEventArgs e)
      private void OnOrderUpdate(object sender, OrderEventArgs e)

      Have bools :
      Stop1_State_Accepted set to true when 'Stop1' reaches e.Order.OrderState == OrderState.Accepted
      Target1_State_Working set to true when 'Target1' reaches e.Order.OrderState == OrderState.Working

      When those bools are true then I call AtmStrategyChangeStopTarget.

      This is a normal market OutputWindow. And it works flawlessly.
      Will post a screen shot of a fast market when it occurs. There is a huge difference.

      (5) 2024-01-24_11-30-11 - TechSmith Screencast - TechSmith Screencast

      Comment


        #4
        Hello TAJTrades,

        Thanks for your notes.

        This would depend on the state of the Atm Strategy when you call the AtmStrategyChangeStopTarget() method in the script and if the order exists or not.

        Atm Strategies do not work with the order events directly so that might be what is causing the error.

        You would need to make sure that you are using the Atm Strategy Methods for Atm Strategy Monitoring to check the Atm status before calling the method. Note the strategy is still only able to communicate what it wants to do with the Atm Strategy. Since Atm Strategies run outside of the strategy it is possible to have the orders filled or be canceled before the strategy calls AtmStrategyChangeStopTarget()

        From the 'Using Atm Strategies in Ninj' help guide page: "Script Executions from ATM Strategies will not have an impact on the hosting NinjaScript strategy position and PnL - the NinjaScript strategy hands off the execution aspects to the ATM, thus no monitoring via the regular NinjaScript strategy methods will take place (also applies to strategy performance tracking)"

        See the help guide documentation below for more information about Atm Strategy Monitoring.

        Using Atm Strategies in NinjaScripts: https://ninjatrader.com/support/help...strategies.htm
        Atm Strategy Methods: https://ninjatrader.com/support/help...gy_methods.htm
        GetAtmStrategyEntryOrderStatus(): https://ninjatrader.com/support/help...rderstatus.htm
        GetAtmStrategyMarketPosition(): https://ninjatrader.com/support/help...etposition.htm
        GetAtmStrategyStopTargetOrderStatus(): https://ninjatrader.com/support/help...rgetorders.htm
        Brandon H.NinjaTrader Customer Service

        Comment


          #5
          Been down that road. I used SampleATMReversal as a guide. When used on Calculate.OnEachTick and the Order Entry is FirstTickOfBar the same errors show up.

          My guess is that ATM Strategy Management and ATM Strategy Monitoring Methods are NOT doing a check for the correct Order State before attempting to retrieve data or change prices.

          The User Guide States for GetAtmStrategyEntryOrderStatus():

          Note: If the method can't find the specified order, an empty array is returned.

          Instead of returning an empty array it is throwing an error message.

          Can you confirm or reject my guess?

          In an effort to find a work around I tried using private void OnExecutionUpdate(object sender, ExecutionEventArgs e) and private void OnOrderUpdate(object sender, OrderEventArgs e).​



          BTW: SampleATMReversal works as expected when using Calculate.OnBarClose and using a Data Series that allows a few seconds for all processes to complete.











          Comment


            #6
            Hello TAJTrades,

            Thanks for your notes.

            That is correct, if GetAtmStrategyEntryOrderStatus() can't find the specified order, an empty array is returned as noted in the help guide.

            You could debug your script by printing out GetAtmStrategyEntryOrderStatus() similar to how it is used in the SampleAtmStrategy reference sample to see what the entry order status is evaluating to in your logic.

            Since the NinjaScript strategy hands off the execution aspects to the ATM, no monitoring via the regular NinjaScript strategy methods will take place. Atm Strategy Monitoring methods would have to be used in the script to monitor the entry, stop, and target order's status. There would be no workarounds to using Atm Strategy Methods for monitoring orders when using Atm Strategies in a NinjaScript.

            ​You would have to make sure to wait for at least 1 tick to pass after the entry fills before attempting to change the stop loss order or the error could occur. You could consider running your script using Calculate.OnPriceChange instead of Calculate.OnEachTick to see if that prevents the behavior from occurring.

            Or, you can choose to not use Atm Strategy Methods and instead use methods internal to NinjaScript Strategies.

            Brandon H.NinjaTrader Customer Service

            Comment


              #7
              That is correct, if GetAtmStrategyEntryOrderStatus() can't find the specified order, an empty array is returned as noted in the help guide.
              This is NOT CORRECT for

              string[,] orders = GetAtmStrategyStopTargetOrderStatus("Target1", "idValue");

              If "Target1" is mispelled "TArget1" it will throw an error NOT an empty array.
              If the Target Order Process has not processed the initial Target Order based on the AtmStrategyID, it will throw an error NOT return an empty array.

              Therefore, how would I check to make sure the Target1 Order has reached OrderState.Working? When it reaches that state then all the ATM Strategy Management and ATM Strategy Monitoring Methods work otherwise it throws an error.

              I will modify Sample Atm Strategy Reversal found here Sample Atm Strategy Reversal - NinjaTrader Ecosystem​ with some modifications for Calculate.OnEachTick. I will add in GetAtmStrategyEntryOrderStatus(string orderId) and GetAtmStrategyStopTargetOrderStatus to demonstrate this.

              Then perhaps, you can provide some guidance on how to make it work without errors.



              Comment


                #8
                I took the Sample Atm Strategy Reversal found Sample Atm Strategy Reversal - NinjaTrader Ecosystem​ and made some modifications for it to work on Calculate.OnEachTick. The modifications are well documented. I have included the .cs file and zip file to make life a little easier.

                Here is a screen grab to show the errors (5) 2024-01-25_09-24-25 - TechSmith Screencast - TechSmith Screencast​​​

                Would you please be so kind as to provide guidance on how to eliminate those errors. Maybe I am doing it wrong (that is always an option). My guess is that GetAtmStrategyEntryOrderStatus() and GetAtmStrategyStopTargetOrderStatus() are not testing to see it the orders have been Initialized before attempting to retrieve the data. This may be what is throwing the error. So, what is the fix?

                Thank you.

                Attached Files

                Comment


                  #9
                  Hello TAJTrades,

                  Thanks for your notes.

                  In the prints you added to the script, you are printing out isLongAtmStrategyCreated in both the long and short prints.

                  Print(string.Format(" isLongAtmStrategyCreated: {0,-5} longOrderId: {1,-32} longAtmId: {2,-32}", isLongAtmStrategyCreated, longOrderId.Length > 0 ? longOrderId : "string.empty", longAtmId.Length > 0 ? longAtmId : "string.empty"));

                  Print(string.Format(" isShortAtmStrategyCreated: {0,-5} shortOrderId: {1,-32} shortAtmId: {2,-32}", isLongAtmStrategyCreated, shortOrderId.Length > 0 ? shortOrderId : "string.empty", shortAtmId.Length > 0 ? shortAtmId : "string.empty"));


                  I modified the script to print isShortAtmStrategyCreated for your short order prints so that the correct value is being printed when testing.

                  ​That said, before calling GetAtmStrategyStopTargetOrderStatus() in your script you will need to make sure that you are checking that GetAtmStrategyMarketPosition() is returning long or short. This is to ensure that you are in a long or short market position before trying to get the stop/target order status in the script.

                  Further, you must have an ATM Strategy template saved with the name "AtmStrategyTemplate". Could you confirm you have created and saved an ATM Strategy template named "AtmStrategyTemplate"?

                  If so, does the ATM Strategy template named "AtmStrategyTemplate" have a target saved?

                  GetAtmStrategyMarketPosition(): https://ninjatrader.com/support/help...etposition.htm

                  ​​​​​​​
                  Brandon H.NinjaTrader Customer Service

                  Comment


                    #10

                    Could you confirm you have created and saved an ATM Strategy template named "AtmStrategyTemplate"?
                    If so, does the ATM Strategy template named "AtmStrategyTemplate" have a target saved?
                    Yes. Here is an image of the AtmStrategyTemplate. (5) 2024-01-25_17-10-00 - TechSmith Screencast - TechSmith Screencast

                    make sure that you are checking that GetAtmStrategyMarketPosition() is returning long or short.

                    Was not aware that this needed to be done. Will the add the check tonight and give it a go.

                    Comment


                      #11
                      Brandon, we are making progress. Added a check for Market Position and that cleaned up the Errors thrown when using GetAtmStrategyStopTargetOrderStatus. So, thank you very much. I believe my frustration prevented me from thinking clearly (aka: Colossal Case of Cranial Flatulence).
                      (5) 2024-01-26_07-31-55 - TechSmith Screencast - TechSmith Screencast

                      The last issue to solve still has me stumped. GetAtmStrategyEntryOrderStatus is still throwing errors. I went thru the Log and Trace files but that did not provide much information. When searching the files for Entry Order Id this is all I found. Not exactly providing clues as to what to try next.
                      (5) 2024-01-26_07-41-38 - TechSmith Screencast - TechSmith Screencast

                      Suggestions?

                      Thanks again for all your help.

                      Edit:
                      I will run the Strategy script using Data Series: ninzaRenko (Brick Size 4 and Trend Threshold 2) during the Core PCE Price Index m/m news at 8:30 am. Hopefully it will be crazy enough to stress test the strategy and see if any other errors pop up.

                      Last edited by TAJTrades; 01-26-2024, 07:13 AM.

                      Comment


                        #12
                        Crap, failed.

                        Market Position was Long but GetAtmStrategyStopTargetOrderStatus still throw an error.
                        (5) 2024-01-26_08-35-24 - TechSmith Screencast - TechSmith Screencast

                        Next idea?

                        Comment


                          #13
                          Hello TAJTrades,

                          Thanks for your notes.

                          I have tested the script further with my colleague and we have found that the "'Stop1' is invalid" and "'Target1' is invalid" error message would likely be unavoidable in this case.

                          1/29/2024 8:22:45 AM | 4917.25, 1, Filled
                          entryOrder State: string.Empty Price: 0.00 Qty: 0 longOrderId:
                          stopOrder State: Initialized Price: 0 Qty: 0 longAtmId: 035723d48ca747eb87cd464364138366
                          'GetAtmStrategyStopTargetOrderStatus' method error: Order name 'Target1' is invalid
                          entryOrder State: string.Empty Price: 0.00 Qty: 0 longOrderId:
                          stopOrder State: Accepted Price: 0 Qty: 0 longAtmId: 035723d48ca747eb87cd464364138366
                          targetOrder State: Working Price: 0 Qty: 0 longAtmId: 035723d48ca747eb87cd464364138366​


                          The Stop1 order is initialized and has not been submitted yet. The method is being called right at the same moment the entry order is filling and the stop and target have not had time to be submitted yet. Then, right after the stop and target go to a State of Accepted and then Working.

                          The only fix for this would be to wait a moment after the entry is showing as filled.

                          You could consider detecting if the entry is filled and the Position has changed to MarketPosition.Long, then in OnMarketData() save the time and wait for the next market update that is after 250ms

                          Or, you could consider using a timer to wait 250ms to 500ms for the orders to be constructed and submitted before checking the Stop and Target order status.

                          See this help guide page for more information about OnMarketData(): https://ninjatrader.com/support/help...marketdata.htm

                          See this help guide page for more information about TriggerCustomEvent() which has sample code showing how to implement a timer: https://ninjatrader.com/support/help...ustomevent.htm

                          As for the the entry error when calling GetAtmStrategyEntryOrderStatus, see the attached modified version of your script which has changes to the script to avoid the error. You could use a DiffChecker to compare your script with the attached script to see where differences in the code might be. To find a DiffChecker you could do a quick Google search for 'DiffChecker'.​
                          Attached Files
                          Brandon H.NinjaTrader Customer Service

                          Comment


                            #14
                            Thanks for your efforts.

                            The Stop1 order is initialized and has not been submitted yet. The method is being called right at the same moment the entry order is filling and the stop and target have not had time to be submitted yet. Then, right after the stop and target go to a State of Accepted and then Working.
                            I totally agree because I have noticed that issue happens in fast market conditions when there is very little time passing between ticks.

                            I am a little disappointed that GetAtmStrategyStopTargetOrderStatus could not do a check for OrderState before attempting to access that data. It could just return an empty array. Then on the next Tick start the process again.

                            I will look at your suggestions and try to implement them.


                            PS: Doing a search over the weekend on the forum it seems like I am not the only one who has encountered this situation. Maybe a review of the internal code to see if any changes could be made is needed.


                            Comment

                            Latest Posts

                            Collapse

                            Topics Statistics Last Post
                            Started by Option Whisperer, Today, 09:05 AM
                            0 responses
                            1 view
                            0 likes
                            Last Post Option Whisperer  
                            Started by cre8able, Yesterday, 01:16 PM
                            3 responses
                            11 views
                            0 likes
                            Last Post cre8able  
                            Started by Harry, 05-02-2018, 01:54 PM
                            10 responses
                            3,203 views
                            0 likes
                            Last Post tharton3  
                            Started by ChartTourist, Today, 08:22 AM
                            0 responses
                            6 views
                            0 likes
                            Last Post ChartTourist  
                            Started by LiamTwine, Today, 08:10 AM
                            0 responses
                            2 views
                            0 likes
                            Last Post LiamTwine  
                            Working...
                            X