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

CancelOrder() for Trail StopLoss needed

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

    CancelOrder() for Trail StopLoss needed

    Hello Community,

    working several days on a concept of trailing my StopLoss but with unexpected results in real world.

    At the moment i just shifting my SL with methode (SetStopLoss). --> SetStopLoss(sSignalname, CalculationMode.Price, dSLPrice, false);
    (Think, that this Methode handles StopLoss modification for me as an update...)

    After triggering SL, sometimes Strategy opens a Counterposition!?
    I'm not sure that this behavoir relies on identical name for correct adressing?
    (I try to reset all signalnames to individuals...) --> sSignalname = Instrument.MasterInstrument.Name + "_" + sTrade_PositionName;


    But may it happens because i don't cancel previous SL-Order before set the new one?
    https://ninjatrader.com/support/help...atusupdate.htm

    Is it necessary to use first Methode (CancelOrder(***)) when i use Methode (SetStopLoss(***)) for an update?
    If so, then i don't understand concept of naming (fromEntrySignal) for Methode (SetStopLoss)...

    If somebody have a hint for me, that would be very nice... :-)



    With best regards,
    Peter


    Last edited by PeterGolz; 12-02-2019, 05:47 AM.

    #2
    See this :

    Code:
    Order entryOrders[norder] = EnterLong(numContrats, lnameOrder[norder]);
    This code has to execute in OnBarUpdate() every time you consider necessary ( for me always )
    Code:
                for (int i = 0; i < MaxnOrders; i++)
                {
                    if (entryOrders[i] != null)
                    {     
                        if (entryOrders[i].IsLong==true)
                        {
                            // Here manage your order
                          }
                        else  //Short orders
                        {
                            // Here manage your order
                          }

    Comment


      #3
      Hello PeterGolz,

      Welcome to the NinjaTrader support forums.

      After triggering SL, sometimes Strategy opens a Counterposition!?
      Do you mean after the stop is filled or after it had been submitted?

      Without more specific detail of what you are doing in the logic it would be hard to say why this is happening. If the script is opening an opposite position that may be caused by logic or a reversal. Are you also seeing on the chart "Close position" at this time or are specifically seeing a reversal of the position? The managed approach will reverse a position if you call an opposite entry method while in a position.



      But may it happens because i don't cancel previous SL-Order before set the new one?


      Is it necessary to use first Methode (CancelOrder(***)) when i use Methode (SetStopLoss(***)) for an update?
      If so, then i don't understand concept of naming (fromEntrySignal) for Methode (SetStopLoss)...
      This would not be needed, cancel order is mainly reserved orders which you may leave open and are not specifically tied to an entry by a signal name. The signal name system allows the order to be associated with an entry to cover the position, if there is no position to cover the target would be cancelled. There is a note about this in the SetStopLoss page:
      A stop loss order is automatically canceled if the managing position is closed by another strategy generated exit order
      If you exit the position it should close the target for you.


      I look forward to being of further assistance.




      JesseNinjaTrader Customer Service

      Comment


        #4
        Hi Jesse,

        thanks for your fast feedback!
        Regarding to your questions here are some details...

        After triggering SL, sometimes Strategy opens a Counterposition!?
        Do you mean after the stop is filled or after it had been submitted?
        After stop is filled, sometimes a Counterposition is in place til i close this by hand!?
        Seems for me like a filled SL with one or more Counterpositions / incorrect amound of real positions for this strategy.

        For this reason i have created a more unique (signalname) for each strategy by a combination of instrument- and strategyname.
        sSignalname = Instrument.MasterInstrument.Name + "_" + sTrade_PositionName;
        A stop loss order is automatically canceled if the managing position is closed by another strategy generated exit order
        (Sure, true...)


        Your statement regarding usage of Methode (SetStopLoss) in combination with used unique (signalname) confirms my understanding of this technique.
        For moving / trailing StopLoss it is NOT necessary to use Methode (CancelOrder)!!! :-)


        Hope to here from you soon...


        Regards,
        Peter


        Comment


          #5
          May this happens, because i have open 2 long-positions?
          But (signalname) is always the same.
          If SL is triggered / fiiled, both long-positions should just be closed... :-(

          Comment


            #6
            Hello PeterGolz,

            You mentioned multiple long positions however a target will not apply to two positions, only one. If the intention is to scale out of a position which was entered as two long positions you would need two stoploss targets to close the whole position.

            If the intention is to scale we have a sample of that concept here: https://ninjatrader.com/support/help...a_position.htm

            Can you provide more specific detail about what you are trying to do in your logic?


            I look forward to being of further assistance.



            JesseNinjaTrader Customer Service

            Comment


              #7
              Hi Jesse,

              thank for your quick responce!

              Unfortunately hole situation looks like a crazy mess for me - so far.
              I really don't understand what problem(s) are comming in place more and more!?

              Today i've build an extreme version of a strategy based on my general sourcecode. (CounterPositionProblem__v1_0)
              This strategy opens every 30 min. a long-position.

              Initial StopLoss (pink) is in place as well a TrailStop (blue) configuration by SMA in defined circumstances.
              If InitalStop is not triggered, TrailStop is alive till triggering or closing by time. (max. 30 min)
              Also different TradeSize is captured by Momentum-Indicator. (If Momentum is postive open 2 positions otherwise just open 1 position.)


              I have really hard penetrate this strategy for today!
              Let it work on instrument FDAX (for example) for today while another strategy is also working with the same instrument.

              It seems working correct, til i really make some hard tests for stability.
              For simulation of Ninjatrader-Crash or Win10 Update / Reboot - i deaktivate strategy (CounterPositionProblem__v1_0) while a position is logged in.
              With my current implentation and StartBehavior.WaitUntilFlatSynchronizeAccount, it should be possible to reconnected and recalibrate by current Account-Position.
              Code:
                          // one time only, as we transition from historical to real-time
                            else if (State == State.Realtime)
                          {
                              // convert any old historical order object references
                              // to the new live order submitted to the real-time account
                              if (orderEntry != null)
                              {
                                  orderEntry = GetRealtimeOrder(orderEntry);
                              }
                          }
              But if i do that everything goes wild and creazy!!!
              Every strategy that handels positions for the current instrument, alive or not would be closed!?
              Other (3) StartBehavior-Options looking not be better and brings up some other behaviors... :-(

              I just want to be able to reconnect and match current Account-Position by defintive individual (signal- / strategyname) ....

              May somebody have a hint?


              With best regards,
              Peter
              Attached Files
              Last edited by PeterGolz; 12-03-2019, 11:11 AM.

              Comment


                #8
                Hello PeterGolz,

                Thank you for the reply.

                It seems working correct, til i really make some hard tests for stability.
                For simulation of Ninjatrader-Crash or Win10 Update / Reboot - i deaktivate strategy (CounterPositionProblem__v1_0) while a position is logged in.
                With my current implentation and StartBehavior.WaitUntilFlatSynchronizeAccount, it should be possible to reconnected and recalibrate by current Account-Position.

                But if i do that everything goes wild and creazy!!!
                Saying its crazy doesn't help me understand what you are seeing, what specifically did you see happen? An image generally is the best way to provide this type of information.



                Every strategy that handels positions for the current instrument, alive or not would be closed!?
                If you disconnected yes, all strategies should now be disabled. If you are just disabling the strategies using the control center and the checkbox, that should only disable the ones you specifically have disabled.

                It sounds like you are using multiple strategies, while you are working on getting the strategy built and the correct start behavior I would not suggest using more than one script. This will absolutely complicate the situation and make it much more difficult to understand what may be happening in contrast to the start behavior. Strategies are not aware of what other strategies are doing so you can create conflicting situations when using more than one strategy for the same instrument. This can compound into a very confusing series of events in case one strategy tries to manage the position at the same time which another is trying the same task.



                Other (3) StartBehavior-Options looking not be better and brings up some other behaviors... :-(
                The start behaviors all work in very specific ways. You cannot change the start behavior and expect it to just work, in most cases your script needs to be programmed to specifically compliment one of the start behaviors and how it works. If you are using WaitUntilFlatSynchronizeAccount, this will not bring the strategy to match your account but will instead bring the account to match your strategy. Here is the description of how this works: https://ninjatrader.com/support/help..._positions.htm

                If the Account Position is flat already, no reconciliatory order will be submitted. The strategy will then wait for the Strategy Position to reach a flat state as well before submitting any orders live.

                If the Account Position is not flat, NinjaTrader will submit a market order(s) to reconcile the Account Position to a flat state. The strategy will then wait for the Strategy Position to reach a flat state before submitting live orders.

                If you are trying to make the strategy match what the account has you would need to use a different behavior. Likely the Immediately submit is what you would want.

                •Any active orders on the account previously generated by the strategy that does not match* an active strategy order will be cancelled. Should the strategy be unable to cancel and receive confirmation on the cancellation of these orders within 40 seconds the strategy will not start and an alert will be issued.

                •The matching active orders on the account will then be mapped to the active strategy orders

                •Any remaining active strategy orders that cannot be successfully paired will be submitted live and the strategy will begin managing your Strategy Position assuming your Account Position is in sync with it.

                Keep in mind if the script now has more data when you enable it or recalculates in a different way you may end up submitting orders to the account directly which put you in a bad position. This assumes the strategy calculated exactly the same and reached the same conclusion as it did before you disabled it.

                I highly recommend reading the descriptions from the link I posted above, after reading the descriptions for each behavior that can help provide direction on how you want to develop the strategy to work with the start behavior.







                I look forward to being of further assistance.
                JesseNinjaTrader Customer Service

                Comment


                  #9
                  Hi Jesse,

                  thanks for your links and documentaion you have provided!
                  Most of them i already have seen and read. 8-)

                  Regarding to your recommandation, from my point of view, we are now reaching a general discussion.
                  Is there a way to drive several different strategies for the same imstrument with NinjaTrader 8?
                  It sounds like you are using multiple strategies, while you are working on getting the strategy built and the correct start behavior I would not suggest using more than one script. This will absolutely complicate the situation and make it much more difficult to understand what may be happening in contrast to the start behavior. Strategies are not aware of what other strategies are doing so you can create conflicting situations when using more than one strategy for the same instrument. This can compound into a very confusing series of events in case one strategy tries to manage the position at the same time which another is trying the same task.

                  With the following code parts it should be possible for every single strategy, as well for reconnection and also reconcile of the Account:
                  Code:
                  StartBehavior                                = StartBehavior.ImmediatelySubmitSynchronizeAccount;
                  .
                  .
                  .
                              else if (State == State.Historical)
                              {
                                  sessionIterator = new SessionIterator(Bars);
                              }
                              // one time only, as we transition from historical to real-time
                                else if (State == State.Realtime)
                              {
                                  // convert any old historical order object references
                                  // to the new live order submitted to the real-time account
                                  if (orderEntry != null)
                                  {
                                      orderEntry = GetRealtimeOrder(orderEntry);
                                  }
                              }
                              else if (State == State.Transition)
                              {
                                  if (orderEntry != null && orderEntry.OrderState == OrderState.Working || 
                                      orderEntry != null && orderEntry.OrderState == OrderState.Accepted)
                                  {
                                      orderEntry = GetRealtimeOrder(orderEntry);
                                      Print("transistioning order");
                  
                                      if (orderEntry == null)
                                      {
                                          Print("order null after transition");
                                      }
                                  }
                                  else
                                  {
                                      Print("order is not in a working state");
                                  }
                              }
                  .
                  .
                  .
                          protected override void OnOrderUpdate(Order order, double limitPrice, double stopPrice, int quantity, int filled, double averageFillPrice, OrderState orderState, DateTime time, ErrorCode error, string nativeError)
                          {
                              // Assign entryOrder in OnOrderUpdate() to ensure the assignment occurs when expected.
                              // This is more reliable than assigning Order objects in OnBarUpdate, as the assignment is not gauranteed to be complete if it is referenced immediately after submitting
                              if (order.Name == (Instrument.MasterInstrument.Name + "_" + sTrade_PositionName) && 
                                  orderState != OrderState.Filled)
                              {
                                  orderEntry = order;
                              }
                  
                              // Evaluates for all updates to entryOrder
                              if (orderEntry != null && 
                                  orderEntry == order)
                              {
                                  switch (order.OrderState)
                                  {
                                      case OrderState.Filled:
                                          // Reset entryOrder back to NULL
                                          orderEntry = null;
                                          break;
                  
                                      case OrderState.Cancelled:
                                          // Reset entryOrder back to NULL
                                          orderEntry = null;
                                          break;
                  
                                      case OrderState.Rejected:
                                          // Reset entryOrder back to NULL
                                          orderEntry = null;
                                          break;
                  
                                      case OrderState.Unknown:
                                          // Reset entryOrder back to NULL
                                          orderEntry = null;
                                          break;
                                  }
                              }
                          }
                  .
                  .
                  .
                          protected override void OnBarUpdate()
                          {
                               // Evaluates to make sure we have at least 50 or more bars in both Bars objects before continuing.
                              if (BarsInProgress == 0 &&
                                  CurrentBars[0] >= BarsRequiredToTrade)
                              {
                                  string sSignalname = Instrument.MasterInstrument.Name + "_" + sTrade_PositionName;
                  
                  
                                  // Is it possible to open a new MarketPosition?
                                  if (Position.MarketPosition == MarketPosition.Flat &&
                                      orderEntry == null)
                                  {
                  .
                  .
                  .

                  Why this code (see CounterPositionProblem.cs) is working for the current strategie also after reactivation.
                  But if another strategy, with the same kind of code-structure, comes in to place for the same instrument, a reactivation affects both stragies. (Sometimes closes position...)

                  By this two parts of code and an individuell name for both strategies it never should be happend:
                  Code:
                          protected override void OnOrderUpdate(Order order, double limitPrice, double stopPrice, int quantity, int filled, double averageFillPrice, OrderState orderState, DateTime time, ErrorCode error, string nativeError)
                          {
                              // Assign entryOrder in OnOrderUpdate() to ensure the assignment occurs when expected.
                              // This is more reliable than assigning Order objects in OnBarUpdate, as the assignment is not gauranteed to be complete if it is referenced immediately after submitting
                              if (order.Name == (Instrument.MasterInstrument.Name + "_" + sTrade_PositionName) && 
                                  orderState != OrderState.Filled)
                              {
                                  orderEntry = order;
                              }
                  .
                  .
                  .
                  
                  
                                  if (Position.MarketPosition == MarketPosition.Flat &&
                                      orderEntry == null)
                  Keep in mind if the script now has more data when you enable it or recalculates in a different way you may end up submitting orders to the account directly which put you in a bad position. This assumes the strategy calculated exactly the same and reached the same conclusion as it did before you disabled it.
                  If StartBehavior = StartBehavior.ImmediatelySubmitSynchronizeAccount;
                  i can't understand this, because after direct reactivation of the strategy (Position.MarketPosition) can't be (Flat), as well as orderEntry is handled by GetRealtimeOrder().

                  From my point of view, something seems to be missing... ???

                  Hope to here from you soon...


                  With best regards,
                  Peter






                  Comment


                    #10
                    Hello PeterGolz,

                    Thank you for the reply.

                    Is there a way to drive several different strategies for the same instrument with NinjaTrader 8?
                    Sure this is possible. In most situations its best to program a single strategy which covers all of your goals but you can also program it to work as multiple strategies. This generally requires very specific logic to do that. Using more than one strategy per instrument will often not work with the start behaviors, this is because the start behavior applies to a single strategy at a time.

                    Why this code (see CounterPositionProblem.cs) is working for the current strategies also after reactivation.
                    But if another strategy, with the same kind of code-structure, comes in to place for the same instrument, a reactivation affects both strategies. (Sometimes closes position...)
                    When working with strategies it is good to remember that they work virtually and individually, anything THIS strategy does the other will not know about. The close position could be caused with the start behavior; if strategy A is re enabled and re calculated the same position and then resumes it, that does not mean strategy B will not affect the position when it enables. Strategy B now has to go through the same process and if it equates at all differently it could end up managing the position differently. If you are using ImmediatelySubmitSynchronizeAccount:
                    • If the Account Position does not match your Strategy Position, NinjaTrader will submit a market order(s) to reconcile the Account Position to match your Strategy Position. The strategy will then begin managing your Strategy Position immediately.


                    By this two parts of code and an individuell name for both strategies it never should be happend:
                    This actually wont matter. The strategies trades are not seen by the other strategy and the signal names only apply toward the current script. Each strategy is completely unaware of what the other is doing and is working on its own. Because there is no communication here you can put in conflicting orders or enter unwanted positions if the logic conflicts.


                    If StartBehavior = StartBehavior.ImmediatelySubmitSynchronizeAccount;
                    i can't understand this, because after direct reactivation of the strategy (Position.MarketPosition) can't be (Flat), as well as orderEntry is handled by GetRealtimeOrder().
                    The position can actually be flat, you are not working with the account position directly and you are working with the strategies virtual position here. When you enable a strategy it starts working from the left at bar 0 in historical data. It will run the historical backtest and calculate entries. If your logic does not equate the same in historical as it originally did in realtime it could end up flat or in a different position than the account when you enter realtime. Additionally if more data is now available after re enabling you run the risk of having more bars where the conditions could become true again or differently leading to a new different position.


                    I look forward to being of further assistance.
                    JesseNinjaTrader Customer Service

                    Comment

                    Latest Posts

                    Collapse

                    Topics Statistics Last Post
                    Started by geddyisodin, Today, 05:20 AM
                    0 responses
                    3 views
                    0 likes
                    Last Post geddyisodin  
                    Started by JonesJoker, 04-22-2024, 12:23 PM
                    6 responses
                    33 views
                    0 likes
                    Last Post JonesJoker  
                    Started by GussJ, 03-04-2020, 03:11 PM
                    12 responses
                    3,239 views
                    0 likes
                    Last Post Leafcutter  
                    Started by AveryFlynn, Today, 04:57 AM
                    0 responses
                    6 views
                    0 likes
                    Last Post AveryFlynn  
                    Started by RubenCazorla, 08-30-2022, 06:36 AM
                    3 responses
                    79 views
                    0 likes
                    Last Post PaulMohn  
                    Working...
                    X