Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

Creating a SL, and 2 target profits.

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

    #16
    Hello,

    To understand why the script is behaving as it is, such as placing orders or not placing orders 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.

    The debugging print output should clearly show what the condition is, what time the conditions are being compared, all values being compared, and how they are being compared.

    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.

    After enabling TraceOrders remove the instance of the strategy from the Configured list in the Strategies window and add a new instance of the strategy from the Available list.


    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 support article that demonstrates using informative prints to understand behavior and includes a link to a video recorded using the Strategy Builder to add prints.

    https://support.ninjatrader.com/s/ar...nd-TraceOrders

    Comment


      #17
      Hi,

      This is an image so you can see how the SL are splitting after target 1 is hit.

      Comment


        #18
        and this is the text file from the output window. I hope these print statements can help you help me.
        Attached Files

        Comment


          #19
          Hello Joseph,

          Unfortunately this output isn't descriptive enough to know what is being compared in the conditions. If you need an example of a print, please let me know which one of your conditions you would like an example for.

          Additionally, the output doesn't have any information from TraceOrders. Make sure TraceOrders is set to true in State.SetDefaults. After doing so, remove the old strategy instance and add a new instance to pull in the new defaults.

          Comment


            #20
            I did as you suggested and added the trace orders.
            what type of prints do you need to debug what is happening after target 1 is hit?
            I need half the position to close with target 1 so that there is one SL for half the position and only target 2 remaining.
            Attached Files

            Comment


              #21
              We need descriptive prints for all conditions in the script.

              I recommend reading this support article for an example of how to create a descriptive print.

              Comment


                #22
                I hope this is better now.
                Attached Files

                Comment


                  #23
                  Hello Joseph,

                  Unfortunately these prints are similar to the previous ones posted where they aren't descriptive enough to tell what is being compared in the conditions.

                  If you would like assistance creating a print, please let me know of a specific condition in your script and I can provide you with an example print.

                  You can also contact a professional NinjaScript Consultant who would be eager to create or modify this script at your request or assist you with your script. The NinjaTrader Ecosystem has affiliate contacts who provide educational as well as consulting services.

                  Please let me know if you would like a list of affiliate consultants who would be happy to create this script or any others at your request or provide one on one educational services.

                  Comment


                    #24
                    Hi,

                    For now I will try by myself before turning to professional help.

                    The code for the onExecutionUpdate() is as follows:

                    The problem arises when target 1 is hit and the stop loss isn't behaving as I want it to.

                    half the position is closing and target 1 is being closed after it is hit. half the stop loss is moving to break even plus 2 pips but the first half of the stop is remaining live which I don't understand why, even when I have explicitly cancelled the SL.

                    protected override void OnExecutionUpdate(Execution execution, string executionId, double price, int quantity, MarketPosition marketPosition, string orderId, DateTime time)
                    {
                    // Print execution details for debugging
                    Print(string.Format("[{0}] Execution Update: Order: {1}, Price: {2}, Quantity: {3}, MarketPosition: {4}, OrderID: {5}",
                    Time[0], execution.Order.Name, price, quantity, marketPosition, orderId));

                    // Handle BullishEntry1 execution
                    if (execution.Order != null && execution.Order.Name == "BullishEntry1")
                    {
                    sumFilled += execution.Quantity;
                    if (execution.Order.OrderState == OrderState.Filled && sumFilled == execution.Order.Filled)
                    {
                    entryPrice1 = execution.Order.AverageFillPrice; // Use AverageFillPrice to capture entry price
                    stopLossOrder1 = ExitLongStopMarket(0, true, firstPositionSize, stopLossPrice, "Stop1", "BullishEntry1");
                    targetOrder1 = ExitLongLimit(0, true, firstPositionSize, tp1Price, "Target1", "BullishEntry1");

                    Print("[" + Time[0] + "] BullishEntry1 filled. SL and Target set for first position.");

                    // Enter the second position once the first entry fills
                    EnterLong(secondPositionSize, "BullishEntry2");
                    }
                    }

                    // Handle BullishEntry2 execution
                    if (execution.Order != null && execution.Order.Name == "BullishEntry2" && execution.Order.OrderState == OrderState.Filled)
                    {
                    stopLossOrder2 = ExitLongStopMarket(0, true, secondPositionSize, stopLossPrice, "Stop2", "BullishEntry2");
                    targetOrder2 = ExitLongLimit(0, true, secondPositionSize, tp2Price, "Target2", "BullishEntry2");

                    Print("[" + Time[0] + "] BullishEntry2 filled. SL and Target set for second position.");
                    }

                    // Adjust stop-loss when TP1 is hit
                    if (execution.Order != null && execution.Order.Name == "Target1" && execution.Order.OrderState == OrderState.Filled)
                    {
                    Print("[" + Time[0] + "] Target1 hit.");

                    // Cancel existing stop-loss for BullishEntry2
                    if (stopLossOrder2 != null && stopLossOrder2.OrderState == OrderState.Working)
                    {
                    CancelOrder(stopLossOrder2);
                    stopLossOrder2 = null;

                    Print("[" + Time[0] + "] Stop-loss for BullishEntry2 canceled.");
                    }

                    // Adjust stop-loss to breakeven + 2 pips for the second position
                    double newStopPrice = entryPrice1 + (BreakEvenPipAdjustment * pipSize);
                    stopLossOrder2 = ExitLongStopMarket(0, true, secondPositionSize, newStopPrice, "AdjustedStop", "BullishEntry2");

                    Print(string.Format("[{0}] TP1 hit. Stop-loss for BullishEntry2 moved to breakeven + {1} pips. New Stop Price: {2}", Time[0], BreakEvenPipAdjustment, newStopPrice));
                    }

                    // Reset orders after stop-loss or target is hit for both entries
                    if ((stopLossOrder1 != null && stopLossOrder1 == execution.Order) || (targetOrder1 != null && targetOrder1 == execution.Order))
                    {
                    if (execution.Order.OrderState == OrderState.Filled)
                    {
                    Print("[" + Time[0] + "] Stop-loss or Target1 filled. Resetting SL1 and Target1.");
                    stopLossOrder1 = null;
                    targetOrder1 = null;
                    }
                    }

                    if ((stopLossOrder2 != null && stopLossOrder2 == execution.Order) || (targetOrder2 != null && targetOrder2 == execution.Order))
                    {
                    if (execution.Order.OrderState == OrderState.Filled)
                    {
                    Print("[" + Time[0] + "] Stop-loss or Target2 filled. Resetting SL2 and Target2.");
                    stopLossOrder2 = null;
                    targetOrder2 = null;
                    }
                    }
                    }​

                    Comment


                      #25
                      Hello,

                      Here is an example print for that first condition.

                      Code:
                      Print(Times[0][0] + " execution.Order: " + execution.Order + " != null & execution.Order.Name: " + execution.Order.Name + " = BullishEntry1");
                      if (execution.Order != null && execution.Order.Name == "BullishEntry1")
                      {
                      }​
                      You'll need to make similarly descriptive prints for all conditions in your strategy, including conditions you may have within OnBarUpdate() or OnOrderUpdate() etc.

                      Comment


                        #26
                        Hi,

                        Hope this is more informative now.
                        Attached Files

                        Comment


                          #27
                          Hello Joseph,

                          These prints still don't tell us anything about what is being compared in the conditions.

                          Code:
                          17/09/2024 16:00:00 Stop-loss for BullishEntry2 moved to breakeven + 2 pips. New Stop Price: 185.989
                          17/09/2024 16:00:00 Stop-loss or Target1 filled. Resetting SL1 and Target1.
                          17/09/2024 17:00:00 Strategy is in real-time state.
                          17/09/2024 17:00:00 Checking Bullish Pin Bar conditions.
                          
                          17/09/2024 17:00:00 Execution Update: Order: Target2, Price: 186.985, Quantity: 2000, MarketPosition: Short, OrderID: dfe1691dbe134f99b963a9fd7aa8b230
                          17/09/2024 17:00:00 Checking if execution.Order: orderId='dfe1691dbe134f99b963a9fd7aa8b230' account='Playback101' name='Target2' orderState=Filled instrument='GBPJPY'  ​


                          I also do not see the example print provided - all prints should be modeled after this print. Note how the example print includes all comparison operators so we can tell exactly what the values are in this condition and how they are being compared.

                          Code:
                          Print(Times[0][0] + " execution.Order: " + execution.Order + " != null & execution.Order.Name: " + execution.Order.Name + " = BullishEntry1");
                          if (execution.Order != null && execution.Order.Name == "BullishEntry1")
                          {
                          }​

                          You can also contact a professional NinjaScript Consultant who would be eager to create or modify this script at your request or assist you with your script. The NinjaTrader Ecosystem has affiliate contacts who provide educational as well as consulting services.

                          Please let me know if you would like a list of affiliate consultants who would be happy to create this script or any others at your request or provide one on one educational services.

                          Comment


                            #28
                            I will update you that I managed to solve my issues. Thank you for your help.

                            I have another question which is baffling me.

                            On the one hand, I need final authentication that the candle which will create my entry signal has been closed - so for this I am using Calculate = Calculate.OnBarClose; but on the other hand, I want the stops to move to break even, if the price comes within a certain distance of my target - say 2-3 pips (without touching it) which means that my observation was correct, I just placed my target 2-3 pips too far and instead of the price reversing against me and stopping me out for the whole position, moving the stops will protect me.
                            In order to do this though, I need to use Calculate = Calculate.OnPriceChange;
                            But these are contradicting as sometimes, before the candle has closed, it will give me a signal for entry but on its close it is no longer a valid signal.

                            Do you have any advice for this?

                            Comment


                              #29
                              Hello Joseph,

                              To clarify, you are saying you need to use two Calculate settings?

                              If you want to do something OnBarClose while keeping the script OnPriceChange, you can use IsFirstTickOfBar to simulate OnBarClose behavior.



                              Example script: https://ninjatrader.com/support/help...either_cal.htm

                              Comment


                                #30
                                Great!! This is what I was looking for!! Thank you very much!

                                Comment

                                Latest Posts

                                Collapse

                                Topics Statistics Last Post
                                Started by Geovanny Suaza, 02-11-2026, 06:32 PM
                                0 responses
                                578 views
                                0 likes
                                Last Post Geovanny Suaza  
                                Started by Geovanny Suaza, 02-11-2026, 05:51 PM
                                0 responses
                                334 views
                                1 like
                                Last Post Geovanny Suaza  
                                Started by Mindset, 02-09-2026, 11:44 AM
                                0 responses
                                101 views
                                0 likes
                                Last Post Mindset
                                by Mindset
                                 
                                Started by Geovanny Suaza, 02-02-2026, 12:30 PM
                                0 responses
                                554 views
                                1 like
                                Last Post Geovanny Suaza  
                                Started by RFrosty, 01-28-2026, 06:49 PM
                                0 responses
                                551 views
                                1 like
                                Last Post RFrosty
                                by RFrosty
                                 
                                Working...
                                X