Announcement

Collapse
No announcement yet.

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 ;-)

    #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!

      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?

        Comment


          #5
          here for testing purposes a demo account with oneup trader. it's just this trade, nothing else.

          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.

            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?

              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.

                  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");

                      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?

                          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?

                              Comment

                              Latest Posts

                              Collapse

                              Topics Statistics Last Post
                              Started by CyberNate, Today, 03:11 PM
                              3 responses
                              10 views
                              0 likes
                              Last Post CyberNate  
                              Started by NinjaTrader_ChrisL, Today, 03:44 PM
                              0 responses
                              4 views
                              0 likes
                              Last Post NinjaTrader_ChrisL  
                              Started by TheBean236, Today, 12:57 PM
                              5 responses
                              17 views
                              0 likes
                              Last Post TheBean236  
                              Started by DTSSTS, Today, 09:59 AM
                              7 responses
                              39 views
                              0 likes
                              Last Post DTSSTS
                              by DTSSTS
                               
                              Started by Kirk Thorns, Today, 12:46 PM
                              2 responses
                              10 views
                              0 likes
                              Last Post Kirk Thorns  
                              Working...
                              X