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

Exit Execution

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

    Exit Execution

    Hello, I have a strategy that is set to Calculate.OnBarClose

    I have some logic in OnOrderUpdate that will set my profit & stop loss as below

    PHP Code:
    protected override void OnOrderUpdate(Cbi.Order orderdouble limitPricedouble stopPriceint quantityint filleddouble averageFillPriceOrderState orderStateDateTime timeErrorCode errorstring comment)
            {
                if(
    order.OrderState == OrderState.Filled)
                {
                    if (
    order.IsShort)
                    {
                        
    ExitShortStopMarket((double)openingRangeHigh, @"cover loss", @"short");
                        
    ExitShortLimit(StrategyHelpers.GetProfitTargetBasedOnRR(Close[0], (double)openingRangeHighRR), @"cover profit", @"short");
                    }
                    else
                    {
                        
    ExitLongStopMarket((double)openingRangeLow, @"sell loss", @"long");
                        
    ExitLongLimit(StrategyHelpers.GetProfitTargetBasedOnRR(Close[0], (double)openingRangeLowRR), "sell profit", @"long");
                    }
                }
                
            }&
    #8203; 
    My question is will the exits trigger when price is hit or will it also wait for the bar close?

    #2
    Hello proptradingshop,

    Thank you for your post.

    As a heads up, if you are basing your strategy logic based on order fills, we recommend you do this from OnExecutionUpdate() instead.

    "For triggering actions such as the submission of a stop loss order and target order using custom OCO logic when your entry order is filled, we recommend working directly in OnExecutionUpdate() instead.​"

    "Critical: If you want to drive your strategy logic based on order fills you must use OnExecutionUpdate() instead of OnOrderUpdate(). OnExecutionUpdate() is always triggered after OnOrderUpdate(). There is internal strategy logic that is triggered after OnOrderUpdate() is called but before OnExecutionUpdate() that can adversely affect your strategy if you are relying on tracking fills within OnOrderUpdate().​"



    OnExecutionUpdate() is called on an incoming execution of an order managed by a strategy. It will not wait for the bar to close, the Calculate setting only affects how often OnBarUpdate() is called.



    Please let me know if you have any further questions.
    Gaby V.NinjaTrader Customer Service

    Comment


      #3
      Thank you NinjaTrader_Gaby for the resources. I have moved my code to OnExecutionUpdate...however I am unable to see my stop loss or profit target being hit within backtests. By glancing at the code can you tell why?

      I have validated my print statements and have my targets set accordingly, just seems that when price is breaching these values the orders are not being executed.

      PHP Code:
              protected override void OnExecutionUpdate(Execution executionstring executionIddouble priceint quantityMarketPosition marketPositionstring orderIdDateTime time)
              {
                  
      base.OnExecutionUpdate(executionexecutionIdpricequantitymarketPositionorderIdtime);

                  if (
      execution.Order.OrderState == OrderState.Filled && (execution.Order.Name.Equals(@"buy") || execution.Order.Name.Equals(@"short")))
                  {
                      {
                          
      Cbi.Order stopOrder = new Cbi.Order();
                          
      Cbi.Order targetOrder = new Cbi.Order();
                          if (
      execution.Order.IsShort)
                          {
                              
      stopOrder ExitShortStopMarket((double)openingRangeHigh, @"cover loss", @"short", );
                              
      targetOrder ExitShortLimit(StrategyHelpers.GetProfitTargetBasedOnRR(Close[0], (double)openingRangeHighRR), @"cover profit", @"short");
                              
      stopOrder.IsLiveUntilCancelled true;
                              
      targetOrder.IsLiveUntilCancelled true;
                              Print(
      Bars.Instrument.FullName " Setting Stop Loss @" + (double)openingRangeHigh " Setting Profit Target @" StrategyHelpers.GetProfitTargetBasedOnRR(Close[0], (double)openingRangeHighRR));
                          }
                          if (
      execution.Order.IsLong)
                          {
                              
      stopOrder ExitLongStopMarket((double)openingRangeLow);
                              
      targetOrder ExitLongLimit(StrategyHelpers.GetProfitTargetBasedOnRR(Close[0], (double)openingRangeLowRR), "sell profit", @"long");
                            
                              Print(
      Bars.Instrument.FullName " Setting Stop Loss @" + (double)openingRangeLow " Setting Profit Target @" StrategyHelpers.GetProfitTargetBasedOnRR(Close[0], (double)openingRangeLowRR));
                          }

                          
      stopOrder.IsLiveUntilCancelled true;
                          
      targetOrder.IsLiveUntilCancelled true;
                      }
                  }
              }&
      #8203; 

      Comment


        #4
        Hello proptradingshop,

        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.​
        Gaby V.NinjaTrader Customer Service

        Comment


          #5
          Thank you NinjaTrader_Gaby. I figured the issue above was related to a null reference and fixed it. However I do have one other question. It seems that when running my strategy live, only 1 of the orders is ever placed, since my stopOrder is first in the code it will be placed but not my targetOrder. I can switch the order and have my targetOrder be placed first. I am using TDA. How can I have it be a OCO order for my take profit and stop loss.

          Comment


            #6
            Hello proptradingshop,

            With the managed approach, you cannot tie orders via true OCO. This would only be possible using the Unmanaged Approach. With the Managed Approach, you can however tie orders together using signal names. You can specify the fromEntrySignal in your exit orders to tie the exit to the entry and exit the position quantity represented by the actual entry.

            ExitLongStopMarket(double stopPrice, string fromEntrySignal)



            ExitLongLimit(double limitPrice, string fromEntrySignal)



            Please let me know if you have any other questions.
            Gaby V.NinjaTrader Customer Service

            Comment


              #7
              Thank you NinjaTrader_Gaby for your support. Good catch, I was missing the fromSignal param on my ExitLongStopMarket​ but can you confirm that both orders would post on TDA. I added the fromSignal and I am only seeing the stopOrder post to TDA not the targetOrder.

              Comment


                #8
                Hello proptradingshop,

                I recommend adding prints and enabling TraceOrders to confirm anything. TraceOrders in particular will let us know if/when orders are being submitted, ignored, cancelled, or rejected when the conditions for submit your target order are true.

                Please let us know if we can assist further.
                Gaby V.NinjaTrader Customer Service

                Comment


                  #9
                  One last question, NinjaTrader_Gaby. If I have a strategy running live, I then make updates to the code/strategy. I then disable and reenable the strategy. Would the new updates take effect? Or would it require me to delete and recreate the strategy again?

                  Comment


                    #10
                    Hello,

                    If this is on a chart, you would need to right-click within the chart > Reload NinjaScript. If you made changes in State.SetDefaults, this would require removing that instance of the strategy and then adding a new instance.

                    From the Strategies tab of the Control Center, you should remove the old instance and add a new instance when you make a change to the code in order for it to update.

                    Please let me know if you have any further questions.
                    Gaby V.NinjaTrader Customer Service

                    Comment

                    Latest Posts

                    Collapse

                    Topics Statistics Last Post
                    Started by fx.practic, 10-15-2013, 12:53 AM
                    5 responses
                    5,406 views
                    0 likes
                    Last Post Bidder
                    by Bidder
                     
                    Started by Shai Samuel, 07-02-2022, 02:46 PM
                    4 responses
                    98 views
                    0 likes
                    Last Post Bidder
                    by Bidder
                     
                    Started by DJ888, Yesterday, 10:57 PM
                    0 responses
                    8 views
                    0 likes
                    Last Post DJ888
                    by DJ888
                     
                    Started by MacDad, 02-25-2024, 11:48 PM
                    7 responses
                    160 views
                    0 likes
                    Last Post loganjarosz123  
                    Started by Belfortbucks, Yesterday, 09:29 PM
                    0 responses
                    9 views
                    0 likes
                    Last Post Belfortbucks  
                    Working...
                    X