Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

SetStopLoss Problem

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

    SetStopLoss Problem

    Hello,

    I'm having an issue with using the SetStopLoss code.

    This is part of my code that sets the StopLoss.


    - The line of code for setting up long positions. This line of code works very well.
    Code:
         
            private void postavi_limit_order(double cijenaaa, string pozicija)
            {
                if (pozicija == "Long")
                {
                    EnterLongLimit(cijenaaa, "test1");
                }
                if (pozicija == "Short")
                {
                    EnterShortLimit(cijenaaa, "test1");
                }
            }​

    - This line of code checks when the Limit order is filled and sets the StopLoss
    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)
            {
                if (order.OrderState.ToString() == "Filled")
                {
                    Print("Start SL");
                    nalazim_se_u_tredu = true;
                    if (pozicija == "Long")
                        SetStopLoss(CalculationMode.Price, SL_cijena - 0.25);
    
                    if (pozicija == "Short")
                        SetStopLoss(CalculationMode.Price, SL_cijena + 0.25);
                }
            }​
    When in a Long position, the SetStopLoss function sets the StopLoss correctly.

    But when in a Short position, the SetStopLoss function doesn't set the StopLoss correctly. It sets it as "Action: Buy to cover - Type: Stop Market" instead of "Buy - Stop Market". When the current candle closes, the following problem occurs. Image attached for reference.


    Please assist me in identifying where I am making a mistake and why?

    Thanks


    #2
    Hello Filip385,

    Thank you for your post.

    "Buy" is used for a long entry while "Buy to cover" is used to exit a short entry. This is why you are seeing Buy to cover for the short position's stop loss.

    Please note that while you can call SetStopLoss() in OnOrderUpdate(), we would recommend using Exit methods and following the SampleOnOrderUpdate reference sample that demonstrates using OnOrderUpdate() and OnExecution() to enter protective orders. This sample script below demonstrates:




    "Stop price can't be changed below the market."

    This message means that the strategy attempted to change an order to the wrong side of the market. Buy stop market orders must be placed above the current Ask price, and sell stop market orders must be placed below the current Bid price.

    You can use GetCurrentBid() and GetCurrentAsk() to make sure that the price you are submitting or changing the order to is a valid price and on the correct side of the market.

    Help Guide: NinjaScript > Language Reference > Common > Analytical > GetCurrentBid()
    Help Guide: NinjaScript > Language Reference > Common > Analytical > GetCurrentAsk()

    Since you are using Set methods, like SetStopLoss(), with CalculationMode.Price please note that these cannot be unset so they will continue to have the previous entry’s price so when a new entry is submitted. This can also cause this error.

    From the Help Guide on SetStopLoss():

    ”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.”

    Help Guide: NinjaScript > Language Reference > Strategy > Order Methods > Managed Approach > SetStopLoss()

    Set methods should always be set or reset before the entry is called with CalculationMode.Ticks before calling a new entry. They can then be adjusted to a specific price after the entry fills.

    Please let me know if I can assist further.​

    Comment


      #3
      Thank you for your response.

      Now, I'm trying to set up a Stop Loss with ExitLongStopMarket
      Here is my code:

      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)
              {
      
                  if (orderState == OrderState.Filled && order.Name == "ES JUN24#Long#1")
                  {
                        Print("STATUS - OK");
                        ExitLongStopMarket(0, true, 2, 5248.75, "ES JUN24#Long#1SL", "ES JUN24#Long#1");    
                  }
      
             }​
      In the image, you can see the current position with all parameters.

      In the NinjaScript Output, I get the message 'STATUS - OK,' but the strategy doesn't set the Stop Loss.

      Please, where am I going wrong? Could you write the code to set up the Stop Loss for my example?

      Thanks
      Attached Files

      Comment


        #4
        Hello Filip385,

        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).

        It is also helpful to set TraceOrders to true in State.Configure as well as print the order object in OnOrderUpdate().

        TraceOrders will output to the NinjaScript Output window a message when orders are being submitted, ignored, cancelled, or rejected.

        Printing the order object in OnOrderUpdate() will allow you to track the progression of the order from submitted, to working, to filled, cancelled, or rejected.

        These tools will let you know what happens to the order.
        TraceOrders - https://ninjatrader.com/support/help...raceorders.htm
        OnOrderUpdate() - https://ninjatrader.com/support/help...rderupdate.htm​.

        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

        Latest Posts

        Collapse

        Topics Statistics Last Post
        Started by NullPointStrategies, Today, 05:17 AM
        0 responses
        53 views
        0 likes
        Last Post NullPointStrategies  
        Started by argusthome, 03-08-2026, 10:06 AM
        0 responses
        130 views
        0 likes
        Last Post argusthome  
        Started by NabilKhattabi, 03-06-2026, 11:18 AM
        0 responses
        70 views
        0 likes
        Last Post NabilKhattabi  
        Started by Deep42, 03-06-2026, 12:28 AM
        0 responses
        44 views
        0 likes
        Last Post Deep42
        by Deep42
         
        Started by TheRealMorford, 03-05-2026, 06:15 PM
        0 responses
        49 views
        0 likes
        Last Post TheRealMorford  
        Working...
        X