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

SetStopLoss(): reset it

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

    SetStopLoss(): reset it

    Hi NT,

    I have BUY entry condition and would like to set an initial stop at Close[1] - ATR(14)[1]*5.
    I use SetStopLoss() on the OnBarUpdate method like so:

    Code:
    protected override void OnBarUpdate()
    		{
    			if (condition)  [0] == bullish)
    			{	
    				if (condition)  [1] == sideways)
    				{
    					SetStopLoss("Enter Long",CalculationMode.Price, Close[1] - ATR(200)[1]*3, false);								
    				}
    				EnterLong(1,"Enter Long");					
    			}
    So far so good. My nested IF ensures that my stop loss (110 for instance) doesnt dynamically change while in an open position and stays at 110 for the life of the trade.
    Is there anything wrong here ? The help pages imply that for a static stop, "it is suggested to call this method from within the strategy OnStateChange()"

    The problem is have it: once I hit my Stop Loss (at 110), and I enter a new long position, the stop loss is being sent at the same 110 price (instead of the updated to: Close[1] - ATR(200)[1]*3).
    It's like the stop value is being cached and recycled. This looks like expected behaviour :

    "You should always reset the stop loss price / offset value when your strategy is flat otherwise, the last price/offset value set will be used to generate your stop loss order on your next open position"

    But how do I reset it ?

    I've tried the following in both State.Configure method and OnBarUpdate with no success

    Code:
    if (Position.MarketPosition == MarketPosition.Flat)
    				{
    						SetStopLoss(CalculationMode.Price, ATR(14)[1]);		
    				}
    Can someone point me in the right direction ?

    #2
    Hello akvevo,

    The SetStopLoss is reset each time you call it.

    I always suggest setting the price of the stop loss one line above where the entry is placed.

    If you add a print where the stop loss is being set and you add TraceOrders = true; to State.SetDefaults, are you able to see the print (and thus the SetStopLoss being set) before you see the entry order being placed?

    Resetting this when flat should also work.

    Below is a link to an example that successfully does this called StopStrategySetMethodsOnMarketData_NT8.zip.
    Chelsea B.NinjaTrader Customer Service

    Comment


      #3
      Thanks ChelseaB,

      The SetStopLoss is reset each time you call it.
      I am not seeing this. I see the stop loss on is the same value on the next trade. I need to explicitly reset it right ? In your example, this snippet in the OnBarUpdate resets it ?

      Code:
      if (Position.MarketPosition == MarketPosition.Flat)
      			{
      				currentStop		= 0;
      				trail			= false;
      				SetStopLoss(CalculationMode.Ticks, StopLossDistance);
      			}


      What is the purpose of also adding the SetStopLoss( ) to the (State == State.Historical) ? I saw example that placed the SetStopLoss in the State.Configure instead of the State.Historical method.

      Code:
      else if (State == State.Configure)
      			{
      				SetStopLoss(CalculationMode.Price, Close[1]);								
      			}
      
      protected override void OnBarUpdate()
      {
      			if (Position.MarketPosition == MarketPosition.Flat)
      			{
      				SetStopLoss(CalculationMode.Price, Close[1]);
      			}
      				
      
      			if (condition)  [0] == bullish)
      			{	
      				if (condition)  [1] == flat)
      				{
      					SetStopLoss("Enter Long",CalculationMode.Price, Close[1] - ATR(200)[1]*3, false);								
      				}  	
      				EnterLong(1,"Enter Long");					
      			}
      Do you perhaps have a line example of how to Print the stop value ?
      Last edited by akvevo; 07-03-2017, 03:43 PM.

      Comment


        #4
        Hello akvevo,

        The stop loss will continue to hold its old value unless it is called again with a new value.

        This is why it must be reset before a new entry is placed.

        The example I have provided, moves the stop loss several times simply by calling it.

        The SetStopLoss is called in historical to give this an initial value when the script starts.
        SetStopLoss can be called just about anywhere. Its fine to call this in State.Configure or State.Historical (or State.DataLoaded) or in OnBarUpdate or any other data driven method like OnMarketData.

        To print the stop loss price, you would need to detect the order updating in OnOrderUpdate.
        Chelsea B.NinjaTrader Customer Service

        Comment


          #5
          In reply to this thread I had what seems the same problem today. An earlier trade had set the SetStopLoss to a certain value. This trade was later closed out. A second order was executed later on (which uses the same entry name as the previous entry, being the word "short" and today's date converted to string), the previous SetStopLoss value was submitted along with this second entry, which was below market price in this case and got rejected.

          The code snippets for entries/stoploss is as follows:

          Code:
                      if(short entry requirments)
                      {
                          vol =  (ATR(60)[0]);
                          stopLoss = (vol*2)*100;
                          entryCalc = (100/(stopLoss))*1000;
                          entrySize = Convert.ToInt32(entryCalc);
                          entryName = "Short"+ToDay(Time[0]).ToString();
          
                          EnterShort(entrySize,entryName);    
                      }
          Code:
                  protected override void OnExecutionUpdate(Execution execution, string executionId, double price, int quantity, MarketPosition marketPosition, string orderId, DateTime time)
                  {
                      if (entryOrder != null && entryOrder == execution.Order)
                      {
                          if (execution.Order.OrderState == OrderState.Filled || execution.Order.OrderState == OrderState.PartFilled || (execution.Order.OrderState == OrderState.Cancelled && execution.Order.Filled > 0))
                          {                 
                              stopLoss = (vol*2)*100;
                              profitTarget = (vol*4)*100;
          
                              SetStopLoss(entryName,CalculationMode.Ticks, stopLoss,false);
          
                              if(entryName == "Short"+ToDay(Time[0]).ToString())
                              {
                                  SetProfitTarget(entryName,CalculationMode.Ticks, profitTarget);           
                              }
          
                              if (execution.Order.OrderState != OrderState.PartFilled)
                                  entryOrder = null;
                          }
                      }
                  }
          Even though the description from Chelsea says that the SetStopLoss is reset everytime it is called, it didn't occur in this case today. The stop loss submitted for the second short entry of the day was exactly the same as the first, despite the first entry price being 13059.05 and the second entry price roughly two hours later of 13076.45 (DAX).

          Strangely, the SetProfitTarget adjusted correctly to the new value (only used in case of a short position entry).

          How can I ensure SetStopLoss is properly overwritten with the new SetStopLoss price when subsequent entries are made on the same day. Bearing in mind I have long and short entries within this script so setting stop loss when MarketPosition == Flat doesn't seem to be an option as per Chelsea's example.

          Comment


            #6
            Hello pmn100,

            The code you have provided does not show where the order is being placed.

            May I confirm you are resetting the price of the stop loss and profit target before the new entry is placed, or may I confirm you are using unique signal names and from entry signals to keep all stop losses and profit targets separate?
            Chelsea B.NinjaTrader Customer Service

            Comment


              #7
              Originally posted by NinjaTrader_ChelseaB View Post
              Hello pmn100,

              The code you have provided does not show where the order is being placed.
              Its within onbarupdate(). The actual code is in the original post.


              May I confirm you are resetting the price of the stop loss and profit target before the new entry is placed, or may I confirm you are using unique signal names and from entry signals to keep all stop losses and profit targets separate?
              The price of the stop loss and profit target are changing because they are based off a changing ATR value, and of course they are OCO orders so should be referencing the latest entry order. I'm not specifically resetting them between trades because I'm not sure how I would go about that. They are simply called within onexecutionupdate() and I'm trusting they're getting overwritten with new values when they're called. The entry signal names are unique to the day but not to the trades, so a second short entry on the day would share the same entry name as the first short entry that was in this case closed out earlier.

              Just to make clear, this works fine in backtest. It was today during realtime that the SetStopLoss failed to update correctly for the second short entry of the day.

              Comment


                #8
                Hello pmn100,

                Reset the stop loss and profit target by calling these with a new price one line before the entry is placed in OnBarUpdate..

                SetStopLoss() once called does not get unset and continues to hold that same price for new orders. So change the price of the stop loss to a valid price before the entry is placed.
                Chelsea B.NinjaTrader Customer Service

                Comment


                  #9
                  Originally posted by NinjaTrader_ChelseaB View Post
                  Hello pmn100,

                  Reset the stop loss and profit target by calling these with a new price one line before the entry is placed in OnBarUpdate..

                  SetStopLoss() once called does not get unset and continues to hold that same price for new orders. So change the price of the stop loss to a valid price before the entry is placed.
                  Thanks Chelsea

                  So you're suggesting I should take SetStopLoss and SetProfitTarget out of onexecutionupdate() and place them within the if() statement of my first snippet of code like this:

                  Code:
                              if(short entry requirments)
                              {
                                  vol =  (ATR(60)[0]);
                                  stopLoss = (vol*2)*100;
                                  profitTarget = (vol*4)*100;
                                  entryCalc = (100/(stopLoss))*1000;
                                  entrySize = Convert.ToInt32(entryCalc);
                                  entryName = "Short"+ToDay(Time[0]).ToString();
                  
                                  SetStopLoss(entryName,CalculationMode.Ticks, stopLoss,false);
                  
                                  if(entryName == "Short"+ToDay(Time[0]).ToString())
                                      {
                                      SetProfitTarget(entryName,CalculationMode.Ticks, profitTarget);
                                      }
                  
                                  EnterShort(entrySize,entryName);    
                              }
                  This won't throw out errors about trying to place a stop loss/profit target for an entry that doesn't exist? I thought the point of placing stop loss and profit targets within onexecutionupdate() was to ensure the entry order has been processed before submitting linking stop loss and profit targets.

                  Comment


                    #10
                    Hello pmn100,

                    No, I am not suggesting you need to remove any other code.

                    SetStopLoss will be set any time you call it. You can call it any time.

                    I am suggesting that you call it to set it to a valid price before you place an order.

                    No, SetStopLoss and SetProfitTarget are not used the same as Exit orders. SetStopLoss and SetProfitTarget should be set before an order is placed. If you use the Strategy Builder, NinjaTrader will only set these once, in State.Configure, before any data is processed and before any orders are placed and doesn't set them again.

                    From the help guide on SetStopLoss in the tips section:
                    "It is suggested to call this method from within the strategy OnStateChange() method if your stop loss price/offset is static
                    You may call this method from within the strategy OnBarUpdate() method should you wish to dynamically change the stop loss price while in an open position
                    Should you call this method to dynamically change the stop loss price in the strategy OnBarUpdate() method, you should always reset the stop loss price / offset value when your strategy is flat otherwise, the last price/offset value set will be used to generate your stop loss order on your next open position"
                    Last edited by NinjaTrader_ChelseaB; 12-27-2017, 10:25 AM.
                    Chelsea B.NinjaTrader Customer Service

                    Comment


                      #11
                      Okay thanks Chelsea

                      I was under the impression that the submission of stop loss and profit targets was when calling SetStopLoss and SetProfitTarget but they actually only submit once the corresponding entry is executed.

                      So I shouldn't have SetStopLoss and SetProfitTarget within onexecutionupdate() ever really?

                      Comment


                        #12
                        Hello pmn100,

                        Yes, SetStopLoss and SetProfitTarget are set as triggers for when the entry order fills. These will not be placed until the entry order fills.

                        ExitOrders are submitted immediately when called.

                        You can set the stop loss and profit target any time. Its fine to also do this in OnExecution if you want to change the price of the stop with a new price after the entry has filled. This is up to you.
                        Its still necessary to set and reset these before the entry is submitted.
                        Chelsea B.NinjaTrader Customer Service

                        Comment

                        Latest Posts

                        Collapse

                        Topics Statistics Last Post
                        Started by xiinteractive, 04-09-2024, 08:08 AM
                        2 responses
                        11 views
                        0 likes
                        Last Post xiinteractive  
                        Started by Irukandji, Today, 09:34 AM
                        1 response
                        3 views
                        0 likes
                        Last Post NinjaTrader_Clayton  
                        Started by RubenCazorla, Today, 09:07 AM
                        1 response
                        5 views
                        0 likes
                        Last Post RubenCazorla  
                        Started by TraderBCL, Today, 04:38 AM
                        3 responses
                        25 views
                        0 likes
                        Last Post NinjaTrader_Jesse  
                        Started by WeyldFalcon, 08-07-2020, 06:13 AM
                        11 responses
                        1,423 views
                        0 likes
                        Last Post jculp
                        by jculp
                         
                        Working...
                        X