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

get back order information on broker server after close Ninja Trader application

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

    get back order information on broker server after close Ninja Trader application

    Hi,

    I develop a simple strategy to have an entry based on where I draw a horizontal line. The system automatically send oco stop order and target order (also based on my preset horizontal price lines) once the entry order is filled. Those OCO orders are sent to Interactive Broker servers, but I still can control it by storing order information into variables. However, the issue is that when I change to other instruments or quit Ninjatrader, then come back, those variable storing order information lost, so I cannot control OCO orders any more. So, is there any solution that I can get back those OCO orders information and assign them into Order variable after I quit the software and come back? (I use SubmitOrderUnmanaged)

    Thanks.

    #2
    Hello phuochh,

    Thanks for your post.

    When a strategy is enabled, it processes historical data to determine trades that the strategy would have made on the data that is already on the PC/chart and to determine what position the strategy is in. (Strategy positions are separate from actual Account positions.)

    Immediately Submit automatically submits working orders from when the strategy processed historical data, and assumes the strategy position and account position are where you want it when you enable the strategy. This is typically used to have a strategy resume a position after disabling/enabling.

    If the strategy already had live orders running, the orders will resume with the new enablement of the strategy if they exactly match the historically calculated orders. If the orders calculated from historical data do not match the live working orders, the live working orders will be canceled and replaced by those calculated from historical data.

    See this help guide page for more information: https://ninjatrader.com/support/help..._positions.htm

    Let me know if I may further assist.​
    Brandon H.NinjaTrader Customer Service

    Comment


      #3
      Thanks for your prompt reply.

      I read the document, but still cannot capture how to do it. Let me explains my code, so you can get my issue:
      -Once entry order is hit, stoploss & target orders are sent to the broker server in execution event. Orders information are saved into _entryOrder, _stopOrder, _targetOrder variables.
      The issue is when I switch instrument or shut down NinjaTrader, those variables are reset. I understand that, those live orders (OCO orders) are syncronized by Ninjatrader, this syncronization is done outside of the strategies according to the document (if I'm not wrong), so how can I access to the syncronized OCO orders information and assign them into _stopOrder & _targetOrder variables in my strategies?



      ////This function is triggered by a button, once I already set entry price, stoploss price, target price (before that _Direction = _EntryPrice > _ExitPrice? "LONG":"SHORT")

      private void TradeEntry()
      {
      if (_Direction == "LONG")
      {
      _entryFilled = 0;
      _ocoName = "";
      OrderType orderType = _EntryPrice < GetCurrentAsk() ? OrderType.Limit : OrderType.StopLimit;
      string orderName = "Entry";
      _entryOrder = LongOrder(orderType, orderName, _PositionSize); //=> triggering LongOrder function
      }
      else if (_Direction == "SHORT")
      {
      OrderType orderType = _EntryPrice > GetCurrentBid() ? OrderType.Limit : OrderType.StopLimit;
      string orderName = "Entry";
      _entryOrder = ShortOrder(orderType, orderName, _PositionSize); //=> triggering ShortOrder function
      }

      }

      ////This function is triggered if _Direction is LONG

      private Order LongOrder(OrderType orderType, string orderName, int PositionSize)
      {
      Order entryOrder = null;
      switch (orderType)
      {
      case OrderType.Limit:
      if (_EntryPrice <= GetCurrentAsk())
      {
      entryOrder = SubmitOrderUnmanaged(0, OrderAction.Buy, orderType, PositionSize, _EntryPrice, 0, "", orderName);
      }
      break;

      case OrderType.StopLimit:
      if (_EntryPrice >= GetCurrentAsk())
      {
      var LimitPrice = _EntryPrice + p_StopLimitGap * TickSize;
      entryOrder = SubmitOrderUnmanaged(0, OrderAction.Buy, orderType, PositionSize, LimitPrice, _EntryPrice, "", orderName);
      }
      break;

      }

      return entryOrder; //==> return order information once the order is successfully summitted
      }

      ////////////Once entry order is hit, stoploss and target orders are sent to the broker server. Order information is saved into _stopOrder & _targetOrder variables.

      protected override void OnExecutionUpdate(Execution execution, string executionId, double price, int quantity, MarketPosition marketPosition, string orderId, DateTime time)
      {
      if (execution.Order == _entryOrder && _entryOrder != null)
      {
      if (_entryFilled == 0) _ocoName = "OCO " + time.ToString();
      _entryFilled += quantity;

      if (_entryOrder.Quantity < _entryFilled)
      {
      Print(string.Format("Overfilled!!! Filled Qty: {0} > Order Qty: {0}", _entryFilled, _entryOrder.Quantity));
      }

      if (_Direction == "LONG")
      {
      if (_stopOrder == null) _stopOrder = SubmitOrderUnmanaged(0, OrderAction.Sell, OrderType.StopMarket, _entryFilled, 0, _ExitPrice, _ocoName, "Entry");
      else ChangeOrder(_stopOrder, _entryFilled, 0, _ExitPrice);

      _targetOrder = SubmitOrderUnmanaged(0, OrderAction.Sell, OrderType.Limit, _entryFilled, _EntryPrice + _Runit * 4, 0, _ocoName, "Entry");
      } else
      {
      _stopOrder = SubmitOrderUnmanaged(0, OrderAction.BuyToCover, OrderType.StopMarket, _entryFilled, 0, _ExitPrice, _ocoName, "Entry");
      _targetOrder = SubmitOrderUnmanaged(0, OrderAction.BuyToCover, OrderType.Limit, _entryFilled, _EntryPrice - _Runit * 4, 0, _ocoName, "Entry");
      }


      }
      if (PositionAccount.Quantity == 0)
      {
      _entryFilled = 0;
      _ocoName = "";
      }


      }​​​

      Comment


        #4
        Hello phuochh,

        As the strategy is re-enabled, the historical data will be processed. The same orders should be submitted in historical data, triggering OnOrderUpdate(), and again saving these orders to variables.
        If the orders match the real-time orders submitted previously by the strategy, the real-time orders will be matched, and those will be the orders that are assigned to your variables.
        1-tick intra-bar granularity will allow the strategy to resume the orders properly by allowing these to be submitted and at the proper time and price.

        Below is a link to a forum post that details.
        Chelsea B.NinjaTrader Customer Service

        Comment


          #5
          Hi Chelsea B.,

          I tried, but cannot see any triggering OnOrderUpdate(). Actually, My strategy is simple, after my entry order is hit, I submit a pair of OCO orders (target order and stop order) using SubmitOrderUnmanaged(). The issue is when I change another instrument then come back the instrument that I have positiona and OCO orders, the _stopOrder and _targetOrder now become null and I am still struggle to get back their information. I tried to capture them in OnOrderUpdate(), but it seems that their is no triggering in OnOrderUpdate event when I change instrument, even thougg the position and the OCO orders are still available for manual handling. Could you please advice?

          Comment


            #6
            Hello phuochh,

            Thanks for your note.

            Did you add 1-Tick intrabar granularity to the script to allow the orders to be submitted at the proper price and time so the strategy can resume the orders?

            The forum thread linked by my colleague Chelsea in post # 4 could be used to see more information and examples about adding intrabar granularity to a script.

            Have you added debugging prints to see if the OnOrderUpdate() method is being triggered and that your logic is being reached?

            If not, it is necessary to add prints to a script to understand exactly how the script is behaving and if logic is being reached or not.

            Below is a link to a forum post that demonstrates how to use prints to understand behavior.

            https://ninjatrader.com/support/foru...121#post791121

            Let me know if I may assist further.
            Brandon H.NinjaTrader Customer Service

            Comment


              #7
              I added 1-Tick granularity to the script to tried to debug prints in OnOrderUpdate() but there is nothing being triggered when I switch on and off the strategy or change between instruments. In addition, with the setting "Immediate Submit, Synchonize Account" for start behavior, the Position and Account Position does not match, so the system closes my position when I turn off and on the strategy. I use submitOrderunmanaged and set Barsinprogess = 1 which is 1-tick series, so I wonder what I am missing here, could you please advice? Thanks.

              Comment


                #8
                Hello phuochh,

                Thanks for your note.

                What exactly do you mean by 'there is nothing being triggered'? Are you referring to the conditions in your strategy not becoming true?

                Or, are you referring to not seeing any prints you made printing to a New > NinjaScript Output window?

                Prints could be used to confirm if the logic of your conditions are becoming true and if the condition should be triggering actions. One line above the conditions in your script, add prints that print out each value being used in the condition. Also, add a print inside of the conditions so that you know the logic inside the condition is being triggered.

                By adding these prints, you could tell that your condition(s) in fact is becoming true and the logic within the condition is being triggered.

                Note that no logic within a condition will fire until that condition becomes true.

                A simple example of using prints can be found below.

                Code:
                Print("Close[0] > Open[0]": + (Close[0] > Open[0]));
                if (Close[0] > Open[0])
                {
                     SubmitOrderUnmanaged(0, OrderAction.Buy, OrderType.Market, 1, 0, 0, "", "Enter Long");
                     Print("Logic triggered for Close[0] > Open[0] condition.");
                }​
                The prints above allow us to see if the condition is true or false and if the logic inside our condition should be triggered.

                In regard to using the Start Behavior 'Immediate Submit, Synchronize Account", if the strategy already had live orders running, the orders will resume with the new enablement of the strategy if they match the historically calculated orders. If the orders calculated from historical data do not match the live working orders, the live working orders will be canceled and replaced by those calculated from historical data. Note to have the orders resume, they must exactly match the historically calculated orders.

                Sync Account Positions is an additional option that has NinjaTrader submit an order to sync the account position to the position calculated by the strategy. (Not the other way around.)

                See this help guide page for further information about the different Start Behavior options available: https://ninjatrader.com/support/help...hronizeAccount

                Please let me know if I may assist further.
                Brandon H.NinjaTrader Customer Service

                Comment


                  #9
                  Hi Brandon,
                  I'm facing the issue of lossing controll of live stoploss and target orders that already submitted to brokers when I turn on and off my strategy or switching back and forth between instruments. Could you see the attached recording link on youtube that I explain my detail issue.

                  Thank you very much.
                   

                  Comment


                    #10
                    Hello phuochh,

                    Thanks for your video.

                    The behavior demonstrated in the video you shared shows that the active order on the account that was previously generated does not match the historically calculated order when the script re-enables with Immediately Submit, Synchronize Account and the active strategy order is being canceled, leaving you in a flat strategy position and account position.

                    To resume an order, your logic in the script needs to equate the same both historically and realtime so that the order is not canceled when the script re-enables.

                    From the Immediately Submit, Synchronize Account help guide:

                    "Any active orders on the account previously generated by the strategy that does not match* an active strategy order will be cancelled.

                    A previously generated order is considered to match an active strategy order when the order action, order type, quantity, limit price, and stop price are exactly identical."


                    Since the order exists while the start behavior runs, that is a known strategy order. If there is a live order that matches that order, the strategy maps the live order to that historical order.

                    If the strategy just enters realtime and does not submit that order, the live order does not match any known order so it is canceled.

                    Note that not all strategies can resume orders. For example, if you used OnMarketData() to place orders that likely can't be replicated. Another example is if the script ignores historical processing and only processes realtime data. In this case, you would need to avoid stopping the strategy or cancel the orders/position before restarting it.

                    Let me know if I may assist further.
                    Brandon H.NinjaTrader Customer Service

                    Comment

                    Latest Posts

                    Collapse

                    Topics Statistics Last Post
                    Started by port119, Today, 02:43 PM
                    0 responses
                    1 view
                    0 likes
                    Last Post port119
                    by port119
                     
                    Started by Philippe56140, Today, 02:35 PM
                    0 responses
                    2 views
                    0 likes
                    Last Post Philippe56140  
                    Started by 00nevest, Today, 02:27 PM
                    0 responses
                    1 view
                    0 likes
                    Last Post 00nevest  
                    Started by Jonafare, 12-06-2012, 03:48 PM
                    5 responses
                    3,986 views
                    0 likes
                    Last Post rene69851  
                    Started by Fitspressorest, Today, 01:38 PM
                    0 responses
                    2 views
                    0 likes
                    Last Post Fitspressorest  
                    Working...
                    X