Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

Two versions of OnExecutionUpdate

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

    Two versions of OnExecutionUpdate

    Getting this error when running this line:
    account.ExecutionUpdate += OnExecutionUpdate;

    protected override void OnExecutionUpdate(Execution execution, string executionId, double price, int quantity, MarketPosition marketPosition, string orderId, DateTime time) { .. }


    Click image for larger version

Name:	image.png
Views:	269
Size:	5.1 KB
ID:	1298947

    However, if I instead use this function in my Strategy:

    private void OnExecutionUpdate(object sender, ExecutionEventArgs e)

    Boom works. But the problem is this function is not helpful at all.

    The order IDs returned do not match that used in my AtmStrategyCreate call.​

    I am growing increasingly frustrated with the disjointedness of the documentation. I have no idea why there are two OnExecutionUpdate methods, and I am forced to use the one that won't provide the info I need.

    Appreciate any guide here. I basically am using SampleAtmStrategy as my template but I want to immediately change stop and TP as soon as the entry enters market.

    #2
    Hello firefoxforum12,

    Thanks for your post.

    If you are using Atm Strategy Methods in a custom NinjaScript, no monitoring via the regular NinjaScript strategy methods will take place. This is noted on the help guide documentation linked below.

    From the help guide: "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)"

    Using Atm Strategies in NinjaScript: https://ninjatrader.com/support/help...strategies.htm

    To monitor orders placed from a NinjaScript strategy using an Atm Strategy Template, you must use Atm Strategy Methods.

    For example, GetAtmStrategyStopTargetOrderStatus() would be used to get information about the stops and targets. GetAtmStrategyEntryOrderStatus() would get used to get information about the entry order.

    GetAtmStrategyStopTargetOrderStatus(): https://ninjatrader.com/support/help...rgetorders.htm
    GetAtmStrategyEntryOrderStatus(): https://ninjatrader.com/support/help...rderstatus.htm
    Atm Strategy Methods: https://ninjatrader.com/support/help...gy_methods.htm

    Changing a stop or target would be done using the AtmStrategyChangeStopTarget() method.

    AtmStrategyChangeStopTarget(): https://ninjatrader.com/support/help...stoptarget.htm

    To see an example of monitoring orders in a NinjaScript that uses Atm Strategy Methods, you could view the SampleAtmStrategy sample that comes with NinjaTrader. To view the script, open a New > NinjaScript Editor window, open the Strategies folder, and double-click on the SampleAtmStrategy file.

    If you want to track orders in OnExecutionUpdate(), you would need to modify your strategy to use Enter and Exit methods for entry orders, stops, and targets instead of Atm Strategy Methods.
    <span class="name">Brandon H.</span><span class="title">NinjaTrader Customer Service</span><iframe name="sig" id="sigFrame" src="/support/forum/core/clientscript/Signature/signature.php" frameborder="0" border="0" cellspacing="0" style="border-style: none;width: 100%; height: 120px;"></iframe>

    Comment


      #3
      Thanks for the response. I 100% want to use ATM strategy methods for safety, but that SampleAtmStrategy example only uses OnBarUpdate() which is super high risk. Price could wildly move... and I noted this just now... which seems truly bizzaire to me... having to wait for next OnBarUpdate()!




      I will test out GetAtmStrategyStopTargetOrderStatus perhaps by looping it and report back​

      Comment


        #4
        Also I have noticed Ninja Trader after pressing F5 enough times, starts seemingly Ignoring my code changes, no amount of chart window closing and reloading solves the issue. Is doing:

        account.SelectedAccount.ExecutionUpdate -= OnExecutionUpdate

        strictly necessary or is there another way I can avoid weird bugs with running strategies (while developing)?

        Comment


          #5
          Hello firefoxforum12,

          Thanks for your notes.

          If you are submitting orders using Atm Strategy Templates and want to track executions, you could use the Account.ExecutionUpdate for Atm submitted orders.

          Note that NinjaTrader has OnExecutionUpdate() which is specific to strategies and there is Account.ExecutionUpdate which is different.

          You should use Account.ExecutionUpdate for Atm Strategy submitted orders along with the OnExecutionUpdate() method below.

          private void OnExecutionUpdate(object sender, ExecutionEventArgs e)
          {
          ​}


          Note the The execution order IDs will be the same as the Orders tab of the Control Center.

          Make sure to unsubscribe to ExecutionUpdate events in OnStateChange() when the State is State.Terminated

          See this help guide documentation for more information on Account.ExecutionUpdate and sample code: https://ninjatrader.com/support/help...tionupdate.htm

          See this help guide documentation for more information about Executions: https://ninjatrader.com/support/help...executions.htm

          After making changes to the script and compiling, remove the strategy from the chart window and then re-add the strategy to the chart to ensure changes take effect.
          Last edited by NinjaTrader_BrandonH; 04-09-2024, 08:47 AM.
          <span class="name">Brandon H.</span><span class="title">NinjaTrader Customer Service</span><iframe name="sig" id="sigFrame" src="/support/forum/core/clientscript/Signature/signature.php" frameborder="0" border="0" cellspacing="0" style="border-style: none;width: 100%; height: 120px;"></iframe>

          Comment


            #6
            Thank you for the response. I apologise but I cannot understand what you mean by Account.ExecutionUpdate. Is that not already what I am doing?

            Click image for larger version  Name:	image.png Views:	0 Size:	6.8 KB ID:	1298978


            I am doing something like this in my code in general:


            Code:
            
            
            
            atmStrategyId = GetAtmStrategyUniqueId();
            atmStrategyOrderId = GetAtmStrategyUniqueId();
            
            AtmStrategyCreate(OrderAction.Buy, OrderType.StopMarket, 0, entryPrice , TimeInForce.Day,
            atmStrategyOrderId, "myatm", atmStrategyId, (atmCallbackErrorCode, atmCallbackId) => {
            // If I make strat name "" I get error: AtmStrategyCreate method error: Strategy template name parameter missing
            
            // checks that the call back is returned for the current atmStrategyId stored
            if (atmCallbackId == atmStrategyId)
            {
            // check the atm call back for any error codes
            if (atmCallbackErrorCode == Cbi.ErrorCode.NoError)
            {
            // if no error, set private bool to true to indicate the atm strategy is created
            isAtmStrategyCreated = true;
            Print("No ATM error. Error code: " + atmCallbackErrorCode);
            }
            }​
            ​
            
            
            private void OnExecutionUpdate(object sender, ExecutionEventArgs e)
            {
            
            // e.OrderId NEVER MATCHES atmStrategyOrderId above.  <====
            
            
            This code below dies here because for one reason or another I cannot change the new stop and TP of my ATM because I can never find it...
            
            Thats my core problem at the moment. This code below is getting murky its 1am for me I'm in pain sir.
            
            // DIES HERE WITH: AtmStrategyChangeStopTarget' method error: Order name 'Stop1' is invalid
            string[,] orders = GetAtmStrategyStopTargetOrderStatus("Stop1", atmStrategyId);
            if (orders.Length > 0)
            {
            for (int i = 0; i < orders.GetLength(0); i++)
            {
            Print("Average fill price is " + orders[i, 0].ToString());
            Print("Filled amount is " + orders[i, 1].ToString());
            Print("Current state is " + orders[i, 2].ToString());
            }
            
            //
            // IT NEVER GETS HERE - I am trying to do this below.
            //
            if (atmStrategyOrderId.Length > 0 )//&& GetAtmStrategyMarketPosition(atmStrategyId) != MarketPosition.Flat)// && orderId == atmStrategyOrderId)
            {
            
            bool worked = AtmStrategyChangeStopTarget(0, entryPrice - 40, "Stop1", atmStrategyId);
            Print("ATM STOP CHANGED 40 TICKS: " + worked);
            worked = AtmStrategyChangeStopTarget(entryPrice + 50*TickSize, 0, "Target1", atmStrategyId);
            Print("ATM STOP CHANGED 50 TICKS: " + worked);
            atmStrategyOrderId = ""; // never enter this IF statement again
            }



            I would GREATLY appreciate help as to what the pain I am receiving is.

            SUMMARY:
            I am looking at this code snippet I am pasting and its clear I am mentally cooked now. Basically I dont know how to Identify when my ATM entry has executed on the market, because e.orderId in private void OnExecutionUpdate(object sender, ExecutionEventArgs e)

            never matches atmStrategyOrderId and if I run
            GetAtmStrategyStopTargetOrderStatus("Stop1", atmStrategyId) it just fails quietly.

            Note my ATM entry and stop and TP do execute on Ninja Trader and are visible on the chart window, I just cannot change the stop and TP to what I want via code... because the mechanisms I am aware of don't tell me its occurred and/or never match any details from my AtmStrategyCreate() call above.

            Appreciate your help. Apologies if this is a bit murky but hopefully making sense...
            Last edited by firefoxforum12; 04-09-2024, 09:12 AM.

            Comment


              #7
              Hello firefoxforum12,

              Thanks for your notes.

              Yes, that would be the correct OnExecutionUpdate() event-driven method for the Account.ExecutionUpdate events.

              You could subscribe to account level OrderUpdate and ExecutionUpdate from the Account object of the NinjaScript strategy, and you can see all of these events from the account.

              You can then observe the OrderUpdate events on the account to find the ATM strategy Entry order that matches the instrument, price, and order type you have submitted from the NinjaScript strategy. Once you have that Order object, you can check for its execution in the account level OnExecutionUpdate() event method, and see if the executing order matches the Order object you captured.

              In OnExecutionUpdate() you could print out e.OrderId to get the order ID of the execution that occurs and print out e.Execution.Order.Name to get the name of the order being executed. This e.OrderId matches the ID column in the Orders tab of the Control Center and e.Execution.Order.Name matched the Name column on the Orders tab of the Control Center.

              Note that an orderId is not the same thing as the atmStrategyId.

              atmStrategyId = GetAtmStrategyUniqueId();
              orderId = GetAtmStrategyUniqueId();​

              The error "Order name 'Stop1' is invalid" indicates that the stop order has not yet been submitted at the time you are accessing it.

              Before trying to change the stop/target, you would need to ensure that you are checking that the entry order has filled and the stop/target is in an OrderState of Accepted/Working.

              You may want to try using OrderUpdate events and OnOrderUpdate() to change the stop order instead.

              Attached is a simple example script demonstrating how to change the Stop1 order from the Atm Strategy Template in OnOrderUpdate() the moment the stop is submitted.

              When testing this we can see that when the Stop1 order reaches the OrderState of Accepted, a change is submitted for the Stop1 order to move it to a different price.

              2024-04-09 13:00:23:189|1|32|Order='e66cb7c69ed9443d87a546773 db29b8b/Sim101' Name='Stop1' New state='Accepted' Instrument='ES 06-24' Action='Sell' Limit price=0 Stop price=5229 Quantity=1 Type='Stop Market' Time in force=GTC Oco='3c915a6753ab4225bf2242755b99404e' Filled=0 Fill price=0 Error='No error' Native error=''

              2024-04-09 13:00:23:189|1|32|Order='e66cb7c69ed9443d87a546773 db29b8b/Sim101' Name='Stop1' New state='Change submitted' Instrument='ES 06-24' Action='Sell' Limit price=0 Stop price=5232 Quantity=1 Type='Stop Market' Time in force=GTC Oco='3c915a6753ab4225bf2242755b99404e' Filled=0 Fill price=0 Error='No error' Native error=''

              2024-04-09 13:00:23:293|1|32|Order='e66cb7c69ed9443d87a546773 db29b8b/Sim101' Name='Stop1' New state='Accepted' Instrument='ES 06-24' Action='Sell' Limit price=0 Stop price=5232 Quantity=1 Type='Stop Market' Time in force=GTC Oco='3c915a6753ab4225bf2242755b99404e' Filled=0 Fill price=0 Error='No error' Native error=''


              OrderUpdate: https://ninjatrader.com/support/help...rderupdate.htm
              Orders: https://ninjatrader.com/support/help...rs_account.htm
              ExecutionUpdate: https://ninjatrader.com/support/help...tionupdate.htm
              Executions: https://ninjatrader.com/support/help...executions.htm
              Attached Files
              Last edited by NinjaTrader_BrandonH; 04-09-2024, 11:09 AM.
              <span class="name">Brandon H.</span><span class="title">NinjaTrader Customer Service</span><iframe name="sig" id="sigFrame" src="/support/forum/core/clientscript/Signature/signature.php" frameborder="0" border="0" cellspacing="0" style="border-style: none;width: 100%; height: 120px;"></iframe>

              Comment


                #8
                Thank you for your help! That OnOrderUpdate() solution really made all the difference. I had no idea we had to wait for OrderState.Accepted to be there.

                I managed to get a long ATM strategy to enter with TP and stop executed upon entry firing onto market. However there is a key problem now.

                The TP and Stop are now OCO orders and are not "connected" to my Entry it appears, upon going live. And if I go short the market in another ATM strategy and that entry manages to enter the market, it will kill the open long position. marooning me with a TP and stop that still exist for the long, and now I have a tp and stop for the short position that "cancelled out" the long position!



                Click image for larger version

Name:	image.png
Views:	327
Size:	19.3 KB
ID:	1299105

                They should both be co-existing in the market, both open. I know this is possible because you can do it via the Chart Window. See below strategy with sell limit and buy limit at same time. When they run they will exist as separate units. If one is closed, their correspending TP and stop will also disapear. Whereas above via my code they still exist.

                Click image for larger version

Name:	image.png
Views:	243
Size:	36.2 KB
ID:	1299106

                Appreciate any insight so either when hedging one doesnt cancel the other side, OR at least the TP and stop of the killed positions are REMOVED immediately.

                Thanks

                Comment


                  #9
                  Hello firefoxforum12,

                  Thanks for your notes.

                  This would be the expected behavior when placing orders with a NinjaScript strategy.

                  If the strategy is in a Long position and then the strategy submits an order to enter a Short position, the Long position will be closed.

                  It is not supported to submit orders to be in a Long position and a Short position at the same time on the same account/instrument combination.

                  Further, NinjaTrader does not support hedging.

                  To truly have an open long account position and an open short account position on the same instrument (instead of a net flat account position), this would require placing trades to two different accounts. One account to hold a long position, the other account to hold a short position.

                  Here is a forum thread post that discusses this topic: https://forum.ninjatrader.com/forum/...t792660​
                  <span class="name">Brandon H.</span><span class="title">NinjaTrader Customer Service</span><iframe name="sig" id="sigFrame" src="/support/forum/core/clientscript/Signature/signature.php" frameborder="0" border="0" cellspacing="0" style="border-style: none;width: 100%; height: 120px;"></iframe>

                  Comment


                    #10
                    NinjaTrader 100% supports hedging. I've done it. I noted SIM101 it does not work too good though.



                    I guess my question in this case is: How can I ensure my OCO orders are KILLED if the main entry is closed without one of the OCO orders firing? As in via ATM taking care of it automatically just like a normal ATM strategy would.


                    Thanks again for your help
                    Last edited by firefoxforum12; 04-10-2024, 05:46 PM.

                    Comment


                      #11
                      NOTE: I just tested that if I close my ATM created via the Gui Sell/Buy Market button, the OCO orders + the main position disapear.

                      But if I run this:

                      Code:
                      Order mar****rder = acc.SelectedAccount.CreateOrder(Instrument, OrderAction.Sell / same for SellShort, OrderType.Market, TimeInForce.Day, 1, 0, 0, string.Empty, "get out test", null);
                      acc.SelectedAccount.Submit(new[] { mar****rder });
                      It closes the main position but orphans the OCO brackets!

                      There are a lot of tricks going on in the GUI that are not reflected in our ability to utilise in the code!?​ Growing quite frustrated with the limitations / work-arounds of ATM strategies via Ninjascript I must say. It does not reflect what the GUI is doing.

                      It's only your team on the forum here keeping me going so I appreciate you.

                      Could you kindly review my Q in this post? https://forum.ninjatrader.com/forum/...16#post1299216

                      Thank you
                      Last edited by firefoxforum12; 04-10-2024, 07:59 PM.

                      Comment


                        #12
                        Hello, I discovered AtmStrategyClose(atmLongStrategyId) seems to help, did something strange I am investigating (because I market exited an order that was long, running this tried to kill my position I already killed, so actually sold short - but it did kill my OCO orders which is positive). Technically AtmStrategyClose() should of been intelligent enough to detect there was no active position in the ATM still around to kill (imo but take with grain of salt). When I run AtmStrategyClose() as the sole mechanism to get out of an ATM strategy it works well.

                        Guys please my feedback since developing on Ninjascript for past 2 weeks is: The documentation is disjointed, and there is not a single clear example of:
                        1. Creating an ATM with tp and stop that you can then cancel entirely upon whatever event. Not on OnBarUpdate() that is a ridiculous example no one's going to wait on say the 1H candle to close to then run cancelling of an order, especially if something crazy happens at lets say minute 39 of the 1hour candle. Need a far better real-life example.
                        2. The usage of GetAtmStrategyMarketPosition(atmLongStrategyId)) is used in examples where certain events have not occurred and therefore this actually just crashes NinjaTrader. There is an example of this in OnBarUpdate() event where it does work, but again this is a fairy tale example need a real world example where this data can be extracted the second its possible.
                        3. Documentation needs review to make less disjointed and the samples need a concise review with a real world application such as point

                        Thanks
                        Last edited by firefoxforum12; 04-10-2024, 08:58 PM.

                        Comment


                          #13
                          Hello firefoxforum12,

                          Thanks for your notes.​

                          When submitting orders from a NinjaScript strategy, you cannot be in a long position and a short position on the same instrument/account at the same time. Accounts cannot go long and short at the same time. As previously mentioned, if you are in a long position and you placed a short order, you will end up in a flat position. This is noted on the forum thread linked below.


                          You could submit an entry order to enter a long position and an entry order to enter a short position that are tied by OCO so that if the entry order to enter a long position is filled, the entry order to enter a short position is canceled. This would require using the Unmanaged Approach for order management.

                          Unmanaged Approach: https://ninjatrader.com/support/help...d_approach.htm

                          Here is a reference sample demonstrating this also: https://forum.ninjatrader.com/forum/...49#post1164449

                          If you are wanting to close an ATM Strategy position, you should use AtmStrategyClose().

                          AtmStrategyClose(): https://ninjatrader.com/support/help...ategyclose.htm

                          If you want to cancel an entry order submitted by AtmStrategyCreate(), you would use AtmStrategyCancelEntryOrder().



                          Atm Strategy Method should be used if you are wanting to modify, cancel, or close a position.

                          Atm Strategy Methods: https://ninjatrader.com/support/help...gy_methods.htm

                          For important information about manually closing an ATM Strategy position, see the "!!! IMPORTANT: Manually Closing an ATM Strategy from an Order Entry Window such as the SuperDOM" section of this help guide page: https://ninjatrader.com/support/help...strategies.htm

                          If you want more control over your order management you could consider using the Managed Approach or Unmanaged Approach instead of using Atm Strategy Methods.
                          Last edited by NinjaTrader_BrandonH; 04-11-2024, 08:11 AM.
                          <span class="name">Brandon H.</span><span class="title">NinjaTrader Customer Service</span><iframe name="sig" id="sigFrame" src="/support/forum/core/clientscript/Signature/signature.php" frameborder="0" border="0" cellspacing="0" style="border-style: none;width: 100%; height: 120px;"></iframe>

                          Comment

                          Latest Posts

                          Collapse

                          Topics Statistics Last Post
                          Started by NullPointStrategies, Today, 05:17 AM
                          0 responses
                          52 views
                          0 likes
                          Last Post NullPointStrategies  
                          Started by argusthome, 03-08-2026, 10:06 AM
                          0 responses
                          130 views
                          0 likes
                          Last Post argusthome  
                          Started by NabilKhattabi, 03-06-2026, 11:18 AM
                          0 responses
                          70 views
                          0 likes
                          Last Post NabilKhattabi  
                          Started by Deep42, 03-06-2026, 12:28 AM
                          0 responses
                          44 views
                          0 likes
                          Last Post Deep42
                          by Deep42
                           
                          Started by TheRealMorford, 03-05-2026, 06:15 PM
                          0 responses
                          49 views
                          0 likes
                          Last Post TheRealMorford  
                          Working...
                          X