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

Unmanaged Mode with partialFilled Orders and Trailingstop

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

    Unmanaged Mode with partialFilled Orders and Trailingstop

    good day together, i have now spent 2 days on this and other forums looking for a solution to my problem and hope to get an answer to my question here ;-)
    the following scenario in unmanaged mode:

    --------------------------------------------------------------------------------------------------------------------------------------------------------------
    protected override void OnBarUpdate()
    .......

    // BarByBar Trail
    ......
    if (SLL1 != null && (SLL1.OrderState == OrderState.Accepted || SLL1.OrderState == OrderState.Working))

    {
    ChangeOrder(SLL1, sumexecution, 0, newPrice); // Readjust stoploss level
    Print(Time[0] + " *** Stoploss SLL1 move to " + newPrice + " *** by BarByBar Trail" + " *** Qty: " + Position.Quantity + " *** SLL1 Qty: " + SLL1.Quantity + " *** ocoID: " + ocoExit);
    }

    // Entry Long Limit
    .......
    if (LE1 == null && IsFirstTickOfBar .......)
    {
    SubmitOrderUnmanaged(1, OrderAction.Buy, OrderType.Limit, Positionsgrösse1, GetCurrentBid(), 0, ocoEntry, "LongEntry1");
    }

    ------------------------------------------------------------------------------------------------------------------------------------------------------------------
    protected override void OnOrderUpdate(...)

    // Long Entry
    if (order.Name == "LongEntry1")
    {
    LE1 = order;

    if (LE1 != null && LE1 == order)
    {
    // Reset the long entry object to null if order was cancelled without any fill
    if (order.OrderState == OrderState.Cancelled)// && order.Filled == 0)
    {
    LE1 = null;
    sumFilledLE1 = 0;
    }
    }
    }

    // Long Stop
    else if (order.Name == "StopLossLong1")
    {
    SLL1 = order;

    if (SLL1 != null && SLL1 == order)
    {
    // Reset the long stop loss object to null if order was cancelled without any fill
    if (order.OrderState == OrderState.Cancelled && order.Filled == 0)
    {
    SLL1 = null;
    }
    }
    }
    -------------------------------------------------------------------------------------------------------------------------------------------------------------------------
    protected override void OnExecutionUpdate(....)

    // Long SL and TP Position 1
    if (LE1 != null && LE1 == execution.Order)
    {

    if (execution.Order.OrderState == OrderState.Filled || execution.Order.OrderState == OrderState.PartFilled || (execution.Order.OrderState == OrderState.Cancelled && execution.Order.Filled > 0))
    {
    if (State == State.Historical)
    ocoExit = DateTime.Now.ToString() + CurrentBar + " LongExits ";
    else
    ocoExit = GetAtmStrategyUniqueId() + " LongExits ";

    // We sum the quantities of each execution making up the entry order
    sumFilledLE1 += execution.Quantity;

    // Submit exit orders for partial fills
    if (UseTickStop && execution.Order.OrderState == OrderState.PartFilled)
    {
    SubmitOrderUnmanaged(1, OrderAction.Sell, OrderType.StopMarket, execution.Quantity, 0, execution.Order.AverageFillPrice - InitialStopTick * TickSize, ocoExit, "StopLossLong1");

    }
    // Update our exit order quantities once orderstate turns to filled and we have seen execution quantities match order quantities
    else if (UseTickStop && execution.Order.OrderState == OrderState.Filled && sumFilledLE1 == execution.Order.Filled)
    {
    SubmitOrderUnmanaged(1, OrderAction.Sell, OrderType.StopMarket, execution.Quantity, 0, execution.Order.AverageFillPrice - InitialStopTick * TickSize, ocoExit, "StopLossLong1");
    Print(Time[0] + " *** Set Stoploss SLL1 fullfilled Order @ " + (execution.Order.AverageFillPrice - InitialStopTick * TickSize) + " *** Qty: " + execution.Quantity + " *** " + execution.Order.Filled + " / " + execution.Order.Quantity + " *** ocoID: " + ocoExit);
    }

    if (execution.Order.OrderState == OrderState.Filled)
    {
    sumexecution = execution.Order.Filled;
    }


    // Resets the long entry object to null after the order has been filled
    if (execution.Order.OrderState != OrderState.PartFilled && sumFilledLE1 == execution.Order.Quantity)
    {
    LE1 = null;
    sumFilledLE1 = 0;
    }

    //Reset our stop order and target orders' Order objects after our position is closed.
    //Long SL
    if (SLL1 != null && SLL1 == execution.Order)
    {
    if (execution.Order.OrderState == OrderState.Filled || execution.Order.OrderState == OrderState.PartFilled)
    {
    SLL1 = null;
    }
    }

    ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
    as far as i can see, i am given one order for the partially executed quantities and another order for the last fully executed position. my problem now is that when i use the ChangeOrder() method for the barbabar trailingstop, the last filled position is taken as the basis for this ChangeOrder() and the last remainder of the partially filled order remains as stoploss. since the ChangeOrder() trades a whole position, the partial position is too much and should be deleted. how exactly can i implement this? on the pictures you can see very well what exactly i mean. sorry for my english ;-)

    the example for the partial executions i got from the SampleOnOrderUpdate file from here. I have also looked at the other examples:
    UnmanagedOCOBracketExample, SampleUnmanagedBracketStrategy, ProfitChaseStopTrailUnmanagedExample ...., but found nothing that could help me. maybe there is someone here who can - i hope so.... it's certainly a little tip for someone who can a just a little program, not like me ;-)
    sidlercom80
    NinjaTrader Ecosystem Vendor - Sidi Trading

    #2
    Hello sidlercom80,

    Thanks for your post.

    I had implemented the logic described in SampleOnOrderUpdate for partial fills into my Unmanaged Template strategy. Partial fills were working as I would expect. I have attached this example so it may provide you some further direction.

    Also as a tip, please use [CODE] blocks when posting code on the forums so the code keeps its formatting and is more readable by others browsing the forum.

    If you you see an issue testing this strategy, please let me know.
    Attached Files
    JimNinjaTrader Customer Service

    Comment


      #3
      hi _jim, thank you so much for your help. It was just what I was looking for. really very good service and great performance from you!!!
      i have only now seen the hint with the code block, i will do it next time ;-)
      again many thanks and have a nice evening!
      sidlercom80
      NinjaTrader Ecosystem Vendor - Sidi Trading

      Comment


        #4
        Hi NinjaTrader_Jim, if I run your script in a Sim account everything is fine. If I run your script in a Demo account, most of the time when more than one volume is traded, are not the correct position sizes calculated for stoploss and takeprofit. can you give me a hint as to why that might be?
        sidlercom80
        NinjaTrader Ecosystem Vendor - Sidi Trading

        Comment


          #5
          here for testing purposes a demo account with oneup trader. it's just this trade, nothing else.
          sidlercom80
          NinjaTrader Ecosystem Vendor - Sidi Trading

          Comment


            #6
            i also found this post and loaded the SampleOnOrderUpdate and there it is the same problem
            https://ninjatrader.com/support/foru...n-live-account
            Last edited by sidlercom80; 02-14-2020, 07:04 AM.
            sidlercom80
            NinjaTrader Ecosystem Vendor - Sidi Trading

            Comment


              #7
              I think that might be my problem:

              Rithmic and Interactive Brokers Users: Due to provider API design these adapters do not guarantee the sequence of events of OnOrderUpdate, OnExecution, and OnPositionUpdate. Therefore when working on a strategy that will run on these connections it is best practice to only work with passed by value data from that callback to eliminate the dependency on the sequence of events.

              i don't understand how this problem could be solved. does anyone have any experience with this?
              sidlercom80
              NinjaTrader Ecosystem Vendor - Sidi Trading

              Comment


                #8
                Hello sidlercom80,

                Thanks for your message.

                I can reproduce the same on my end with Rithmic connections.

                From what I am seeing when examining my log files, the Order Update event is coming after the Execution once the order has been filled. I then expect execution.Order to not be current when the stops and targets are modified in OnExecutionUpdate.

                I am no longer able to test with our test account at this time and will likely need to come back to this next week. My next suggestions would be to attempt writing a script that depends on OnOrderUpdate only, or to try adding code in OnOrderUpdate to adjust stops/targets when the entry order is fully filled. This out-of-order Order/Execution events seem to only come up in the case of partial fill.

                Snippet to try in OnOrderUpdate (modification for SampleOnOrderUpdate)

                Code:
                if (order.OrderState == OrderState.Filled && order.Name == "MyEntry")
                {
                    entryOrder = null;
                    sumFilled = 0;
                
                    stopOrder = ExitLongStopMarket(0, true, order.Filled, order.AverageFillPrice - 4 * TickSize, "MyStop", "MyEntry");
                    targetOrder = ExitLongLimit(0, true, order.Filled, order.AverageFillPrice + 8 * TickSize, "MyTarget", "MyEntry");
                }
                You may test my suggestions here and report back your findings. I will be working on this further next week.
                Attached Files
                JimNinjaTrader Customer Service

                Comment


                  #9
                  Hi _Jim
                  This out-of-order Order/Execution events seem to only come up in the case of partial fill.
                  I've only seen this with the partially filled orders, same as you.
                  sidlercom80
                  NinjaTrader Ecosystem Vendor - Sidi Trading

                  Comment


                    #10
                    Hello sildercom80,

                    Thanks for confirming your observations.

                    I have attached a modified SampleOnOrderUpdate strategy that can be used to work around the issue. I tested the case this morning and this looks to handle the issue appropriately. A similar approach can be given for Unmanaged strategies.

                    I am also checking with the Development team if there is anything that we can do on our end to improve the situation in the near term. If there is not anything that can be adjusted without large changes to the connection adapter, we would advise catching these order/execution event ordering issues within the script like the attached script does.

                    I'll keep you posted on our findings.
                    Attached Files
                    JimNinjaTrader Customer Service

                    Comment


                      #11
                      hi_jim thank you very much for your input. i use your template (UnmanagedTemplate). so i understand it correctly. will the incoming order be set in OnOrderUpdate again, or will it stay in OnExecutionUpdate?

                      Code:
                      protected override void OnOrderUpdate
                      ChangeOrder(SLL1, order.Filled, 0, order.AverageFillPrice - InitialStopTick * TickSize);
                      Code:
                      protected override void OnExecutionUpdate
                      SubmitOrderUnmanaged(1, OrderAction.Sell, OrderType.StopMarket, execution.Order.Filled, 0, execution.Order.AverageFillPrice - InitialStopTick * TickSize, ocoExit1, "SLL1");
                      sidlercom80
                      NinjaTrader Ecosystem Vendor - Sidi Trading

                      Comment


                        #12
                        Hello sildercom80,

                        The stop and target get submitted on the execution of the entry order and get updated with subsequent executions to fill after that. Since the order update when the order is filled comes after the Execution, execution.Order is not up to date in OnExecutionUpdate.

                        My workaround checks if there has been a part fill in OnExecutionUpdate. If there is a partfill, do not update the stop/target in OnExecutionUpdate, and update the orders in OnOrderUpdate when we see OrderState.Filled and bPartFilled is true. Using a diff tool, like diffchecker, can help to compare the exact changes I have made if you would like to implement in the same work around in the UnmangedTemplate strategy.

                        Publicly available link to diffchecker - https://www.diffchecker.com/

                        I look forward to assisting.
                        JimNinjaTrader Customer Service

                        Comment


                          #13
                          hello _Jim, thank you very much for your explanation, that's exactly what I thought ;-) In the SIM account everything seems to fit, after a few small adjustments in my script. Can you tell me how I can get a Rithmic demo account for free or at least for a low price without having to open an account with a broker and deposit money? Is there an alternative if you already had a demo account with Rithmic?
                          sidlercom80
                          NinjaTrader Ecosystem Vendor - Sidi Trading

                          Comment


                            #14
                            Hello sildercom80,

                            You could consider using a Rithmic Trading Combine so you can practice trade using Rithmic's paper trading servers. We use this for testing order submissions with Rithmic connections.

                            I had tested with our TopStepTrader test account.
                            JimNinjaTrader Customer Service

                            Comment


                              #15
                              hi _jim i realize that i could test on a combine but i don't want to spend hundreds of dollars in fees just for a test ;-)
                              can i write you a private message?
                              sidlercom80
                              NinjaTrader Ecosystem Vendor - Sidi Trading

                              Comment

                              Latest Posts

                              Collapse

                              Topics Statistics Last Post
                              Started by Sparkyboy, Today, 10:57 AM
                              0 responses
                              1 view
                              0 likes
                              Last Post Sparkyboy  
                              Started by TheMarlin801, 10-13-2020, 01:40 AM
                              21 responses
                              3,916 views
                              0 likes
                              Last Post Bidder
                              by Bidder
                               
                              Started by timmbbo, 07-05-2023, 10:21 PM
                              3 responses
                              152 views
                              0 likes
                              Last Post grayfrog  
                              Started by Lumbeezl, 01-11-2022, 06:50 PM
                              30 responses
                              810 views
                              1 like
                              Last Post grayfrog  
                              Started by xiinteractive, 04-09-2024, 08:08 AM
                              3 responses
                              11 views
                              0 likes
                              Last Post NinjaTrader_Erick  
                              Working...
                              X