Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

ExitShortStopMarket and OnBarUpdate

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

    ExitShortStopMarket and OnBarUpdate

    I just can't manage to write a working strategy that checks at OnBarUpdate whether a position is open and sets a StopLoss.
    I have tried it with ExitShortStopMarket and with SetStopLoss.
    What am I doing wrong?​


    Code:
      protected override void OnBarUpdate()
            {
                if (PositionAccount != null && PositionAccount.MarketPosition != MarketPosition.Flat) // Es gibt eine offene Position
                {
                    bool hasStopLoss = false;
    
                    if (Orders != null && Orders.Count > 0) // Überprüfen, ob Orders nicht null und nicht leer ist
                    {
                        foreach (Order order in Orders)
                        {
                            if (order.OrderType == OrderType.StopMarket || order.OrderType == OrderType.StopLimit)
                            {
                                hasStopLoss = true;
                                break;
                            }
                        }
                    }
    
                    if (!hasStopLoss) // Falls kein Stop-Loss existiert, einen setzen
                    {
                        double stopPrice;
    
                        if (PositionAccount.MarketPosition == MarketPosition.Long) // Für Long-Position
                        {
                            stopPrice = PositionAccount.AveragePrice - (stopLossTicks * TickSize);
                        }
                        else // Für Short-Position
                        {
                            stopPrice = PositionAccount.AveragePrice + (stopLossTicks * TickSize);
                        }
    
                        // Stop-Loss-Order setzen und überprüfen
                        Order longStopOrder = ExitLongStopMarket(stopPrice);
                        Order shortStopOrder = ExitShortStopMarket(stopPrice);
    
                        
                        // Überprüfung, ob die Stop-Orders erfolgreich gesetzt wurden
                        if (longStopOrder != null)
                        {
                            Print("Long Stop-Loss-Order Status: " + longStopOrder.OrderState);
                            if (longStopOrder.OrderState == OrderState.Working)
                            {
                                Print("Long Stop-Loss-Order erfolgreich gesetzt.");
                            }
                        }
                        else
                        {
                            Print("Fehler beim Setzen der Long Stop-Loss-Order. Status: " + longStopOrder?.OrderState);
                        }
    
                        if (shortStopOrder != null)
                        {
                            Print("Short Stop-Loss-Order Status: " + shortStopOrder.OrderState);
                            if (shortStopOrder.OrderState == OrderState.Working)
                            {
                                Print("Short Stop-Loss-Order erfolgreich gesetzt.");
                            }
                        }
                        else
                        {
                            Print("Fehler beim Setzen der Short Stop-Loss-Order. Status: " + shortStopOrder?.OrderState);
                        }
                    }​
    Last edited by knobi4711; 02-12-2025, 03:37 AM.

    #2
    Hello knobi4711,

    Welcome to the NinjaTrader forums!

    When using Set methods, these should be submitted before calling the entry order method, not after.

    "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."
    Join the official NinjaScript Developer Community for comprehensive resources, documentation, and community support. Build custom indicators and automated strategies for the NinjaTrader platforms with our extensive guides and APIs.


    When using Exit methods, it would be suggested to submit a stop and limit order in OnExecutionUpdate() at the moment the entry order fills.

    Below is a link to an example.


    Further, you are assigning order objects to variables directly from the method call and not from the order object parameter provided in OnOrderUpdate().
    Orders should only be assigned to variables from the order object parameter from OnOrderUpdate().

    "OnOrderUpdate() will run inside of order methods such as EnterLong() or SubmitOrderUnmanaged(), therefore attempting to assign an order object outside of OnOrderUpdate() may not return as soon as expected. If your strategy is dependent on tracking the order object from the very first update, you should try to match your order objects by the order.Name (signal name) from during the OnOrderUpdate() as the order is first updated.​"
    Join the official NinjaScript Developer Community for comprehensive resources, documentation, and community support. Build custom indicators and automated strategies for the NinjaTrader platforms with our extensive guides and APIs.


    Further, your stop order must have a valid price. A sell stop must have the stop price below the bid, a buy stop must have the price above the ask.

    See the support article below with sample code.



    With all that said, use prints and TraceOrders to understand why your order is not being submitted or filled.

    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 triggers the action.
    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.
    Last, print the order.ToString() at the top of the OnOrderUpdate() override, as this will show us when orders become working and are being filled, and print the GetCurrentAsk() and GetCurrentBid() in OnOrderUpdate() as well so we can see what the market price is at the time of a fill.

    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.


    Let me know the date and time the behavior occurred or when you are expecting the behavior to occur.

    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.​
    Chelsea B.NinjaTrader Customer Service

    Comment

    Latest Posts

    Collapse

    Topics Statistics Last Post
    Started by gustavobp, Today, 02:50 AM
    0 responses
    3 views
    0 likes
    Last Post gustavobp  
    Started by rubiijonson, Today, 01:02 AM
    0 responses
    4 views
    0 likes
    Last Post rubiijonson  
    Started by fkronloff, Today, 12:25 AM
    0 responses
    3 views
    0 likes
    Last Post fkronloff  
    Started by Zadomani, Yesterday, 11:39 PM
    0 responses
    14 views
    0 likes
    Last Post Zadomani  
    Started by ToNovy, 01-27-2025, 11:22 PM
    20 responses
    198 views
    0 likes
    Last Post ToNovy
    by ToNovy
     
    Working...
    X