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

Samples of OnExecutionUpdate - trying to Reverse trade on some of my stops

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

    Samples of OnExecutionUpdate - trying to Reverse trade on some of my stops

    Its not easy to find real examples how someone has successfully used "OnExecutionUpdate". Just looking for some samples to work with.

    Trying to have some of my stops reverse when a "SetStopLoss" triggers.

    Say this executes:
    SetStopLoss("Long", CalculationMode.Price, Position.AveragePrice * 1.01, true); //Stop if up more than 1% but fades back to 1%

    Now I want to Go Short immediately after this executes - thus doing the same thing as "Reverse On Stop" does.

    Thanks as always in advance for the help.

    #2
    Hi, thanks for posting. We have an example on advanced order management here:



    This example shows how to work with OnOrderUpdate/OnExecutionUpdate and how to properly assign orders to Order objects so they can be detected with their state in OnOrderUpdate/OnExecutionUpdate.

    Kind regards.
    Chris L.NinjaTrader Customer Service

    Comment


      #3
      Thanks for this page. I already saw it. I am looking for a more complex example that handles more than one order or stop Execution to reverse the trade?

      I currently have 6 Named Long Entries and 6 Named Short Entries (12 total entries).....with over 18 different stops per Entry. So I am looking for an "OnExecutionUpdate" example with multiple entries/multiple stops. Of the 18 stops per side.....I want to target only 3 or 4 of those stops for reversal entries.

      Code PARTIAL Snippet example (please NOTE I am not including all the code or brackets below - its just example to get the gist of what I am looking for)

      EnterLong(QuantitySize, "Long");
      EnterLong(QuantitySize, "Long2");
      EnterLong(QuantitySize, "Long3");

      if (Close[0] > ......
      SetStopLoss("Long", CalculationMode.Price, Position.AveragePrice * 1.005, true);
      SetStopLoss("Long1", CalculationMode.Price, Position.AveragePrice * 1.005, true);
      SetStopLoss("Long2", CalculationMode.Price, Position.AveragePrice * 1.005, true);

      if (Close[0] > ......
      SetStopLoss("Long", CalculationMode.Price, Position.AveragePrice * 1.01, true);
      //Reverse trade onExecutionUpdate of these stops only
      ​​​​​​​SetStopLoss("Long1", CalculationMode.Price, Position.AveragePrice * 1.01, true); //Reverse trade onExecutionUpdate of these stops only
      ​​​​​​​SetStopLoss("Long2", CalculationMode.Price, Position.AveragePrice * 1.01, true); //Reverse trade onExecutionUpdate of these stops only

      Comment


        #4
        Hi BigT4X, I do not know of any other examples that demonstrate. I would recommend making a test strategy that only does 1 order, and get that working for reversals. You are going to need to use the technique in the above example where you use Exit orders rather than SetStopLoss because you can give Exit orders signal names that can be detected in OnExecutionUpdate. When the order reaches the filled state, submit a reversal order.

        Kind regards,
        -ChrisL
        Chris L.NinjaTrader Customer Service

        Comment


          #5
          Fair enough.....that helps.

          If I wanted for all the "Stop Losses" (so all 18 stops x 12 entries).....to do reversal trades once stopped out.......would I still need to use "Exit Orders signal names"? Or could I just use the 12 Entry Signal Names only to identify them?

          Or some sort of "If Any Long gets stopped" go short logic (and vice versa). Just looking for a way to simplify it.

          Something like this perhaps should work? (I did not include the resetting of counters, nulls or the Short side).....I think it misses an identifier for just Stoploss exits.....the below will go the opposite way on every exit. Any suggestions?

          protected override void OnOrderUpdate(Order order, double limitPrice, double stopPrice, int quantity, int filled, double averageFillPrice, OrderState orderState, DateTime time, ErrorCode error, string nativeError)
          {
          if (order.Name == "Long1" || order.Name == "Long2" || order.Name == "Long3")
          {
          entryLongOrder = order;
          }
          }


          protected override void OnExecutionUpdate(Execution execution, string executionId, double price, int quantity, MarketPosition marketPosition, string orderId, DateTime time)
          {
          if (entryLongOrder != null && entryLongOrder == execution.Order)
          {
          EnterShort(QuantitySize, "ShortStopReverse");
          }
          }
          Last edited by BigT4X; 07-30-2022, 07:10 PM.

          Comment


            #6
            Hi, This should work fine. Please do test it out on the Sim101 account/replay connection to confirm:

            Chris L.NinjaTrader Customer Service

            Comment


              #7
              Sorry for the long message but less verbiage seems to cause more problems than help..........please assist.

              This code above I suggested causes the Long Trade to exit immediately upon Entry, rather than only on Long Exits. It goes Short immediately after a Long. If it only went short on a Long Exit that would be better so that I could then isolate just the stop exits next.

              My goal here is to take an Opposite trade ONLY on Stop Loss Exits. Not go the opposite way immediately upon Entry, not on Profit exits, not on any other exits (Time based ones, etc). Enter the Short trade only if a Long Stop loss fills and vice versa to enter the Long trade only if a Short Stop loss fills. A simple ask but apparently not so easy to code.

              Unfortunately the "SampleOnOrderUpdate" example provided does not handle Longs and Shorts separately. I need it separate to handle the multiple exit types I have. I have tried many various ways, looked at the log using trace orders and prints and simplified but I am clearly not doing something right that is probably really simple.

              Here is my current Update/Execution code. I know it does not isolate the stops specifically but I thought it would at least isolate all Long exits but its not doing that either:

              protected override void OnOrderUpdate(Order order, double limitPrice, double stopPrice, int quantity, int filled, double averageFillPrice, OrderState orderState, DateTime time, ErrorCode error, string nativeError)
              {
              if (order.Name == "Long1" || order.Name == "Long2" || order.Name == "Long3" || order.Name == "Long4" || order.Name == "Long5" || order.Name == "Long6")
              {
              EntryLongOrder = order;
              }

              if (order.OrderState == OrderState.Cancelled)
              {
              EntryLongOrder = null;
              StopLongOrder = null;
              }
              }

              protected override void OnExecutionUpdate(Execution execution, string executionId, double price, int quantity, MarketPosition marketPosition, string orderId, DateTime time)
              {
              if (EntryLongOrder != null && EntryLongOrder == execution.Order)
              {
              EnterShort(QuantitySize, "ShortReverseOnLongStop");
              EntryLongOrder = null;
              StopLongOrder = null;
              }
              }


              You can see why its entering a Short immediately after a long. I need some further logic to isolate a Long Stop Exit. Adding "OrderState.Filled" does not help.

              My stops are are all under OnBarUpdate(). Do I need to put all the Stop logic into OnOrderUpdate or OnExecutionUpdate.....keeping in mind I am manually trailing stops 10 times at least?

              Do I need to add some sort of "OrderState.Cancelled" logic of some kind?


              I have another issue also with StopLongOrder = ExitLongStopMarket(0, true, QuantitySize, Position.AveragePrice * 1.002, "LongStops1", "Long1"); where the Stop orders are not retained after 1 bar....so I am currently just sticking to SetStopLoss("Long1", CalculationMode.Price, Position.AveragePrice * 1.002, true); format for now for my stops. Do the ExitLongStopMarket orders need to be in OnOrderUpdate instead? I am trying to get over one hurdle at a time but perhaps this is also part of one big problem?

              OR should I just be using "EnterShortStopMarket" instead of using SetStopLoss("Long1"...) or StopLongOrder = ExitLongStopMarket(0, true....)? Does that need to be in OnOrderUpdate instead? So far only SetStopLoss keeps the stop.....the other change it for one bar and then change to the default after one bar.

              Sample of one of my stop levels

              if (LongStop1 == true && LongStop2 == false)
              {
              if (High[0] > Position.AveragePrice * 1.0045)
              {

              //With the // removed....this code does not keep the stop after 1 bar - it reverts
              //StopLongOrder = ExitLongStopMarket(0, true, QuantitySize, Position.AveragePrice * 1.002, "LongStops2", "Long1");
              //StopLongOrder = ExitLongStopMarket(0, true, QuantitySize, Position.AveragePrice * 1.002, "LongStops2", "Long2");
              //StopLongOrder = ExitLongStopMarket(0, true, QuantitySize, Position.AveragePrice * 1.002, "LongStops2", "Long3");
              //StopLongOrder = ExitLongStopMarket(0, true, QuantitySize, Position.AveragePrice * 1.002, "LongStops2", "Long4");
              //StopLongOrder = ExitLongStopMarket(0, true, QuantitySize, Position.AveragePrice * 1.002, "LongStops2", "Long5");
              //StopLongOrder = ExitLongStopMarket(0, true, QuantitySize, Position.AveragePrice * 1.002, "LongStops2", "Long6");


              //With the // removed.....this code keeps the stop but does not reverse the trade on the Stop loss - the objective of this post
              //SetStopLoss("Long1", CalculationMode.Price, Position.AveragePrice * 1.002, true);
              //SetStopLoss("Long2", CalculationMode.Price, Position.AveragePrice * 1.002, true);
              //SetStopLoss("Long3", CalculationMode.Price, Position.AveragePrice * 1.002, true);
              //SetStopLoss("Long4", CalculationMode.Price, Position.AveragePrice * 1.002, true);
              //SetStopLoss("Long5", CalculationMode.Price, Position.AveragePrice * 1.002, true);
              //SetStopLoss("Long6", CalculationMode.Price, Position.AveragePrice * 1.002, true);


              //This does not go short because it does not keep the order after 1 bar
              EnterShortStopMarket(0, true, QuantitySize, Position.AveragePrice * 1.002, "ShortReverseOnLongStop");
              LongStop2 = true;
              }
              }


              I appreciate any help from anyone.
              Last edited by BigT4X; 07-30-2022, 09:53 PM.

              Comment


                #8
                FYI...this logic also does not work....one of many I tried:

                protected override void OnOrderUpdate(Order order, double limitPrice, double stopPrice, int quantity, int filled, double averageFillPrice, OrderState orderState, DateTime time, ErrorCode error, string nativeError)
                {
                if (order.Name == "Long1" || order.Name == "Long2" || order.Name == "Long3" || order.Name == "Long4" || order.Name == "Long5" || order.Name == "Long6")
                {
                EntryLongOrder = order;
                }


                //With or Without this "LongStops" logic
                if (order.Name == "LongStops1" || order.Name == "LongStops2" || order.Name == "LongStops3" || order.Name == "LongStops4" || order.Name == "LongStops5" || order.Name == "LongStops6" || order.Name == "LongStops7" || order.Name == "LongStops8" || order.Name == "LongStops9" || order.Name == "LongStops10" )
                {
                StopLongOrder = order;
                }

                if (order.OrderState == OrderState.Cancelled)
                {
                EntryLongOrder = null;
                StopLongOrder = null;
                }
                }

                protected override void OnExecutionUpdate(Execution execution, string executionId, double price, int quantity, MarketPosition marketPosition, string orderId, DateTime time)
                {
                if (StopLongOrder != null && StopLongOrder == execution.Order)
                {
                EnterShort(QuantitySize, "ShortReverseOnLongStop");
                EntryLongOrder = null;
                StopLongOrder = null;
                }
                }

                Comment


                  #9
                  Hi, I apologize, I will not be able to make any suggestions for custom scripts or help with debugging. Other members of the community will need to pitch in to help develop a custom script with this amount of complexity, or, you can hire a developer from the NinjaTrader Ecosystem website in the "programmers" section.

                  Kind regards.
                  Chris L.NinjaTrader Customer Service

                  Comment


                    #10
                    Thanks Chris

                    To be clear I was not asking anyone to help debug. I gave extra information to help give more context. I am very sorry that made it more confusing. Its a balance to find between sharing not enough info and too much info.

                    In the end (and the first post) all I am looking for a working example of how to "Reverse on a Stop" using Strategy code. Something should be documented somewhere in the Guide to do this rather simple action in a Strategy (mimic what you can do on a Manual ATM order).....when an order hits a stop....stop out (exit) and immediately enter the opposite direction. Unfortunately the "SampleOnOrderUpdate" code example provided does not handle Longs and Shorts in the same code or separately for cases when a person is using multiple Exit types.

                    If anyone has a valid working example "Reverse trade after Execution of a Stop" please feel free to share.

                    Comment


                      #11
                      Hello BigT4X, could you make it work? I am trying to do the same with my strategy... I dont find anything... and I would like to ask if it's posible to find the code for the reverse direction order in the ATM...

                      Thanks!!!

                      Comment


                        #12
                        Originally posted by BigT4X View Post
                        Thanks Chris

                        To be clear I was not asking anyone to help debug. I gave extra information to help give more context. I am very sorry that made it more confusing. Its a balance to find between sharing not enough info and too much info.

                        In the end (and the first post) all I am looking for a working example of how to "Reverse on a Stop" using Strategy code. Something should be documented somewhere in the Guide to do this rather simple action in a Strategy (mimic what you can do on a Manual ATM order).....when an order hits a stop....stop out (exit) and immediately enter the opposite direction. Unfortunately the "SampleOnOrderUpdate" code example provided does not handle Longs and Shorts in the same code or separately for cases when a person is using multiple Exit types.

                        If anyone has a valid working example "Reverse trade after Execution of a Stop" please feel free to share.
                        I found a simple solution to this by using Multi Charts. No need to go through the hoops
                        in NT8 while trying to reverse with a stop. If a stop entry is filled, MC
                        will cancel opposite position and it's stop and target order. NT8 does
                        not have a detailed example for sure. Had to waste my time coding it
                        for NT8.

                        Maybe take a vote on it if NT8 can makes these changes internally. Did either
                        of you figure it out? I have that stop entry reversal coded if you need it.

                        Comment


                          #13
                          Hi Trader17,

                          Maybe I can give it a try and code it for NT8, could you post the code so I can check it?

                          Thanks!

                          TN

                          Comment


                            #14
                            Originally posted by tradingnasdaqprueba View Post
                            Hi Trader17,

                            Maybe I can give it a try and code it for NT8, could you post the code so I can check it?

                            Thanks!

                            TN
                            tradingnasdaqprueba PM me. Have you tried your code in a strategy yet? What exactly are you trying to achieve?

                            Comment


                              #15
                              Originally posted by BigT4X View Post
                              FYI...this logic also does not work....one of many I tried:

                              protected override void OnOrderUpdate(Order order, double limitPrice, double stopPrice, int quantity, int filled, double averageFillPrice, OrderState orderState, DateTime time, ErrorCode error, string nativeError)
                              {
                              if (order.Name == "Long1" || order.Name == "Long2" || order.Name == "Long3" || order.Name == "Long4" || order.Name == "Long5" || order.Name == "Long6")
                              {
                              EntryLongOrder = order;
                              }


                              //With or Without this "LongStops" logic
                              if (order.Name == "LongStops1" || order.Name == "LongStops2" || order.Name == "LongStops3" || order.Name == "LongStops4" || order.Name == "LongStops5" || order.Name == "LongStops6" || order.Name == "LongStops7" || order.Name == "LongStops8" || order.Name == "LongStops9" || order.Name == "LongStops10" )
                              {
                              StopLongOrder = order;
                              }

                              if (order.OrderState == OrderState.Cancelled)
                              {
                              EntryLongOrder = null;
                              StopLongOrder = null;
                              }
                              }

                              protected override void OnExecutionUpdate(Execution execution, string executionId, double price, int quantity, MarketPosition marketPosition, string orderId, DateTime time)
                              {
                              if (StopLongOrder != null && StopLongOrder == execution.Order)
                              {
                              EnterShort(QuantitySize, "ShortReverseOnLongStop");
                              EntryLongOrder = null;
                              StopLongOrder = null;
                              }
                              }
                              BigT4X are you trying to reverse with a stop and a position open?

                              Comment

                              Latest Posts

                              Collapse

                              Topics Statistics Last Post
                              Started by geddyisodin, 04-25-2024, 05:20 AM
                              8 responses
                              60 views
                              0 likes
                              Last Post NinjaTrader_Gaby  
                              Started by jxs_xrj, 01-12-2020, 09:49 AM
                              4 responses
                              3,285 views
                              1 like
                              Last Post jgualdronc  
                              Started by Option Whisperer, Today, 09:55 AM
                              0 responses
                              5 views
                              0 likes
                              Last Post Option Whisperer  
                              Started by halgo_boulder, 04-20-2024, 08:44 AM
                              2 responses
                              22 views
                              0 likes
                              Last Post halgo_boulder  
                              Started by mishhh, 05-25-2010, 08:54 AM
                              19 responses
                              6,189 views
                              0 likes
                              Last Post rene69851  
                              Working...
                              X