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

Having issues with adjusting stop loss after Take profit.

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

    Having issues with adjusting stop loss after Take profit.

    Hey All, First time poster here.. I have a small snag...


    //Here is my buy logic..
    if(Position.MarketPosition == MarketPosition.Flat && currentTime >= TradeStartTime && currentTime <= TradeEndTime && !isTradeOn && isUptrend)
    {
    isTradeOn = true;
    if(NumOfContractTpTwo == 0)
    {
    string orderName = $"LongEntry";
    EnterLong(NumOfContractTpOne, orderName);
    SetProfitTarget(orderName, CalculationMode.Ticks, TakeProfitTicksContract1);
    SetStopLoss(orderName, CalculationMode.Ticks, StopLossTicks, false);
    }
    if(NumOfContractTpTwo >= 1)
    {
    for (int i = 1; i <= 2; i++)
    {
    string orderName = $"LongEntry{i}";
    int numOfContracts = i == 1 ? NumOfContractTpOne : NumOfContractTpTwo;
    EnterLong(numOfContracts, orderName);
    SetStopLoss(orderName, CalculationMode.Ticks, StopLossTicks, false);
    double takeProfitTicks = i == 1 ? TakeProfitTicksContract1 : TakeProfitTicksContract2;
    SetProfitTarget(orderName, CalculationMode.Ticks, takeProfitTicks);
    }
    }
    }​


    When TP 1 is hit I want to adjust my stop loss.

    I am using the below method to look to see when TP1 is hit and then it shoud readjust.



    protected override void OnOrderUpdate(Order order, double limitPrice, double stopPrice, int quantity, int filled,
    double averageFillPrice, OrderState orderState, DateTime time, ErrorCode error, string nativeError)
    {
    // Check if the TP1 order is filled
    if ((order.Name == "LongEntry1" || order.Name == "ShortEntry1") && order.OrderState == OrderState.Filled)
    {
    // Retrieve the average fill price of the entry order
    double entryPrice = order.AverageFillPrice;


    if (order.Name == "LongEntry1")
    {

    double ticksToBreakEven = (entryPrice - Close[0]) / TickSize;
    SetStopLoss("LongEntry2", CalculationMode.Price, entryPrice, false);
    Print("Moving Stop Loss for LongEntry2 to Break Even: " + entryPrice);
    }
    else if (order.Name == "ShortEntry1")
    {
    // Similarly, for 'ShortEntry2'
    double ticksToBreakEven = (Close[0] - entryPrice) / TickSize;
    SetStopLoss("ShortEntry2", CalculationMode.Price, entryPrice, false);
    Print("Moving Stop Loss for ShortEntry2 to Break Even: " + entryPrice);
    }
    }
    }​


    Anythoughts why this wouldnt be working?

    Thanks,
    Greg

    Everything prints correctly but its not moving my stop loss =-(
    Last edited by gamero1202; 02-17-2024, 05:12 PM.

    #2
    Hello Greg,

    Thanks for your post.

    First, I see you are calling Set methods after the Enter method in your script. Set methods should be called before calling your Enter order method as noted in the help guide:

    From the help guide: "Since they are submitted upon receiving an execution, the Set method should be called prior to submitting the associated entry order to ensure an initial level is set."

    SetStopLoss(): https://ninjatrader.com/support/help...etstoploss.htm
    SetProfitTarget(): https://ninjatrader.com/support/help...ofittarget.htm

    Further debugging would need to be done to understand exactly how your logic is behaving. One line above conditions to change the order, add prints that print out all the values being used in the conditions to change the order. One line above where you are changing the order, add prints that print out the price the order is submitted to. And, print out the Order object in OnOrderUpdate() to see how the order is behaving.

    Below is a link to a forum post that demonstrates how to use prints to understand behavior.


    You may also want to consider using the same CalculationMode for the stop/target throughout the script. For example, use either CalculationMode.Ticks or CalculationMode.Price.

    Here is a reference sample demonstrating modifying profit target and stop loss orders: https://ninjatrader.com/support/help...of_stop_lo.htm

    You could also consider handling your protective order in OnExecutionUpdate() as seen in the SampleOnOrderUpdate reference sample from the help guide.

    SampleOnOrderUpdate: https://ninjatrader.com/support/help...and_onexec.htm
    Brandon H.NinjaTrader Customer Service

    Comment


      #3
      Thanks for the reply. I switched the set methods like you suggested and changed the code alittle put... Here are my updates ..

      if(Position.MarketPosition == MarketPosition.Flat && currentTime >= TradeStartTime && currentTime <= TradeEndTime && !isTradeOn && isUptrend)
      {
      isTradeOn = true;
      if(NumOfContractTpTwo == 0)
      {
      string orderName = $"LongEntry";
      EnterLong(NumOfContractTpOne, orderName);
      SetProfitTarget(orderName, CalculationMode.Ticks, TakeProfitTicksContract1);
      SetStopLoss(orderName, CalculationMode.Ticks, StopLossTicks, false);
      }
      if(NumOfContractTpTwo >= 1)
      {
      for (int i = 1; i <= 2; i++)
      {
      string orderName = $"LongEntry{i}";
      int numOfContracts = i == 1 ? NumOfContractTpOne : NumOfContractTpTwo;

      SetStopLoss(orderName, CalculationMode.Ticks, StopLossTicks, false);
      double takeProfitTicks = i == 1 ? TakeProfitTicksContract1 : TakeProfitTicksContract2;
      SetProfitTarget(orderName, CalculationMode.Ticks, takeProfitTicks);
      EnterLong(numOfContracts, orderName);
      }
      }
      }

      This is my orginal order... It places a order named longEntry1 for 1 contract , TP 20 pts and a stop lost of 35pts. and also places another order for 1 contracts TP 30 and stop loss for 35pounts.

      I am using these methods to help keep track of the order.


      protected override void OnOrderUpdate(Cbi.Order order, double limitPrice, double stopPrice, int quantity, int filled, double averageFillPrice, Cbi.OrderState orderState, DateTime time, Cbi.ErrorCode error, string nativeError)
      {
      Print($"Order Update: {order.OrderType} - {order.Name} | State: {orderState} | Error: {error} | Stop Price: {stopPrice}");
      // Check if the TP1 order is filled
      if (order.OrderType == OrderType.StopMarket && order.Name == "ShortEntry2" && orderState == OrderState.Working)
      {
      stopLossOrderId = order.OrderId.ToString();
      Print("Stop Loss Order ID: " + stopLossOrderId);
      }

      if (order.Name == "LongEntry1" && order.OrderState == OrderState.Filled)
      {
      isFirstOrderTpHitLong = true; // Assuming you have a flag to track if TP1 is hit
      Print("TP for LongEntry 1 hit");
      }
      if (order.Name == "ShortEntry1" && order.OrderState == OrderState.Filled)
      {
      isFirstOrderTpHitShort = true; // Assuming you have a flag to track if TP1 is hit
      Print("TP for shortEntry 1 hit");
      }
      }
      protected override void OnExecutionUpdate(Cbi.Execution execution, string executionId, double price, int quantity, Cbi.MarketPosition marketPosition, string orderId, DateTime time)
      {
      if (isFirstOrderTpHitLong)
      {
      // Adjust the stop loss for the long position up by 35 ticks
      double newStopPrice = Position.AveragePrice + (5 * TickSize);
      SetStopLoss(CalculationMode.Price, newStopPrice);
      isFirstOrderTpHitLong = false; // Reset the flag
      Print("Price should be set: " + newStopPrice);
      Print($"Adjusting stop loss for {Position.MarketPosition} position. New stop price: {newStopPrice}");

      }
      else if (isFirstOrderTpHitShort)
      {
      // Adjust the stop loss for the short position down by 35 ticks
      double newStopPrice = Position.AveragePrice - (5 * TickSize);
      SetStopLoss(CalculationMode.Price, newStopPrice);
      isFirstOrderTpHitShort = false; // Reset the flag
      Print("Price should be set: " + newStopPrice);
      Print($"Adjusting stop loss for {Position.MarketPosition} position. New stop price: {newStopPrice}");

      }
      }​

      I added some debugging and this is what i get.



      TP for shortEntry 1 hit
      Order Update: StopMarket - Stop loss | State: Submitted | Error: NoError | Stop Price: 17923
      Order Update: StopMarket - Stop loss | State: Accepted | Error: NoError | Stop Price: 17923
      Order Update: Limit - Profit target | State: Submitted | Error: NoError | Stop Price: 0
      Order Update: Limit - Profit target | State: Accepted | Error: NoError | Stop Price: 0
      Order Update: Limit - Profit target | State: Working | Error: NoError | Stop Price: 0
      Price should be set: 17913
      Adjusting stop loss for Short position. New stop price: 17913
      Order Update: Market - ShortEntry2 | State: Submitted | Error: NoError | Stop Price: 0
      Order Update: Market - ShortEntry2 | State: Accepted | Error: NoError | Stop Price: 0
      Order Update: Market - ShortEntry2 | State: Working | Error: NoError | Stop Price: 0
      Order Update: Market - ShortEntry2 | State: Filled | Error: NoError | Stop Price: 0
      Order Update: StopMarket - Stop loss | State: Submitted | Error: NoError | Stop Price: 17923
      Order Update: StopMarket - Stop loss | State: Accepted | Error: NoError | Stop Price: 17923
      Order Update: Limit - Profit target | State: Submitted | Error: NoError | Stop Price: 0
      Order Update: Limit - Profit target | State: Accepted | Error: NoError | Stop Price: 0
      Order Update: Limit - Profit target | State: Working | Error: NoError | Stop Price: 0
      Order Update: Limit - Profit target | State: Filled | Error: NoError | Stop Price: 0
      Order Update: StopMarket - Stop loss | State: CancelPending | Error: NoError | Stop Price: 17923
      Order Update: StopMarket - Stop loss | State: CancelSubmitted | Error: NoError | Stop Price: 17923
      Order Update: StopMarket - Stop loss | State: Cancelled | Error: NoError | Stop Price: 17923
      Order Update: Limit - Profit target | State: Filled | Error: NoError | Stop Price: 0
      Order Update: StopMarket - Stop loss | State: CancelPending | Error: NoError | Stop Price: 17923
      Order Update: StopMarket - Stop loss | State: CancelSubmitted | Error: NoError | Stop Price: 17923
      Order Update: StopMarket - Stop loss | State: Cancelled | Error: NoError | Stop Price: 17923


      something I just notice but I am trying to print the Order ID for the stop loss and its not printing..

      Here is a snippet for that.​

      protected override void OnOrderUpdate(Cbi.Order order, double limitPrice, double stopPrice, int quantity, int filled, double averageFillPrice, Cbi.OrderState orderState, DateTime time, Cbi.ErrorCode error, string nativeError)
      {
      Print($"Order Update: {order.OrderType} - {order.Name} | State: {orderState} | Error: {error} | Stop Price: {stopPrice}");
      // Check if the TP1 order is filled
      if (order.OrderType == OrderType.StopMarket && order.Name == "ShortEntry2" && orderState == OrderState.Working)
      {
      stopLossOrderId = order.OrderId.ToString();
      Print("Stop Loss Order ID: " + stopLossOrderId);
      }

      if (order.Name == "LongEntry1" && order.OrderState == OrderState.Filled)
      {
      isFirstOrderTpHitLong = true; // Assuming you have a flag to track if TP1 is hit
      Print("TP for LongEntry 1 hit");
      }
      if (order.Name == "ShortEntry1" && order.OrderState == OrderState.Filled)
      {
      isFirstOrderTpHitShort = true; // Assuming you have a flag to track if TP1 is hit
      Print("TP for shortEntry 1 hit");
      }
      }​

      Comment


        #4
        Hello gamero1202,

        Thanks for your notes.

        The entry order code snippets you shared are for entering a long position but the print output seems to be for a short position.

        In your condition to print the stop loss order ID you are checking if the order.Name is "ShortEntry2".

        Is this the signal name of your Entry order method to enter a short position?

        Are you calling EnterShort() to submit your short entry order or are you calling EnterShortStopMarket()?

        Note that the signal name of SetStopLoss() would be "Stop loss" as noted in the SetStopLoss() help guide page. This means the stop loss order.Name would not be "ShortEntry2".

        From the help guide: "The signal name generated internally by this method is "Stop loss" which can be used with various methods such as BarsSinceExitExecution(), or other order concepts which rely on identifying a signal name​"

        SetStopLoss(): https://ninjatrader.com/support/help...ub=setstoploss

        When you are calling SetStopLoss() to change the stop loss I see you are not passing in a FromEntrySignal parameter into the method. You should make sure to pass in the same FromEntrySignal parameter into the SetStopLoss() method when changing the order as you do when you are initially calling SetStopLoss() to place the initial stop loss order.

        Further debugging prints should be added to the script (one line above the conditions) that prints out all the values used for each condition that calls SetStopLoss() to see if the condition is becoming true. Also, you should keep an eye on the Log tab of the Control Center for any errors that may occur.

        And, enable TraceOrders to see exactly how the orders are behaving. This will let you know if any orders are being ignored and not being submitted when the condition to place the orders is evaluating as true.

        Below is a link to a forum post that demonstrates how to use prints to understand behavior.


        Brandon H.NinjaTrader Customer Service

        Comment


          #5
          Sorry for the confusion.. the sell and buy logic are the same (See below)...

          Ok this is making some sense.


          "In your condition to print the stop loss order ID you are checking if the order.Name is "ShortEntry2".

          Is this the signal name of your Entry order method to enter a short position?

          Are you calling EnterShort() to submit your short entry order or are you calling EnterShortStopMarket()?

          Note that the signal name of SetStopLoss() would be "Stop loss" as noted in the SetStopLoss() help guide page. This means the stop loss order.Name would not be "ShortEntry2".

          From the help guide: "The signal name generated internally by this method is "Stop loss" which can be used with various methods such as BarsSinceExitExecution(), or other order concepts which rely on identifying a signal name​"​"

          Yes I have two entries... Maybe I can do this better but this is what I am trying to do..
          I have a loop to take make two orders... to beable to get multipe Take Profts.. The Stops are set the same. I am using entershort to get into the trade and using Set Profit and SetStopLoss

          "This means the stop loss order.Name would not be "ShortEntry2"." Oh...... So if I have two stop loss orders.... I am waiting for the first order to take profit so the first Stop Loss order gets canceled... I should be using below Instead?

          if (order.OrderType == OrderType.StopMarket && order.Name == "Stop Loss" && orderState == OrderState.Working)

          and using the FromEntrySignal

          SetStopLoss("ShortEntry2",CalculationMode.Price, newStopPrice);

          ??


          How can I enable = TraceOrders?

          Thanks,
          Greg


          Sells statement below



          if(Position.MarketPosition == MarketPosition.Flat && currentTime >= TradeStartTime && currentTime <= TradeEndTime && !isTradeOn && isDowntrend)
          {
          isTradeOn = true;


          if(NumOfContractTpTwo == 0)
          {
          string orderName = $"ShortEntry";

          EnterShort(NumOfContractTpOne, orderName);
          SetProfitTarget(orderName, CalculationMode.Ticks, TakeProfitTicksContract1);
          SetStopLoss(orderName, CalculationMode.Ticks, StopLossTicks, false);
          }
          if(NumOfContractTpTwo >= 1)
          {
          for (int i = 1; i <= 2; i++)
          {
          string orderName = $"ShortEntry{i}";
          int numOfContracts = i == 1 ? NumOfContractTpOne : NumOfContractTpTwo;
          SetStopLoss(orderName, CalculationMode.Ticks, StopLossTicks, false);
          double takeProfitTicks = i == 1 ? TakeProfitTicksContract1 : TakeProfitTicksContract2;
          SetProfitTarget(orderName, CalculationMode.Ticks, takeProfitTicks);
          EnterShort(numOfContracts, orderName);



          }
          }
          }​

          Comment


            #6
            Hello gamero1202,

            Thanks for your notes.

            Yes, that would be the correct way to check if the order.Name is equal to "Stop loss" which would be the signal name of a SetStopLoss() order.

            This would not be the correct syntax for SetStopLoss() if you are passing in a FromEntrySignal parameter.

            SetStopLoss(string fromEntrySignal, CalculationMode mode, double value, bool isSimulatedStop)

            You would need to also set the isSimulatedStop parameter to either false or true.

            SetStopLoss(): https://ninjatrader.com/support/help...etstoploss.htm

            If you are submitting two stop loss orders with SetStopLoss(), each stop loss order will have a name of "Stop loss".

            To accomplish your specific goals I would suggest modifying your strategy to use Exit methods for the stop/target orders instead of using Set methods as this would provide you with more control over your protective orders.

            By using Exit methods for your protective orders, you could give each stop/target a specific signal name which would allow you to more easily handle the changing of the stop loss orders for specific entry orders.

            This reference sample demonstrates using Exit order methods with OnOrderUpdate() and OnExecutionUpdate() for handling stops/targets.

            SampleOnOrderUpdate: https://ninjatrader.com/support/help...and_onexec.htm

            OnOrderUpdate(): https://ninjatrader.com/support/help...rderupdate.htm

            OnExecutionUpdate(): https://ninjatrader.com/support/help...tionupdate.htm
            Brandon H.NinjaTrader Customer Service

            Comment


              #7
              Ok I took you advice..

              Updated code

              if(Position.MarketPosition == MarketPosition.Flat && currentTime >= TradeStartTime && currentTime <= TradeEndTime && !isTradeOn && isDowntrend)
              {
              isTradeOn = true;


              if(NumOfContractTpTwo == 0)
              {
              string orderName = $"ShortEntry";

              EnterShort(NumOfContractTpOne, orderName);
              SetProfitTarget(orderName, CalculationMode.Ticks, TakeProfitTicksContract1);
              SetStopLoss(orderName, CalculationMode.Ticks, StopLossTicks, false);
              }
              if(NumOfContractTpTwo >= 1)
              {
              for (int i = 1; i <= 2; i++)
              {
              string orderName = $"ShortEntry{i}";
              string TPName = $"TP{i}Short";
              string StopName = $"Stp{i}Short";
              int numOfContracts = i == 1 ? NumOfContractTpOne : NumOfContractTpTwo;


              EnterShort(numOfContracts, orderName);


              double entryPrice = Close[0];
              double takeProfitTicks = i == 1 ? TakeProfitTicksContract1 : TakeProfitTicksContract2;
              double takeProfitPrice = CalculateTakeProfitPriceForShort(entryPrice, takeProfitTicks);

              double stopLossPrice = CalculateStopLossPriceForShort(entryPrice, stopLossTicks);



              Print("Stop: " + stopLossPrice + " " + "Take Profit: " + takeProfitPrice);
              // ExitLongStopMarket to set a stop loss
              ExitShortStopMarket(0, true, numOfContracts, stopLossPrice, StopName, orderName);

              // ExitLongLimit to set a take profit (MIT functionality)
              ExitShortLimit(0, true, numOfContracts, takeProfitPrice, TPName, orderName);
              Print(TPName);

              }
              }
              }


              protected override void OnOrderUpdate(Order order, double limitPrice, double stopPrice, int quantity, int filled, double averageFillPrice, OrderState orderState, DateTime time, ErrorCode error, string nativeError)
              {
              // Handle entry orders here. The entryOrder object allows us to identify that the order that is calling the OnOrderUpdate() method is the entry order.
              // 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 == "TP1Long" && order.OrderState == OrderState.Filled)
              {
              Print("TP 1 Long Taken ");
              isFirstOrderTpHitLong = true;
              }
              if (order.Name == "TP2Short" && order.Filled == 0)
              {
              Print("TP 1 Shrt Taken ");
              isFirstOrderTpHitShort = true;
              }
              }
              protected override void OnExecutionUpdate(Cbi.Execution execution, string executionId,
              double price, int quantity, Cbi.MarketPosition marketPosition,
              string orderId, DateTime time)
              {
              // Check if the execution is for TP1

              if (isFirstOrderTpHitLong == true)
              {
              double newStopPrice = Position.AveragePrice + (5 * TickSize);
              isFirstOrderTpHitLong = false;
              //ExitShortStopMarket(0, true, numOfContracts, stopLossPrice, StopName, orderName);
              ExitShortStopMarket(0, true, 1, newStopPrice, "Stp2Long", "LongEntry2");
              }

              if (isFirstOrderTpHitShort == true)
              {
              double newStopPrice = Position.AveragePrice - (5 * TickSize);
              isFirstOrderTpHitShort = false;
              ExitShortStopMarket(0, true, 1, newStopPrice, "Stp2Short", "ShortEntry2");
              }

              }


              So still having issues.... The stop loss still isnt moving but I hit a new curb... This my output.. Thanks for helping me with this by the way.


              2/9/2024 9:07:00 AM Strategy 'DaBossStrat/316302357': Entered internal SubmitOrderManaged() method at 2/9/2024 9:07:00 AM: BarsInProgress=0 Action=SellShort OrderType=Market Quantity=1 LimitPrice=0 StopPrice=0 SignalName='ShortEntry1' FromEntrySignal=''
              TP Short
              Stop Short
              Stop: 17927.5 Take Profit: 17913.75
              2/9/2024 9:07:00 AM Strategy 'DaBossStrat/316302357': Entered internal SubmitOrderManaged() method at 2/9/2024 9:07:00 AM: BarsInProgress=0 Action=BuyToCover OrderType=StopMarket Quantity=1 LimitPrice=0 StopPrice=17927.50 SignalName='Stp1Short' FromEntrySignal='ShortEntry1'
              2/9/2024 9:07:00 AM Strategy 'DaBossStrat/316302357': Ignored SubmitOrderManaged() method at 2/9/2024 9:07:00 AM: BarsInProgress=0 Action=BuyToCover OrderType=StopMarket Quantity=1 LimitPrice=0 StopPrice=17927.50 SignalName='Stp1Short' FromEntrySignal='ShortEntry1' Reason='This was an exit order but no position exists to exit'
              2/9/2024 9:07:00 AM Strategy 'DaBossStrat/316302357': Entered internal SubmitOrderManaged() method at 2/9/2024 9:07:00 AM: BarsInProgress=0 Action=BuyToCover OrderType=Limit Quantity=1 LimitPrice=17913.75 StopPrice=0 SignalName='TP1Short' FromEntrySignal='ShortEntry1'
              2/9/2024 9:07:00 AM Strategy 'DaBossStrat/316302357': Ignored SubmitOrderManaged() method at 2/9/2024 9:07:00 AM: BarsInProgress=0 Action=BuyToCover OrderType=Limit Quantity=1 LimitPrice=17913.75 StopPrice=0 SignalName='TP1Short' FromEntrySignal='ShortEntry1' Reason='This was an exit order but no position exists to exit'
              TP1Short
              2/9/2024 9:07:00 AM Strategy 'DaBossStrat/316302357': Entered internal SubmitOrderManaged() method at 2/9/2024 9:07:00 AM: BarsInProgress=0 Action=SellShort OrderType=Market Quantity=1 LimitPrice=0 StopPrice=0 SignalName='ShortEntry2' FromEntrySignal=''
              TP Short
              Stop Short
              Stop: 17927.5 Take Profit: 17910
              2/9/2024 9:07:00 AM Strategy 'DaBossStrat/316302357': Entered internal SubmitOrderManaged() method at 2/9/2024 9:07:00 AM: BarsInProgress=0 Action=BuyToCover OrderType=StopMarket Quantity=1 LimitPrice=0 StopPrice=17927.50 SignalName='Stp2Short' FromEntrySignal='ShortEntry2'
              2/9/2024 9:07:00 AM Strategy 'DaBossStrat/316302357': Ignored SubmitOrderManaged() method at 2/9/2024 9:07:00 AM: BarsInProgress=0 Action=BuyToCover OrderType=StopMarket Quantity=1 LimitPrice=0 StopPrice=17927.50 SignalName='Stp2Short' FromEntrySignal='ShortEntry2' Reason='This was an exit order but no position exists to exit'
              2/9/2024 9:07:00 AM Strategy 'DaBossStrat/316302357': Entered internal SubmitOrderManaged() method at 2/9/2024 9:07:00 AM: BarsInProgress=0 Action=BuyToCover OrderType=Limit Quantity=1 LimitPrice=17910.00 StopPrice=0 SignalName='TP2Short' FromEntrySignal='ShortEntry2'
              2/9/2024 9:07:00 AM Strategy 'DaBossStrat/316302357': Ignored SubmitOrderManaged() method at 2/9/2024 9:07:00 AM: BarsInProgress=0 Action=BuyToCover OrderType=Limit Quantity=1 LimitPrice=17910.00 StopPrice=0 SignalName='TP2Short' FromEntrySignal='ShortEntry2' Reason='This was an exit order but no position exists to exit'
              TP2Short​



              ​​

              Comment


                #8
                Hello gamero1202,

                Thanks for your notes.

                I see you are using both Exit methods and Set methods in the code you shared.

                You should not use both Exit methods and Set methods in the same script as this would go against the Managed Approach Internal Order Handling Rules.

                See the 'Internal Order Handling Rules' section of this help guide page for more information about Managed Approach Internal Order Handling Rules: https://ninjatrader.com/support/help...d_approach.htm

                You will need to modify your strategy to only use Exit methods in your script for placing protective orders.

                Further, Exit methods should not be called in the same bar update that the Enter methods are called. To submit the Exit orders, you should check if you are in a Long or Short position using Position.MarketPosition and then call your Exit methods to place the protective orders.

                The Exit methods to place the initial stops/targets should be called in OnExecutionUpdate() as seen in the SampleOnOrderUpdate reference sample from the help guide. These orders could also be handled in OnExecutionUpdate() when you want to change an order.

                See this reference sample demonstrating submitting and handling protective orders using OnOrderUpdate()/OnExecutionUpdate(): https://ninjatrader.com/support/help...and_onexec.htm

                Further, your prints should print out the actual value being compared in the conditions to see how those conditions are evaluating.

                For example, you should print out the isFirstOrderTpHitLong bool one line above the condition to see how that condition is evaluating. The code might look something like this:

                Code:
                Print("isFirstOrderTpHitLong: " + isFirstOrderTpHitLong);
                if (isFirstOrderTpHitLong == true)
                {
                double newStopPrice = Position.AveragePrice + (5 * TickSize);
                isFirstOrderTpHitLong = false;
                //ExitShortStopMarket(0, true, numOfContracts, stopLossPrice, StopName, orderName);
                ExitShortStopMarket(0, true, 1, newStopPrice, "Stp2Long", "LongEntry2");
                }

                This will allow you to see exactly if that bool variable is evaluating to true or false to confirm if the condition is true by reviewing the prints in the NinjaScript Output window.

                Brandon H.NinjaTrader Customer Service

                Comment


                  #9
                  Success!!!! Thank You!! Testing your test script made a light bulb go off.. Thanks!

                  Comment

                  Latest Posts

                  Collapse

                  Topics Statistics Last Post
                  Started by AaronKoRn, Today, 09:49 PM
                  0 responses
                  6 views
                  0 likes
                  Last Post AaronKoRn  
                  Started by carnitron, Today, 08:42 PM
                  0 responses
                  9 views
                  0 likes
                  Last Post carnitron  
                  Started by strategist007, Today, 07:51 PM
                  0 responses
                  10 views
                  0 likes
                  Last Post strategist007  
                  Started by StockTrader88, 03-06-2021, 08:58 AM
                  44 responses
                  3,976 views
                  3 likes
                  Last Post jhudas88  
                  Started by rbeckmann05, Today, 06:48 PM
                  0 responses
                  9 views
                  0 likes
                  Last Post rbeckmann05  
                  Working...
                  X