Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

Limit order and stop loss keep disappearing after strategy gets triggered

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

    Limit order and stop loss keep disappearing after strategy gets triggered

    Hello!

    So, my strategy is pretty simple. I look for particular candle patterns, for example a doji formation and an engulfing candle. Once the engulfing candle breaks and closes above the high of the doji, it triggers a limit order to go long. The limit order is the close[2] +1 (doji candle). Basically entering on a retest. The limit order and stop seem to appear for the bar after the engulfing candle, but then disappear when one more bar appears. I tried using triggerState and such but with no success. I'm thinking it's because my limit order refers to a previous bar (close[2]), and when new candles appear, then it loses track of where the limit order is supposed to be? I hope I'm explaining my strategy clearly. If you have any tips I'd really appreciate it. I'm not really a coder, and just use the strategy builder.

    Thanks a lot!

    #2
    Hello ujin765,

    Thank you for your post.

    "The limit order and stop seem to appear for the bar after the engulfing candle, but then disappear when one more bar appears"

    Are you resubmitting the order to keep it alive? You will need to save the limit price to a variable, and re-submit the order on each new bar to keep it alive.

    From the Help Guide:
    "By default, orders submitted via Entry() and Exit() methods automatically cancel at the end of a bar if not re-submitted"

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

    Please see this forum post which has Strategy Builder examples on keeping an order alive:
    https://forum.ninjatrader.com/forum/...596#post806596

    Please let me know if you have any other questions.

    Comment


      #3
      Hey Gaby,

      It's been a while since you answered my question, but I recently decided to get back to Ninjatrader after some time with other platforms.

      I did set the limit price as a variable, but it still cancels it on the next bar. Why could that be? Here's a snippet of the code:


      private double LimitPrice;


      .......(more code).....

      // Set 2
      ...(conditions...)
      {
      TriggerState = 1;
      EnterLongLimit(Convert.ToInt32(DefaultQuantity), (Open[2] + (12 * TickSize)) , @"Long1");
      SavedBar = Convert.ToInt32(CurrentBars[0]);
      LimitPrice = (Open[2] + (12 * TickSize)) ;
      }

      // Set 3
      if ((TriggerState == 1)
      && (Position.MarketPosition == MarketPosition.Flat))
      {
      EnterLongLimit(Convert.ToInt32(DefaultQuantity), LimitPrice, @"Long1");
      }


      I also tried splitting it into parts in the following way:

      TriggerState = 1;
      EnterLongLimit(Convert.ToInt32(DefaultQuantity), LimitPrice, @"Long1");
      SavedBar = Convert.ToInt32(CurrentBars[0]);
      LimitPrice = (Open[2] + (12 * TickSize)) ;
      }

      // Set 3
      if ((TriggerState == 1)
      && (Position.MarketPosition == MarketPosition.Flat))
      {
      EnterLongLimit(Convert.ToInt32(DefaultQuantity), LimitPrice, @"Long1");
      }


      ​I don't understand what the issue could be. Thanks for any help you can offer!
      Last edited by ujin765; 04-09-2024, 05:29 PM.

      Comment


        #4
        Hello,

        Are you resubmitting the order to keep it alive? The order needs to be re-submited on each new bar to keep it alive. I'm not sure what other sets you have, or what your set 2 conditions are since you don't list them here, but your Set 3 will only be true when you are flat and then submits the EnterLongLimit order so your position will be long on the next bar.

        If the expected trade(s) are not appearing, this would indicate that the condition to place the order is not evaluating as true and the order is not being submitted, or the order is being ignored for other reasons, or the order is being cancelled.

        To understand why the script is behaving as it is, such as placing orders or not placing orders or drawing objects when expected, it is necessary to add prints to the script that print the values used for the logic of the script to understand how the script is evaluating.

        In the strategy add prints (outside of any conditions) that print the date time of the bar and all values compared in every condition that places an order.

        The prints should include the time of the bar and should print all values from all variables and all hard coded values in all conditions that must evaluate as true for this action to be triggered. It is very important to include a text label for each value and for each comparison operator in the print to understand what is being compared in the condition sets.

        Prints will appear in the NinjaScript Output window (New > NinjaScript Output window).

        Further, enable TraceOrders which will let us know if any orders are being ignored and not being submitted when the condition to place the orders is evaluating as true.

        I am happy to assist you with analyzing the output from the output window.

        Run or backtest the script and when the output from the output window appears save this by right-clicking the output window and selecting Save As... -> give the output file a name and save -> then attach the output text file to your reply.

        Below is a link to a forum post that demonstrates using informative prints to understand behavior and includes a link to a video recorded using the Strategy Builder to add prints.


        Please let me know if I may further assist with analyzing the output or if you need any assistance creating a print or enabling TraceOrders.​

        Comment


          #5
          Hey Gaby, thanks for your reply!

          So, it seems after unlocking the script I managed to modify it so that the order stays active until cancelled. Seemed easier that way. Though we'll see, cause I still have some issues... I seem to be running into another problem and really don't get it.

          Below is the code for entries, exits, limit price, profit target, and stop loss. The question is, why wouldn't the profit target be working correctly? Below are the prints of what happened. And even there it lists the profit target correctly.

          // Calculate stop loss based on lowest low of the last 30 bars
          StopPrice = MIN(Low, MaxLookback)[0] - 8 * TickSize;;
          LimitPrice = Open[2] + 12 * TickSize;
          ProfitTarget = ((LimitPrice - StopPrice)*4); (I assume the number on its own is in ticks, and therefore I multiply it by 4, to give me a 1:1 profit/loss ratio.)

          // Submit entry order as limit order with stop loss and profit target
          EnterLongLimit(0, true, 1, LimitPrice, @"Long1");
          }

          // Check for stop loss hit
          if (Close[0] <= StopPrice && Position.MarketPosition == MarketPosition.Long)

          ExitLongStopMarket(1, StopPrice, @"stopLong", @"Long1");


          // Check for profit target reached
          if (Position.GetUnrealizedProfitLoss(PerformanceUnit. Ticks, Close[0]) >= ProfitTarget)
          {
          ExitLong(1, @"exitLong", @"Long1");


          Here's an example: Longed at 18241.75, Stop Loss automatically set at 18199.5. 18241.75(LimitPrice) - 18199.75(StopPrice) = 42.25*4 = 169(ProfitTarget)
          But it exits in weird places. And if I change the profit target, the exit may either stay the same, or move to another random place, and stay there for some other numbers too. It's like it only has two places it wants to exit. But the profit target is correctly reflected in print based on my changes, so I don't understand what could be the issue.

          Print examples:

          For ProfitTarget = ((LimitPrice - StopPrice)*4) :​

          4/2/2024 1:00:00 PM | Current Market Position: Long | Entry Price: 18241.75 | Stop Price: 18199.5 | Profit Target: 169
          Enabling NinjaScript strategy 'RGRGemini3/274391624' : On starting a real-time strategy - StartBehavior=WaitUntilFlat EntryHandling=All entries EntriesPerDirection=1 StopTargetHandling=Per entry execution ErrorHandling=Stop strategy, cancel orders, close positions ExitOnSessionClose=True / triggering 30 seconds before close SetOrderQuantityBy=Strategy ConnectionLossHandling=Recalculate DisconnectDelaySeconds=10 CancelEntriesOnStrategyDisable=False CancelExitsOnStrategyDisable=False Calculate=On bar close IsUnmanaged=False MaxRestarts=4 in 5 minutes​

          EXITED at 18289.75 instead of 18283.75

          or at ProfitTarget = 100

          4/2/2024 1:00:00 PM | Current Market Position: Long | Entry Price: 18241.75 | Stop Price: 18199.5 | Profit Target: 120
          Enabling NinjaScript strategy 'RGRGemini3/274391624' : On starting a real-time strategy - StartBehavior=WaitUntilFlat EntryHandling=All entries EntriesPerDirection=1 StopTargetHandling=Per entry execution ErrorHandling=Stop strategy, cancel orders, close positions ExitOnSessionClose=True / triggering 30 seconds before close SetOrderQuantityBy=Strategy ConnectionLossHandling=Recalculate DisconnectDelaySeconds=10 CancelEntriesOnStrategyDisable=False CancelExitsOnStrategyDisable=False Calculate=On bar close IsUnmanaged=False MaxRestarts=4 in 5 minutes

          Also EXITED at 18289.75

          But if ProfitTarget = 40

          4/2/2024 12:40:00 PM | Current Market Position: Long | Entry Price: 18241.75 | Stop Price: 18199.5 | Profit Target: 40
          Enabling NinjaScript strategy 'RGRGemini3/274391624' : On starting a real-time strategy - StartBehavior=WaitUntilFlat EntryHandling=All entries EntriesPerDirection=1 StopTargetHandling=Per entry execution ErrorHandling=Stop strategy, cancel orders, close positions ExitOnSessionClose=True / triggering 30 seconds before close SetOrderQuantityBy=Strategy ConnectionLossHandling=Recalculate DisconnectDelaySeconds=10 CancelEntriesOnStrategyDisable=False CancelExitsOnStrategyDisable=False Calculate=On bar close IsUnmanaged=False MaxRestarts=4 in 5 minutes

          EXITED at 18263.50

          So it seems to be able to calculate the profit target correctly as per the code above, but I don't understand why it exits at those places. Can you provide any possible insight into creating profit targets in this way? Thank you!
          Last edited by ujin765; 04-11-2024, 07:10 PM.

          Comment


            #6
            Hello,

            Unfortunately, these prints aren't descriptive enough to be able to tell why it is exiting at that price. The prints should include the time of the bar and should print all values from all variables and all hard coded values in all conditions that must evaluate as true for this action to be triggered. It is very important to include a text label for each value and for each comparison operator in the print to understand what is being compared in the condition sets.

            A good example of a print is below:

            Print("Close[0]: " + Close[0] + " & MarketPosition: " + Position.MarketPosition + " = MarketPosition.Long");
            if (Close[0] <= StopPrice && Position.MarketPosition == MarketPosition.Long)

            Please add similarly descriptive prints for all conditions in your script in order to analyze the output.

            Additionally, I see you are calculating ProfitTarget using ((LimitPrice - StopPrice)*4), however I don't see where you actually use this value to submit an order to exit at this price. Where are you using this variable to submit an order to exit at your calculated ProfitTarget?

            Comment


              #7
              if (Position.GetUnrealizedProfitLoss(PerformanceUnit. Ticks, Close[0]) >= ProfitTarget)
              {
              ExitLong(1, @"exitLong", @"Long1");

              Wouldn't this code be sufficient to exit at the profit target? It states that if my position has reached or exceeded the number of ticks as dictated by ProfitTarget, then exit position via market order. Is this incorrect? I've used this in the past and it seemed to have worked. And I will add more description to the print following your example. Thanks!​

              Comment


                #8
                Hello,

                That could work, apologies as I missed that was where you were using ProfitTarget in my first response. That being said, if it's not working as expected adding a print for this condition and enabling TraceOrders would help understand why this statement is working as expected.

                Please let us know if you have any further questions.

                Comment

                Latest Posts

                Collapse

                Topics Statistics Last Post
                Started by NullPointStrategies, Yesterday, 05:17 AM
                0 responses
                63 views
                0 likes
                Last Post NullPointStrategies  
                Started by argusthome, 03-08-2026, 10:06 AM
                0 responses
                139 views
                0 likes
                Last Post argusthome  
                Started by NabilKhattabi, 03-06-2026, 11:18 AM
                0 responses
                75 views
                0 likes
                Last Post NabilKhattabi  
                Started by Deep42, 03-06-2026, 12:28 AM
                0 responses
                45 views
                0 likes
                Last Post Deep42
                by Deep42
                 
                Started by TheRealMorford, 03-05-2026, 06:15 PM
                0 responses
                50 views
                0 likes
                Last Post TheRealMorford  
                Working...
                X