Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

SampleOnOrderUpdate ==> Short

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

    SampleOnOrderUpdate ==> Short

    Hello to the Forum,
    please support me with the following question:

    I'm trying to rewrite SampleOnOrderUpdate to the short position.

    For this I use the following code:

    PHP Code:
    
    namespace NinjaTrader.NinjaScript.Strategies
    {
        public class SampleOnOrderUpdate : Strategy
        {
            private Order entryOrder                        = null;
            private Order stopOrder                         = null;
            private Order targetOrder                       = null;
    
            private Order entryOrderShort                    = null;
            private Order stopOrderShort                    = null;
            private Order targetOrderShort                  = null;
    
            bool tradeLong, tradeShort, testBreakEven;
            double deltaBreakEven;
    
            protected override void OnStateChange()
            {
                #region settings
    
                if (State == State.SetDefaults)
                {
                    Description                        = @"Sample ";
                    Name                            = "SampleOnOrderUpdate";
                    Calculate                       = Calculate.OnEachTick;
                    EntriesPerDirection             = 1;
                    EntryHandling                   = EntryHandling.AllEntries;
                    IsExitOnSessionCloseStrategy    = true;
                    ExitOnSessionCloseSeconds       = 30;
                    IsFillLimitOnTouch              = false;
                    MaximumBarsLookBack             = MaximumBarsLookBack.TwoHundredFiftySix;
                    OrderFillResolution             = OrderFillResolution.Standard;
                    Slippage                        = 0;
                    StartBehavior                   = StartBehavior.WaitUntilFlat;
                    TimeInForce                     = TimeInForce.Gtc;
                    TraceOrders                     = false;
                    RealtimeErrorHandling           = RealtimeErrorHandling.StopCancelClose;
                    StopTargetHandling              = StopTargetHandling.PerEntryExecution;
                    BarsRequiredToTrade             = 20;
                }
    
                else if (State == State.Realtime)
                {
                    if (entryOrder  != null) entryOrder =  GetRealtimeOrder(entryOrder);
                    if (stopOrder   != null) stopOrder =   GetRealtimeOrder(stopOrder);
                    if (targetOrder != null) targetOrder = GetRealtimeOrder(targetOrder);
    
                    //  Short
                    if (entryOrderShort != null)
                    entryOrderShort = GetRealtimeOrder(entryOrderShort);
                    if (stopOrderShort != null)
                    stopOrderShort =  GetRealtimeOrder(stopOrderShort);
                    if (targetOrderShort!= null)
                    targetOrderShort = GetRealtimeOrder(targetOrderShort);
                }
    
                #endregion
            }
    
            protected override void OnBarUpdate()
            {
                tradeLong = false;
                tradeShort = true;
    
                if (State == State.Realtime)
                {
                #region Long    
    
                if (tradeLong) // OCO ==> ++
                {    
                    if (entryOrder == null && Close[0] > Open[0]
                    && CurrentBar > BarsRequiredToTrade)
                    {EnterLong(1, "MyEntry");}
    
                    // BreakEven
                    if (Position.MarketPosition == MarketPosition.Long
                    && Close[0] >= Position.AveragePrice + 5)
                    {
                        if (stopOrder != null
                        && stopOrder.StopPrice < Position.AveragePrice)
                        {
                            stopOrder = ExitLongStopMarket(0, true, stopOrder.Quantity,
                            Position.AveragePrice + 3, "MyStop", "MyEntry"); // Trailing ++
                        }
                    }    
                }
    
                #endregion
    
                #region Short
    
                if (tradeShort)
                {    
                    if (Position.AveragePrice > 0) deltaBreakEven =
                    Position.AveragePrice - 10;
                    testBreakEven = Close[0] < (deltaBreakEven);
    
                    if (entryOrderShort == null && Close[0] < Open[0]
                    && CurrentBar > BarsRequiredToTrade)
                    {EnterShort(1, "MyEntryShort");}
    
                    // BreakEven
                    if (Position.MarketPosition == MarketPosition.Short && testBreakEven)     
                        {
                            if (stopOrderShort != null
                            && stopOrderShort.StopPrice > Position.AveragePrice)
                            {
                                stopOrderShort = ExitShortStopMarket(0, true,
                                stopOrderShort.Quantity,
                                Position.AveragePrice, "TrailStop", "MyEntryShort");
                            }
                        }
                    }
                    #endregion
    
                }
            }
    
            protected override void OnOrderUpdate(Order order,
            double limitPrice, double stopPrice, int quantity, int filled,
            double averageFillPrice, OrderState orderState,
            DateTime time, ErrorCode error, string nativeError)
            {
                #region Long
    
                if (order.Name == "MyEntry")
                {    
                    entryOrder = order;
                    if (order.OrderState == OrderState.Cancelled
                    && order.Filled == 0) entryOrder = null;
                }
                #endregion
    
                #region Short
                if (order.Name == "MyEntryShort")
                {    
                    entryOrderShort = order;
                    if (order.OrderState == OrderState.Cancelled
                    && order.Filled == 0) entryOrderShort = null;
                }
                #endregion
            }
    
            protected override void OnExecutionUpdate(Execution execution,
            string executionId, double price, int quantity,
            MarketPosition marketPosition, string orderId, DateTime time)
            {
                #region Long
                if (entryOrder != null && entryOrder == execution.Order)
                {
                    if (execution.Order.OrderState == OrderState.Filled
                    || execution.Order.OrderState == OrderState.PartFilled
                    || (execution.Order.OrderState == OrderState.Cancelled
                    && execution.Order.Filled > 0))
                    {
                        stopOrder = ExitLongStopMarket(0, true, execution.Order.Filled,
                        execution.Order.AverageFillPrice - 6 , "MyStop", "MyEntry");
                        targetOrder = ExitLongLimit(0, true, execution.Order.Filled,
                        execution.Order.AverageFillPrice + 15 , "MyTarget", "MyEntry");
                        if (execution.Order.OrderState != OrderState.PartFilled)
                            entryOrder = null;
                    }
                }
    
                if ((stopOrder != null && stopOrder == execution.Order)
                || (targetOrder != null && targetOrder == execution.Order))
                {
                    if (execution.Order.OrderState == OrderState.Filled
                    || execution.Order.OrderState == OrderState.PartFilled)
                    {
                        stopOrder = null; targetOrder = null;
                    }
                }
                #endregion
    
                #region Short
    
                if (entryOrderShort != null && entryOrderShort == execution.Order)
                {
                    if (execution.Order.OrderState == OrderState.Filled
                        || execution.Order.OrderState == OrderState.PartFilled
                        || (execution.Order.OrderState == OrderState.Cancelled
                        && execution.Order.Filled > 0))
                    {
                        stopOrderShort = ExitShortStopMarket(0, true, execution.Order.Filled,
                        execution.Order.AverageFillPrice + 10 , "InitStop", "MyEntryShort");
                        targetOrderShort = ExitShortLimit(0, true, execution.Order.Filled,
                        execution.Order.AverageFillPrice - 20 , "Target", "MyEntryShort");
                        if (execution.Order.OrderState != OrderState.PartFilled)
                            entryOrderShort = null;
                    }
                }
    
                if ((stopOrderShort != null && stopOrderShort == execution.Order)
                || (targetOrderShort != null && targetOrderShort == execution.Order))
                {
                    if (execution.Order.OrderState == OrderState.Filled
                    || execution.Order.OrderState == OrderState.PartFilled)
                    {
                        stopOrderShort = null; targetOrderShort = null;
                    }
                }    
    
                #endregion
            }
        }
    } 
    

    For the calculation of the break-even I cannot use PositionAveragePrice + x as on the LongPosition.
    PositionAveragePrice - x sends a continuous signal to the broker; the position is opened and immediately closed again.

    I therefore calculate the Delta (EntryPrice - x) and use the condition testBreakEven. This enables me to control the trading process correctly.
    Is this procedure correct?

    Unlike the long position, OCO does not work with this programming.
    I get two stop prices. How can I change this?

    Thank you very much for your support!

    #2
    Hello user10,

    Position.AveragePrice is the entry price for the position.
    https://ninjatrader.com/support/help...erageprice.htm

    When you mention the position becomes immediately closed, is the exit order filling?
    If you set the price to a further distance below the current bid does the order still fill immediately?

    For a long position, placing the exit a specific number of ticks below the Position.AveragePrice would be correct.
    https://ninjatrader.com/support/help...8/ticksize.htm

    Below I am providing a link to a few examples I have created of custom exit order movements.
    https://ninjatrader.com/support/foru...269#post802269

    For OCO, you would need to switch to using the unmanaged approach and submit orders with SubmitOrderUnamanged().
    https://ninjatrader.com/support/help...d_approach.htm
    Chelsea B.NinjaTrader Customer Service

    Comment


      #3
      Hello Chelsea,

      thank you for your advice.

      I have now changed my code as follows:

      PHP Code:
      if (stopOrderShort != null && stopOrderShort.OrderState == OrderState.Accepted
          || stopOrderShort.OrderState == OrderState.Working
          && stopOrderShort.StopPrice > Position.AveragePrice)
      {
          // Modifies stop-loss to breakeven
          ExitShortStopMarket(0, true, stopOrderShort.Quantity,
              Position.AveragePrice - 1, "TrailStop", "MyEntryShort");
          // Cancel InitOrder
          CancelOrder(stopOrderShort);
      } 
      
      Is that correct?

      Yours sincerely

      Comment


        #4
        Hello user10,

        You mentioned the issue is the order becomes immediately closed, is this correct?

        I am seeing that CancelOrder() is being called.

        Are you trying to cancel the order you are currently placing?

        For a exit short stop order this would be a buy order. A buy stop must be above the market price.
        Is Position.AveragePrice - 1 above the current ask price?
        If not, this order would be rejected for being on the wrong side of the market.
        Chelsea B.NinjaTrader Customer Service

        Comment

        Latest Posts

        Collapse

        Topics Statistics Last Post
        Started by argusthome, 03-08-2026, 10:06 AM
        0 responses
        69 views
        0 likes
        Last Post argusthome  
        Started by NabilKhattabi, 03-06-2026, 11:18 AM
        0 responses
        42 views
        0 likes
        Last Post NabilKhattabi  
        Started by Deep42, 03-06-2026, 12:28 AM
        0 responses
        24 views
        0 likes
        Last Post Deep42
        by Deep42
         
        Started by TheRealMorford, 03-05-2026, 06:15 PM
        0 responses
        27 views
        0 likes
        Last Post TheRealMorford  
        Started by Mindset, 02-28-2026, 06:16 AM
        0 responses
        54 views
        0 likes
        Last Post Mindset
        by Mindset
         
        Working...
        X