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

Unmanged order handling framework

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

    Unmanged order handling framework

    Hi all,

    I have a question regarding unmanaged orders (using an Interactive Brokers brokerage connection):

    First of all, I’m entering a Buy Limit order in the OnBarUpdate() event.

    Code:
    if (entryOrder == null && profitTakerOrder == null && stopLossOrder == null)
    {
        SubmitOrderUnmanaged(0, OrderAction.Buy, OrderType.Limit, 
            Convert.ToInt32(Math.Round(Quantity / Open[0], 0, MidpointRounding.ToEven)), SubmissionPrice, 0, "", "Enter Long Limit");
    }
    After i have a trailing stop order which so far works as expected.

    Code:
    if (stopLossOrder != null && Close[0] > trailingStopPrice)
    {
        // Trail Stop-Loss 3% below current price
        ChangeOrder(stopLossOrder, stopLossOrder.Quantity, 0, Close[0] - ((Close[0] / 100) * 3));
        trailingStopPrice = Close[0] + ((Close[0] / 100) * 3);
    }
    However, when i try to make a bracket order (stop-loss and take-profit), it gives me a mess in the chart with all the orders.

    Code:
    protected override void OnExecutionUpdate(Execution execution, string executionId, double price, int quantity, MarketPosition marketPosition, string orderId, DateTime time)
    {
        if (execution.Order.OrderState != OrderState.Filled)
            return;
    
        Print("Execution: " + execution.ToString());
        if (entryOrder != null && execution.Order == entryOrder)
        {
            // Stop Loss 5% below entry price
            stopLossOrder = SubmitOrderUnmanaged(0, OrderAction.Sell, OrderType.StopMarket,
                execution.Order.Filled, 0, execution.Order.AverageFillPrice - ((execution.Order.AverageFillPrice / 100) * 3), string.Empty, "Stop Loss");
    
            //// Profit Taker 6% above entry price
            //profitTakerOrder = SubmitOrderUnmanaged(0, OrderAction.Sell, OrderType.Limit,
            //    execution.Order.Filled, execution.Order.AverageFillPrice + ((execution.Order.AverageFillPrice / 100) * 6), 0, string.Empty, "Profit Taker");
    
            if (execution.Order.OrderState != OrderState.PartFilled)
                entryOrder = null;
        }
    
        if ((stopLossOrder != null && stopLossOrder == execution.Order) || (profitTakerOrder != null && profitTakerOrder == execution.Order))
        {
            if (execution.Order.OrderState == OrderState.Filled || execution.Order.OrderState == OrderState.PartFilled)
            {
                stopLossOrder = null;
                profitTakerOrder = null;
            }
        }
    }
    Attached is the full code as a reference.
    Any help is appreciated.

    Thanks...
    Attached Files
    Last edited by Sweet&Sour; 08-27-2018, 10:50 AM.

    #2
    Hello Sweet&Sour,

    Thank you for the post.

    I ran your strategy, and uncommented the profitTakerOrder line, but I am only able to see one execution that the strategy generates towards the beginning of historical data.

    Screenshot: https://www.screencast.com/t/j2yd1ofmOuP3

    Could you please let me know how you are setting up this strategy? Please include the chart instrument and chart type (and period) as well.

    I look forward to your reply.
    Chris L.NinjaTrader Customer Service

    Comment


      #3
      Hi Chris

      Take AAPL in 1 Day Period starting from 1th of January 2018.
      Attached is a screenshot, un-commented the profit taker and commented out the trail stop.

      Thanks...
      Attached Files

      Comment


        #4
        Hello Sweet&Sour,

        Thank you for the reply.

        It looks like the stop loss and profit taker orders are not being canceled when they need to be. The protective orders are creating new positions because the account is flat when they are reached and the orders are not canceled. Make sure to cancel the respective stop loss and profit target orders once the "Enter Long Limit" order is either canceled or is closed.

        Please let me know if I can assist further.
        Chris L.NinjaTrader Customer Service

        Comment


          #5
          I thought that this is done through

          if (entryOrder != null && execution.Order == entryOrder)

          in the OnExecutionUpdate() event handler.

          In which event handler i have to check whether or not, an order is open to properly cancel the SL/TP order? Any sample code availabe?
          Last edited by Sweet&Sour; 08-27-2018, 12:51 PM.

          Comment


            #6
            Hello Sweet&Sour,

            Thanks for the reply.

            I recommend using OnExecutionUpdate to know exactly when your position becomes flat. Below I have linked a reference sample on how to use CancelOrder:



            There is also this reference sample that shows how to submit protective orders within OnExecutionUpdate.



            Please let me know if you have any questions.
            Last edited by NinjaTrader_ChrisL; 08-28-2018, 06:30 AM.
            Chris L.NinjaTrader Customer Service

            Comment


              #7
              Hi Chris

              Actually, I thought that I'm using protective orders as this article was initially my starting point

              Here's my code snippet to drop any SL/TP orders during the OnExecutionUpdate() event handler. This works fine, however i have to make a comparison with the managed order types just to make sure that there isn't a gap somewhere.

              Code:
              protected override void OnExecutionUpdate(Execution execution, string executionId, double price, int quantity, MarketPosition marketPosition, string orderId, DateTime time)
              {
                  if (execution.Order.OrderState != OrderState.Filled)
                      return;
              
                  Print("Execution: " + execution.ToString());
              [B]    if (entryOrder == null)
                  {
                      if (profitTakerOrder != null && (profitTakerOrder.OrderState == OrderState.Accepted || profitTakerOrder.OrderState == OrderState.Working))
                          CancelOrder(profitTakerOrder);
                      else if (stopLossOrder != null && (stopLossOrder.OrderState == OrderState.Accepted || stopLossOrder.OrderState == OrderState.Working))
                          CancelOrder(stopLossOrder);
                  }[/B]
              
                  if (entryOrder != null && execution.Order == entryOrder)
                  {
                      // Stop Loss 5% below entry price
                      stopLossOrder = SubmitOrderUnmanaged(0, OrderAction.Sell, OrderType.StopMarket,
                          execution.Order.Filled, 0, execution.Order.AverageFillPrice - ((execution.Order.AverageFillPrice / 100) * 3), string.Empty, "Stop Loss");
              
                      // Profit Taker 6% above entry price
                      profitTakerOrder = SubmitOrderUnmanaged(0, OrderAction.Sell, OrderType.Limit,
                          execution.Order.Filled, execution.Order.AverageFillPrice + ((execution.Order.AverageFillPrice / 100) * 6), 0, string.Empty, "Profit Taker");
              
                      if (execution.Order.OrderState != OrderState.PartFilled)
                          entryOrder = null;
                  }
              
                  if ((stopLossOrder != null && stopLossOrder == execution.Order) || (profitTakerOrder != null && profitTakerOrder == execution.Order))
                  {
                      if (execution.Order.OrderState == OrderState.Filled || execution.Order.OrderState == OrderState.PartFilled)
                      {
                          stopLossOrder = null;
                          profitTakerOrder = null;
                      }
                  }
              }
              Thanks...
              Attached Files

              Comment


                #8
                Hi Chris,

                One more question. If i would attach my IB Account through an IB Gateway in Ninja 8, i guess i have to use the Account Class to attach my IB account and use the proper account methods like CreateOrder(), Submit(), Change(), Cancel() or CancelAllOrders() to manipulate orders on the IB side? Is that right or are there other ways like the unmanaged approach to raise and managed orders through the IB Gateway?

                Thanks...

                Comment


                  #9
                  Hello Sweet&Sour,

                  Thank you for the reply.

                  The Interactive Brokers connection adapter will handle the interaction between the NinjaScript API and the TWS API. You may use the unmanaged order methods in NinjaScript targeted to your IB account and add/modify/cancel them with the unmanaged order methods as you would normally.

                  Please let me know if I can assist further.
                  Chris L.NinjaTrader Customer Service

                  Comment


                    #10
                    Hi Chris

                    I'm a bit confused with the order management frameworks using the IB Gateway to trade equities on a daily base. Currently i'm not sure whether or not, the managed order framework works against the IB Gateway, as long as i'm just using simple order like a market order + stop loss + profit taker (or just a single trailing stop)? Or does the IB connection adapter only work using the unmanaged framework?

                    Thanks...

                    Comment


                      #11
                      Hello Sweet&Sour,

                      Thanks for the reply.

                      The managed and unmanaged approach will both work with the Interactive Brokers connection adapter. Was there a specific item that you ran into? I tested the SampleMACrossover strategy on a test IB account and it executed orders normally.

                      I look forward to your reply.
                      Chris L.NinjaTrader Customer Service

                      Comment


                        #12
                        Hi Chris

                        In the past, I saw a few German traders using Ninja FDAX strategies over the managed order framework, connecting to Captrader (which is a German broker offering full IB TWS access). So far, I wasn't aware that the managed order framework works as well for the IB connection adapter but glad to get confirmed that this was never an issue :-)

                        Krgds...

                        Comment

                        Latest Posts

                        Collapse

                        Topics Statistics Last Post
                        Started by Javierw.ok, Today, 04:12 PM
                        0 responses
                        4 views
                        0 likes
                        Last Post Javierw.ok  
                        Started by timmbbo, Today, 08:59 AM
                        2 responses
                        10 views
                        0 likes
                        Last Post bltdavid  
                        Started by alifarahani, Today, 09:40 AM
                        6 responses
                        40 views
                        0 likes
                        Last Post alifarahani  
                        Started by Waxavi, Today, 02:10 AM
                        1 response
                        18 views
                        0 likes
                        Last Post NinjaTrader_LuisH  
                        Started by Kaledus, Today, 01:29 PM
                        5 responses
                        15 views
                        0 likes
                        Last Post NinjaTrader_Jesse  
                        Working...
                        X