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

Delay in marketposition update.

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

    Delay in marketposition update.

    Hi
    I have the following code.
    Code:
    protected override void OnOrderUpdate(Cbi.Order order, double limitPrice, double stopPrice,
    int quantity, int filled, double averageFillPrice,
    Cbi.OrderState orderState, DateTime time, Cbi.ErrorCode error, string comment)
    {
    int current_quantity = Position.Quantity;
    msg = string.Format("Order status = {0}, Market Postiion = {1}, Quantity ={2}, Filled = {3}, Position = {4}", orderState, Position.MarketPosition, quantity, filled, current_quantity);
    Print(msg);
    if((orderState == OrderState.Filled) && (order_accomplished == false))
    {
    Manage_StopLoss();
    Manage_Position();
    if(State == State.Realtime)
    {
    order_accomplished = true;
    }
    }
    else if(orderState == OrderState.PartFilled)
    {
    Manage_StopLoss();
    }
    }

    So during entry when this function gets executed I should have a non flat position. However the Position.MarketPosition is still Flat when the order is filled.

    This becomes cumbersome when tracking stoploss quantity
    I have noticed that even Onposition update does not give accurate Position at all times. E.g i have had instances when the strategy position is 4 however it only gives 3 due to partial fills of 3 and 1. Any ideas?

    #2
    I started using on order update because on position update was providing me an incorrect position, however on order update provides incorrect marketposition.

    what is the porder in which events are fired
    My understanding is
    1) on order update
    2) onexecution update
    3) on position update.

    Is this understanding correct?

    Comment


      #3
      Hello sgkcfc,

      Thank you for your note.

      Who is your broker? Strategy positions are based on Executions, and Interactive Brokers/Rithmic based data providers do not have guaranteed event ordering. Ordering otherwise is 1. Order 2. Execution 3. Position.

      Checking the strategy Position in OnPositionUpdate may not be accurate for Rithmic specifically, since the position update can come before the order or execution.

      Interactive Brokers generally has position updates last, but issues like the above may still come up.

      What exactly are you checking in OnPositionUpdate that is not correct?

      Thanks in advance; I look forward to assisting you further.
      Kate W.NinjaTrader Customer Service

      Comment


        #4
        Hi kate,
        Thank you for the reply. My connection is rithmic. I use on position update to modify the stop quantity when exiting and place stops and targets when entering. THi morning i discovered that even on position update is not being fired for atleast 10-15 seconds after i entered the position. Here is the code and output i print
        Code

        Code:
         protected override void OnOrderUpdate(Cbi.Order order, double limitPrice, double stopPrice,
        int quantity, int filled, double averageFillPrice,
        Cbi.OrderState orderState, DateTime time, Cbi.ErrorCode error, string comment)
        {
        int current_quantity = Position.Quantity;
        msg = string.Format("Order status = {0}, Market Postiion = {1}, Quantity ={2}, Filled = {3}, Position = {4}", orderState, Position.MarketPosition, quantity, filled, current_quantity);
        Print(msg);
        if((orderState == OrderState.Filled) && (order_accomplished == false))
        {
        if(State == State.Realtime)
        {
        order_accomplished = true;
        }
        entry_bar = CurrentBar;
        }
        
        }
        
        protected override void OnPositionUpdate(Cbi.Position position, double averagePrice,
        int quantity, Cbi.MarketPosition marketPosition)
        {
        msg = string.Format("On position update Market Postiion = {0}, Quantity ={1}", Position.MarketPosition, Position.Quantity);
        Print(msg);
        if(State == State.Realtime)
        {
        entry_accomplished = true;
        }
        if(Position.Quantity == entry_position)
        {
        entry_bar = CurrentBar;
        }
        Manage_StopLoss();
        Manage_Position();
        }
        }
        here is the output that i recieved. As you can see the position is not updated until the order is fully filled and even the on position update does not get fired.

        Enabling NinjaScript strategy 'TradeManagementV3/185204349' : On starting a real-time strategy - StartBehavior=ImmediatelySubmit EntryHandling=All entries EntriesPerDirection=1 StopTargetHandling=Per entry execution ErrorHandling=Ignore all errors ExitOnSessionClose=True / triggering 30 seconds before close SetOrderQuantityBy=Strategy ConnectionLossHandling=Recalculate DisconnectDelaySeconds=10 CancelEntriesOnStrategyDisable=False CancelExitsOnStrategyDisable=False Calculate=On bar close IsUnmanaged=False MaxRestarts=4 in 5 minutes
        NinjaScript strategy 'TradeManagementV3/185204349' submitting order
        Order status = Submitted, Market Postiion = Flat, Quantity =4, Filled = 0, Position = 0
        Order status = Accepted, Market Postiion = Flat, Quantity =4, Filled = 0, Position = 0
        Order status = Working, Market Postiion = Flat, Quantity =4, Filled = 0, Position = 0
        Order status = PartFilled, Market Postiion = Flat, Quantity =4, Filled = 3, Position = 0
        Order status = Filled, Market Postiion = Long, Quantity =4, Filled = 4, Position = 4
        Disabling NinjaScript strategy 'TradeManagementV3/185204348'

        Comment


          #5
          Can you please provide some pointers and info with realtime how the events will be fired. I tested this on playback connection and it works perfectly. However when i am trying to do it realtime on a connection there seems a gap between what is expected and what actually happens.

          I have another example that i will post in sometime. I have to organize the prints and log so i can communicate the problem effectively to you. In that particular example the position update was so late that the strategy kept on firing target 2 order even though the position was reduced below it. I am thinking this was probably due to wrong position update.

          I am almost to the point where i cant trust the position,quantity and will have to manually track it based on order fills since onposition update does not fire at all or position.quantity is updated at a snailpace. .

          Comment


            #6
            Below is code i use to manage stop losses and orders
            Code:
            private void Manage_StopLoss()
            {
            msg = string.Format(" stoploss routine Market Postiion = {0}, Quantity ={1}", Position.MarketPosition, Position.Quantity);
            Print(msg);
            if(Position.MarketPosition == MarketPosition.Short)
            {
            trail_short();
            }
            if(Position.MarketPosition == MarketPosition.Long)
            {
            trail_long();
            }
            }
            private void Manage_Position()
            {
            msg = string.Format(" manage position routine Market Postiion = {0}, Quantity ={1}", Position.MarketPosition, Position.Quantity);
            Print(msg);
            if(Position.MarketPosition == MarketPosition.Short)
            {
            if(Position.Quantity == entry_position)
            {
            
            ExitShortLimit(target_1_position, Target_1, "First_Target", "Entry");
            }
            
            if((Position.Quantity >= (entry_position - target_1_position)) && (target_2_position != 0))
            {
            ExitShortLimit(target_2_position, Target_2, "Second_Target", "Entry");
            }
            
            if((Position.Quantity >= (entry_position - target_1_position - target_2_position)) && (target_3_position != 0))
            {
            ExitShortLimit(target_3_position, Target_3, "Third_Target", "Entry");
            }
            
            if((Position.Quantity >= (entry_position - target_1_position - target_2_position - target_3_position)) && (target_4_position != 0))
            {
            ExitShortLimit(target_4_position, Target_4, "Fourth_Target", "Entry");
            }
            
            if((Position.Quantity >= (entry_position - target_1_position - target_2_position - target_3_position - target_4_position)) && (target_5_position != 0))
            {
            ExitShortLimit(target_5_position, Target_5, "Fifth_Target", "Entry");
            }
            }
            
            if(Position.MarketPosition == MarketPosition.Long)
            {
            if(Position.Quantity == entry_position)
            {
            ExitLongLimit(target_1_position, Target_1, "First_Target", "Entry");
            }
            
            if((Position.Quantity >= (entry_position - target_1_position)) && (target_2_position != 0))
            {
            ExitLongLimit(target_2_position, Target_2, "Second_Target", "Entry");
            }
            
            if((Position.Quantity >= (entry_position - target_1_position - target_2_position)) && (target_3_position != 0))
            {
            ExitLongLimit(target_3_position, Target_3, "Third_Target", "Entry");
            }
            
            if((Position.Quantity >= (entry_position - target_1_position - target_2_position - target_3_position)) && (target_4_position != 0))
            {
            ExitLongLimit(target_4_position, Target_4, "Fourth_Target", "Entry");
            }
            
            if((Position.Quantity >= (entry_position - target_1_position - target_2_position - target_3_position - target_4_position)) && (target_5_position != 0))
            {
            ExitLongLimit(target_5_position, Target_5, "Fifth_Target", "Entry");
            }
            }
            }

            Comment


              #7
              Hello sgkcfc,

              Thank you for your reply.

              If you are using Rithmic, the most sure fire way to address the position issue is to use the Unmanaged Approach with OnOrderUpdate only. I'm attaching an example of using the Unmanaged approach, which allows you to calculate the position so you aren't dependent on Rithmic's position updates. Information regarding the Unmanaged Approach may be found in our help guide here:



              Please let us know if we may be of further assistance to you.
              Attached Files
              Kate W.NinjaTrader Customer Service

              Comment


                #8
                Thank you for your reply Kate.

                Do you have any idea why the OnpositionUpdate would not fire even though the order got executed. Would onexecution update be more rliable?

                Comment


                  #9
                  Hello sgkcfc,

                  Thank you for your reply.

                  As I mentioned previously, this is a known issue with Rithmic based connections. They do not guarantee the order or even when OnPositionUpdate will fire. I would suggest reviewing the code for the example I previously posted as this shows using both OnExecutionUpdate to monitor for the executions and OnOrderUpdate to calculate the position.

                  Please note the Managed approach should not be used with Rithmic as this does not allow you to ignore the strategy calculated position and calculate your own instead as in the example.

                  Please let us know if we may be of further assistance to you.
                  Kate W.NinjaTrader Customer Service

                  Comment


                    #10
                    Thank you Kate. I tried the managed approch and almost all of the timing issues are taken care of.
                    I am tracking my position in onOrderUpdate.

                    I have one question though. I only place an order once and then i dont care to place it again. Consider it like a advanced ATM strategy. Now problem is the order does not get submitted right away but waits for one bar to complete before it actually gets submitted . This is even after i select "submit immediately" from the strategy menu. Any solution to get over this without adding another series and forcing onBarUpdate to execute?

                    Code:
                    protected override void OnBarUpdate()
                    {
                    if(BarsInProgress != 0)
                    return;
                    if((!entrySubmitted) && (State == State.Realtime))
                    {
                    current_position = 0;
                    enter_position();
                    entrySubmitted = true;
                    }
                    Adjust_Stops();
                    }

                    I also added this code for onstatechange method

                    Code:
                    else if(State == State.Realtime)
                    {
                    /*if((!entrySubmitted) && (State == State.Realtime))
                    {
                    current_position = 0;
                    enter_position();
                    entrySubmitted = true;
                    }*/
                    }
                    Last edited by sgkcfc; 01-15-2021, 12:08 AM.

                    Comment


                      #11
                      Hello sgkcfc,

                      Thank you for your reply.

                      What is your Calculate setting for the strategy?

                      Is this occurring on historical data, like on a chart before real time data or in the Strategy Analyzer, or on real time data?

                      Thanks in advance; I look forward to assisting you further.
                      Kate W.NinjaTrader Customer Service

                      Comment


                        #12
                        Hi Kate,
                        Thank you for the reply. My calculate is on bar close. The strategy is on a chart. So intent is to have the order submitted immediately. Managed apporach there was no problem since orders get cancelled and then again resubmitted. But for unmanaged since we cant resumbit intent is only to place the order one time.

                        Comment


                          #13
                          Hello sgkcfc,

                          Thank you for your reply.

                          When using OnBarClose it would be expected for your orders to be submitted at the open of the bar following the bar which triggered it, since those calculations aren't made until the triggering bar is closed. The order is submitted as soon as those calculations are made. Is this what you're referring to?

                          Thanks in advance; I look forward to assisting you further.
                          Kate W.NinjaTrader Customer Service

                          Comment


                            #14
                            Hi Kate,
                            Yes i get that on bar update would be ikicked in and order be submitted only when it executed. However before when i was using unmanaged, as soon as i activated the strategy the order was submitted. I did not have to wait for the bar close for the on bar update to kick in when using my strategy. I am wondering what is different with unmanged. Before with managed orders where the order used to be submitted as soon as i activated the strategy and not wait for the bar to be closed was as follows. However with unmanaged i cant have the code below as the orders would be accumulated.

                            Code:
                            protected override void OnBarUpdate()
                            {
                            if(BarsInProgress != 0)
                            return;
                            if((Position.MarketPosition == MarketPosition.Flat) && (entry_accomplished == false) && (entry_price != 0) && (entry_position!=0))
                            {
                            enter_position();
                            }
                            else
                            {
                            Manage_StopLoss();
                            Manage_Position();
                            }
                            
                            }

                            Comment


                              #15
                              Hello sgkcfc,

                              Thank you for your reply.

                              Do you mean that when you start the strategy using Immediately Submit, Synchronize Account when the strategy would have been in a position, you're not seeing that position appear until the next bar closes? Or what is the behavior exactly? If you can provide a short video of the behavior that would be the most helpful to understand. When I test with the example I'm seeing those orders immediately submitting as I would expect.

                              Thanks in advance; I look forward to assisting you further.
                              Kate W.NinjaTrader Customer Service

                              Comment

                              Latest Posts

                              Collapse

                              Topics Statistics Last Post
                              Started by Perr0Grande, Today, 08:16 PM
                              0 responses
                              2 views
                              0 likes
                              Last Post Perr0Grande  
                              Started by elderan, Today, 08:03 PM
                              0 responses
                              5 views
                              0 likes
                              Last Post elderan
                              by elderan
                               
                              Started by algospoke, Today, 06:40 PM
                              0 responses
                              10 views
                              0 likes
                              Last Post algospoke  
                              Started by maybeimnotrader, Today, 05:46 PM
                              0 responses
                              11 views
                              0 likes
                              Last Post maybeimnotrader  
                              Started by quantismo, Today, 05:13 PM
                              0 responses
                              7 views
                              0 likes
                              Last Post quantismo  
                              Working...
                              X