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

interested in collaboration with other users to refine some code.

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

    #31



    people with nt,



    the text files with the nt output are in the zip file i uploaded in the previous post as an attachment, and on this post as well.


    the pullback entry reported on 20-03-2020 at 14:02 ended up in a loss of $388 usd, when the stop loss order in the strategy should keep the maximum loss at $42 usd.


    and other entries end up in losses far larger than what the stop loss should keep them to. in this particular case there are only 7 trades with very large losses, but with other strategies i have there are a very high number of such losses above what the stop loss orders should keep them to.


    i'm trying to define a maximum risk for the initial entry, and if there is an attractive pullback, to add an additional contract, but always keeping the monetary value at risk the same. obviously, if the stop loss orders are not working, then this completely defeats this idea.






    Attached Files

    Comment


      #32
      Hello rtwave,

      I'm seeing in the output that the order pustlopuen01 may be getting ignored. (Ignored order TraceOrder messages appear after the first violation and tend not to show for subsequent violations)

      05/03/2021 17:00:00 Strategy 'onorderupdatetests001/-1': Entered internal SubmitOrderManaged() method at 05/03/2021 17:00:00: BarsInProgress=0 Action=Sell OrderType=StopMarket Quantity=1 LimitPrice=0 StopPrice=2196.9 SignalName='pustlopuen01' FromEntrySignal='lopuen01'
      05/03/2021 17:00:00 Strategy 'onorderupdatetests001/-1': Ignored SubmitOrderManaged() method at 05/03/2021 17:00:00: BarsInProgress=0 Action=Sell OrderType=StopMarket Quantity=1 LimitPrice=0 StopPrice=2196.9 SignalName='pustlopuen01' FromEntrySignal='lopuen01' Reason='Invalid order price, please see log tab'

      This order was ignored once, which implies that it is may be ignored many times, and may have been ignored at on 20-03-2020 at 14:00 as the order is never accepted and does not become working.

      20/03/2020 14:00:00 Strategy 'onorderupdatetests001/-1': Entered internal SubmitOrderManaged() method at 20/03/2020 14:00:00: BarsInProgress=0 Action=Sell OrderType=StopMarket Quantity=1 LimitPrice=0 StopPrice=1037.4 SignalName='pustlopuen01' FromEntrySignal='lopuen01'
      20/03/2020 17:00:00 Strategy 'onorderupdatetests001/-1: Cancelled pending exit order, since associated position is closed, orderId='NT-00049-25680' account='Backtest' name='pustlopuen01' orderState=Working instrument='M2K 09-21' orderAction=Sell orderType='Stop Market' limitPrice=0 stopPrice=1037.4 quantity=1 tif=Gtc oco='' filled=0 averageFillPrice=0 onBehalfOf='' id=-1 time='2020-03-20 14:00:00' gtd='2099-12-01' statementDate='2021-09-12'

      Is pustlopuen01 being submitted from OnExecution() when the entry lopuen01 fills, or is this being submitted in OnBarUpdate()?
      (It looks like the stop is being submitted one hour later, which would imply Calculate is OnBarClose and the order is being submitted from OnBarUpdate())

      Are you confirming that the sell stop price is at least 1 tick less than GetCurrentBid() at the time the stop is submitted?
      Chelsea B.NinjaTrader Customer Service

      Comment


        #33



        NinjaTrader_ChelseaB, people with nt,



        thanks a lot.


        this information you have posted is fantastic. i can't believe that it has only taken me since the middle of march and then the last 45 days to achieve all this progress. jaja.


        anyway, all joking aside, it is possible that the problem for my pullback strategies is the structure i have been using:


        - ordinary entries and exits are generated by large bars (10 minute bars) on a bar in progress = 0 subsection of onbarupdate.

        - in the other bar in progress = 1 subsection of onbarupdate, (and on a secondary data series of 1 minute bars) i have the logic to identify pullbacks (ticks higher or lower from averageprice) as well as time conditions of when to trade, liquidate and restore positions.

        - on the onorderandexecutionupdate sections i have just orders and executions.



        the notation i use should be self explanatory, lopuen01 is long pullback entry, pustlopuen01 is pullback stop loss long pullback entry.


        ordinary entries and exits are dictated by large bars in a bar in progress = 0 subsection of onbarupdate and their order objects should associate stop loss orders with every entry on the order and execution methods. pullback entries are generated in a 1 minute bars series and they should also include stop loss orders for every pullback entry.


        if i knew of any better structures to use i would definitely use them.


        this disparity between data intervals and series can easily be the cause for stop loss orders failing every time a second entry is generated. pullback entries do work just as intended, but these entries will cause all stop loss orders to somehow stop working.



        and also, the entire purpose of these strategies is that once a pullback entry is generated, the stop loss orders for all entries (the entire position) should be set at the same level and all the contracts managed in parallel. the objective is to add one additional contract while keeping the total risk for the position the same.


        it seemed to me that i could just redefine the stop loss order for the initial - ordinary entry in the execution method at the same time i was defining the stop loss for the pullback entry but that was not working either so i have disabled that one line as things were even worse when using that code.


        else if (execution.Order.OrderState == OrderState.Filled && shpuenorsufi == execution.Order.Filled && marketPosition == MarketPosition.Short)
        {
        shpuenstor = ExitShortStopMarket(0, true, execution.Order.Filled, execution.Order.AverageFillPrice + ( Costlonuti * TickSize ), "pustshpuen01", "shpuen01");
        // shorenstor = ExitShortStopMarket(0, true, execution.Order.Filled, execution.Order.AverageFillPrice + ( Costlonuti * TickSize ), "pustshoren01", "shoren01");
        }



        from this information that nt support has provided, i will now try to think of ways to place the logic for pullbacks inside the same bar in progress = 0 subsection of onbarupdate. if i manage to make this modification i will report whether the performance of my strategies improves.



        very well, thanks, regards.

        Comment


          #34
          Hello rtwave,

          The TraceOrders and prints output can really tell us a lot, and where to look for issues or mechanisms.

          Below are links to some examples that submit protective exit orders in OnExecution().


          One other note, if this is historical data, intra-bar granularity of 1 tick would also be necessary for order fill accuracy and intra-bar fills.
          Chelsea B.NinjaTrader Customer Service

          Comment


            #35



            people with nt,



            i have been thinking about these strategies.


            trying to have the logic to monitor pullbacks and generate pullback entries on the larger bar section will not work. 1 minute intervals are reasonable if one wants to generate a secondary entry when the profit loss for an initial entry is between 80 and 200 ticks against this entry. however, 10 minute bars or larger could fail frequently if price is made to trade inside this interval and then out of it.



            i have taken a look at all the samples nt makes available but the same logic used to illustrate those samples does not work in this strategy.


            in post 0023 in this thread, i have proven that exit orders will work fine for two entries if they happen at the same time. i have done several tests and in most cases, exit orders work without problem for two entries. if i disable the pullback entry, exit stop loss orders work flawlessly, if i have two simultaneous entries, exit stop loss orders will also work flawlessly.


            however, in these strategies i haven't been able to get to work, i try to make the secondary entry dependent on the profit - loss of the initial entry and this seems to cause the platform or the backtesting - optimizing engine to malfunction. i attach once again the latest version of the strategy that does not work for the people with nt to take a look at. i have been using the same samples nt makes available and the only change of relevance is to have a secondary entry that depends on the profit - loss of an initial entry, it is this that will cause stop loss exit orders to be ignored.


            and the information that the people with nt were able to obtain for the logs i uploaded previously does not make sense. the platform generates an entry and a stop loss order at 17:00 hours, by which time the session is over. and even if the session being over was the cause for all the multiple entries that are left without stop loss orders, the other pullback strategies i have been working on do have time limitations to stop generating entries minutes before the end of the session and to liquidate all positions around 16:43 every day and these malfunctions are even more frequent on those strategies. i have provided the code that does not work as well as log files which capture the errors.


            to me, the only possible explanation would be some kind of platform malfunction, i can't think of any other possibility.



            very well, thanks, regards.
            Attached Files

            Comment


              #36
              Hello rtwave,

              Thanks for your reply.

              NinjaTrader_Chelsea is out of the office today and given the length of this forum post, it would be best to wait for his return.

              We just wanted to acknowledge your post so you are not wondering.

              Thanks in advance for your patience.


              Paul H.NinjaTrader Customer Service

              Comment


                #37


                people with nt,



                Click image for larger version

Name:	20210918 stops working 0001.JPG
Views:	296
Size:	156.7 KB
ID:	1171636


                Click image for larger version

Name:	20210918 stops working 0002.JPG
Views:	264
Size:	244.4 KB
ID:	1171637



                i have been able to fix just one of the pullback strategies i have been working on.


                i had to restrict the pullback entries to being between 80 and 200 ticks against the initial position.



                if ( Position.MarketPosition == MarketPosition.Short && dtc == true && shpuco == true && High[0] > ( Position.AveragePrice + ( Punuti * TickSize ) ) && High[0] < ( Position.AveragePrice + ( Instlonuti * TickSize ) ) )
                {
                EnterShort(Convert.ToInt32(Pullbackentrysize), @"shpuen01");
                shpuco = false;
                }


                a pedestrian, rudimentary ema strategy will generate fantastic returns with the sole addition of nice risk and position management.


                however, this fix does not work with other more elaborate strategies i have developed. i get all the same malfunctions i have documented.

                Comment


                  #38




                  i have been trying to make do with the only sample that nt provides:


                  protected override void OnOrderUpdate(Order order, double limitPrice, double stopPrice, int quantity, int filled, double averageFillPrice, OrderState orderState, DateTime time, ErrorCode error, string nativeError)
                  {
                  if (order.Name == "MyEntry")
                  {
                  entryOrder = order;


                  if (order.OrderState == OrderState.Cancelled && order.Filled == 0)
                  {
                  entryOrder = null;
                  sumFilled = 0;
                  }
                  }
                  }

                  protected override void OnExecutionUpdate(Execution execution, string executionId, double price, int quantity, MarketPosition marketPosition, string orderId, DateTime time)
                  {
                  if (entryOrder != null && entryOrder == execution.Order)
                  {
                  if (execution.Order.OrderState == OrderState.Filled || execution.Order.OrderState == OrderState.PartFilled || (execution.Order.OrderState == OrderState.Cancelled && execution.Order.Filled > 0))
                  {
                  sumFilled += execution.Quantity;


                  if (execution.Order.OrderState == OrderState.PartFilled)
                  {
                  stopOrder = ExitLongStopMarket(0, true, execution.Order.Filled, execution.Order.AverageFillPrice - 4 * TickSize, "MyStop", "MyEntry");
                  targetOrder = ExitLongLimit(0, true, execution.Order.Filled, execution.Order.AverageFillPrice + 8 * TickSize, "MyTarget", "MyEntry");
                  }
                  else if (execution.Order.OrderState == OrderState.Filled && sumFilled == execution.Order.Filled)
                  {
                  stopOrder = ExitLongStopMarket(0, true, execution.Order.Filled, execution.Order.AverageFillPrice - 4 * TickSize, "MyStop", "MyEntry");
                  targetOrder = ExitLongLimit(0, true, execution.Order.Filled, execution.Order.AverageFillPrice + 8 * TickSize, "MyTarget", "MyEntry");
                  }

                  if (execution.Order.OrderState != OrderState.PartFilled && sumFilled == execution.Order.Filled)
                  {
                  entryOrder = null;
                  sumFilled = 0;
                  }
                  }
                  }




                  i copied and pasted the code above 4 times, one each for short and long ordinary and pullback entries. i now realize that it must be the very arguments inside onexecutionupdate that are not working.


                  i ask that nt provide an exhaustive list of all the arguments i can use inside onexecutionupdate to create a stop order. specially, price and quantity.


                  i have tried to reference the entire position average price and it seems like it doesn't work. also, trying to refer to the quantity of another execution is not proving helpful either:



                  if (shpuenor != null && shpuenor == execution.Order)
                  {
                  if (execution.Order.OrderState == OrderState.Filled || execution.Order.OrderState == OrderState.PartFilled || (execution.Order.OrderState == OrderState.Cancelled && execution.Order.Filled > 0))
                  {
                  shpuenorsufi += execution.Quantity;

                  if (execution.Order.OrderState == OrderState.PartFilled && marketPosition == MarketPosition.Short)
                  {
                  shpupuenstor = ExitShortStopMarket(0, true, execution.Order.Filled, execution.Order.AverageFillPrice + ( Costlonuti * TickSize ), "pustpusp01", "shpuen01");
                  // shorenstor = ExitShortStopMarket(0, true, shorenstor.Quantity, Position.AveragePrice + ( Costlonuti * TickSize ), "orstorsp01", "shoren01");
                  // shpuorenstor = ExitShortStopMarket(0, true, Orensi, execution.Order.AverageFillPrice + ( Costlonuti * TickSize ), "pustorsp01", "shoren01");
                  }

                  else if (execution.Order.OrderState == OrderState.Filled && shpuenorsufi == execution.Order.Filled && marketPosition == MarketPosition.Short)
                  {
                  shpupuenstor = ExitShortStopMarket(0, true, execution.Order.Filled, execution.Order.AverageFillPrice + ( Costlonuti * TickSize ), "pustpusp01", "shpuen01");
                  // shorenstor = ExitShortStopMarket(0, true, shorenstor.Quantity, Position.AveragePrice + ( Costlonuti * TickSize ), "orstorsp01", "shoren01");
                  // shpuorenstor = ExitShortStopMarket(0, true, Orensi, execution.Order.AverageFillPrice + ( Costlonuti * TickSize ), "pustorsp01", "shoren01");
                  }

                  if (execution.Order.OrderState != OrderState.PartFilled && shpuenorsufi == execution.Order.Filled)
                  {
                  shpuenor = null;
                  shpuenorsufi = 0;
                  }
                  }
                  }




                  i have developed several profitable strategies, but i will only use nt and nt brokerage to trade automated as is my intention if i can get my strategies to manage risk and positions as i have been trying to do for a number of weeks:


                  if downtrend

                  ordinary short entry at market ( 2 contracts )

                  create stop loss order for ordinary short entry at +200 ticks from initial average entry price ( ordinary short entry )


                  if pullback

                  pullback short entry at market ( 1 contract )

                  create stop loss order for ordinary short entry at +80 ticks from combined average entry price ( average of ordinary and pullback short entries )

                  create stop loss order for pullback short entry at +80 ticks from combined average entry price ( average of ordinary and pullback short entries )


                  if downtrend ends


                  liquidate all short entries

                  cancel all stop orders





                  very well, regards.

                  Comment


                    #39
                    Hello rtwave,

                    All arguments to OnExecutionUpdate() and OnOrderUpdate() that are supported are listed in the help guide.

                    Below are links to the help guide.



                    For OnExecutionUpdate() the quantity will be the amount of contracts in the most recent execution (meaning if the order is part filled, this is the amount of contracts of this part fill). The price will be the price that execution occurred at.

                    For OrderUpdateUpdate() the filled will be the amount of contracts total that have been filled for the order (meaning all combined fills). The averageFillPrice will be the entry price of the order (averaged over all part fills).


                    For creating a stop order with ExitLongStopMarket(), below are the overloads available.
                    ExitLongStopMarket(double stopPrice)

                    ExitLongStopMarket(int quantity, double stopPrice)
                    ExitLongStopMarket(double stopPrice, string fromEntrySignal)
                    ExitLongStopMarket(double stopPrice, string signalName, string fromEntrySignal)
                    ExitLongStopMarket(int quantity, double stopPrice, string signalName, string fromEntrySignal)
                    ExitLongStopMarket(int barsInProgressIndex, bool isLiveUntilCancelled, int quantity, double stopPrice, string signalName, string fromEntrySignal)

                    Let me know if you need any help analyzing the output from prints or traceorders that I may assist with.
                    Chelsea B.NinjaTrader Customer Service

                    Comment


                      #40



                      people with nt,



                      i did not make myself understood.


                      i ask for a list of all the coding values or inputs that can be used inside the executionupdate section.


                      i have read the help guide several times. the only thing it states is this:



                      price A double value representing the execution price

                      quantity An int value representing the execution quantity



                      i have been working by trial and error on the only sample exit order available by making the changes i could think of:


                      stopOrder = ExitLongStopMarket(0, true, execution.Order.Filled, execution.Order.AverageFillPrice - 4 * TickSize, "MyStop", "MyEntry");




                      ¿what other values can i use instead of execution.Order.Filled?

                      ¿can i reference the number of filled contracts of another execution?



                      ¿what other values can i use instead of execution.Order.AverageFillPrice? i imagine i could use high, low, close and all those, ¿but can i reference the average price for an entire position? ¿can i reference the average price of another different execution? ¿can i use a private variable inside executionupdate?


                      if i only use one ordinary entry everything works fine, i want to understand if i can code an initial entry and then when a secondary entry is executed, create a stop loss order for that secondary entry in the executionupdate section and also move - redefine - modify the stop loss for the initial entry in that same section, at the same time, with the same values.


                      stopOrder2 = ExitShortStopMarket(0, true, execution.Order.Filled, average position price + 80 * TickSize, "MyStop2", "MyEntry2");
                      stopOrder1 = ExitShortStopMarket(0, true, entry1 quantity, average position price + 80 * TickSize, "MyStop1", "MyEntry1");




                      that is exactly what i have been working and have not been able to perform as desired:


                      if pullback

                      pullback short entry at market ( 1 contract )

                      move - redefine - reset - modify (create) stop loss order for ordinary short entry at + 80 ticks from combined average entry price ( average of ordinary and pullback short entries )

                      create stop loss order for pullback short entry at + 80 ticks from combined average entry price ( average of ordinary and pullback short entries )




                      very well, regards.

                      Comment


                        #41
                        Hello rtwave,

                        Where you have asked:
                        "i ask for a list of all the coding values or inputs that can be used inside the executionupdate section."

                        I'm not entirely certain what you are asking for. The OnExecutionUpdate() method is an override void that runs when an execution event occurs. This is not method you call yourself, and would not be supplying any inputs to this.

                        The overload properties provided are information about the execution. The execution object is provided, the executionId, price, quantity, marketPositoin, orderId, and DateTime of the execution.
                        protected override void OnExecutionUpdate(Execution execution, string executionId, double price, int quantity, MarketPosition marketPosition, string orderId, DateTime time)
                        {
                        // code to run here when an execution happens
                        }

                        The execution.Order.Filled is total filled amount of the order object. execution.quantity is the quantity of this specific execution.

                        Where you have mentioned:
                        "what other values can i use instead of execution.Order.Filled?"

                        What other values do you want? If you don't want to use the filled amount of the order, you can use an integer you make up instead.

                        Where you have mentioned:
                        "can i reference the number of filled contracts of another execution?"

                        Yes, save that execution to an Execution variable when the execution updates in OnExecutionUpdate(), or just save the execution quantity to an integer. Then you'll have that execution to reference at any time, as it's stored in a variable.

                        private int saveExecutionQuantityForLater;
                        protected override void OnExecutionUpdate(Execution execution, string executionId, double price, int quantity, MarketPosition marketPosition, string orderId, DateTime time)
                        {
                        saveExecutionQuantityForLater = quantity;
                        }

                        protected override void OnBarUpdate()
                        {
                        Print(saveExecutionQuantityForLater);
                        }

                        Where you mention:
                        "what other values can i use instead of execution.Order.AverageFillPrice?"

                        You can use any valid double that is a valid price for the order you are placing. For example if the order is a sell stop, a price below the GetCurrentBid() is a valid price.

                        Where you mention:
                        " i imagine i could use high, low, close and all those, but can i reference the average price for an entire position?"

                        Yes, you can reference Position.AveragePrice.


                        Where you mention:
                        "can i reference the average price of another different execution?"

                        Yes, save that price to a double variable when the execution updates, then use that double variable wherever you would like.

                        Where you mention:
                        "can i use a private variable inside executionupdate?"

                        Yes, you can use private variables in any method in C#.
                        Chelsea B.NinjaTrader Customer Service

                        Comment


                          #42



                          people with nt, NinjaTrader_ChelseaB,




                          thanks.


                          not being able to put my ideas into code is really frustrating. however, i cannot trade these strategies with real funds if the position management is not working exactly as intended.




                          i have tried everything i can think of but stop loss orders will still be ignored after a secondary entry that depends on the profit - loss of an initial entry is triggered.



                          i have tried orders like this one inside of executionupdate, with this setting:



                          ExitShortStopMarket(0, true, Position.Quantity, Position.AveragePrice + ( Costlonuti * TickSize ), "shpustpuen01", "shpuen01");

                          StopTargetHandling = StopTargetHandling.ByStrategyPosition;


                          this will result in not even a single one of these stop loss orders triggering at the level they should.



                          i have tried orders like the one below:


                          ExitShortStopMarket(0, true, execution.Order.Filled, execution.Order.AverageFillPrice + ( Costlonuti * TickSize ), "pustshpuen01", "shpuen01");

                          StopTargetHandling = StopTargetHandling.PerEntryExecution;


                          and this will fail as well, some orders will trigger but a lot will not.





                          and the platform ignoring the orders because of price does not make any sense.


                          i am trying to set stop orders 60 to 200 ticks away from the latest execution or the position's average price, that should be more than enough distance away from the bid - ask spread at the time of the secondary execution. and the stop loss orders will indeed work as they should if i disable the secondary entry or if both entries are simultaneous and at the same level.



                          i was asking whether i could use expressions like shorenstor.Quantity or Position.AveragePrice inside executionupdate and i now have but that has made the performance even worse.




                          i will have to concentrate on strategies with one single entry and leave this more ambitious position management for later.



                          ¿can nt provide a working sample of a strategy with two entries, where a secondary entry depends on a 200 tick profit or loss of an initial entry and all entries - contracts have stop loss orders at all times? i have tried tens and tens of different versions but still there will be immense losing trades that should have been cut by the stop loss orders.



                          i will try to upload the nt output for the latest failed strategy i have tried, just to document these persistent issues.



                          very well, thanks, regards.

                          Comment


                            #43
                            Hello rtwave,

                            Previously, we found you have orders with invalid prices. Have you corrected that behavior yet?

                            Use Print() and TraceOrders to understand why any condition is evaluating as true or false and to understand if any order is submitted, ignored, rejected, cancelled, or filled.

                            My recommendation is that you do not change the logic in the code before understanding the behavior. Once you have understanding of the current behavior, then change the script to get the behavior you want.

                            Choose a specific order you are expecting to fill at a specific time.

                            Print all values in the condition that trigger the order method along with the time of the bar. Enable TraceOrders. Print the order object in OnOrderUpdate().

                            Save the output to a text file, and post this if you would like assistance analyzing the output.
                            Chelsea B.NinjaTrader Customer Service

                            Comment


                              #44
                              hello rtwave,

                              I ran across this on an unrelated issue and wondered if you found any collaborator's?

                              I actually made similar posts in the past looking for others interested in shorter term (intra-day) systems.

                              I was surprised there was not a whole lot of interest.

                              In any event if you are still seeking an extra pair of hands let me know either here or glendemarco [at] gmail [dot] com.

                              Good luck to you.

                              glen
                              Last edited by NinjaTrader_ChelseaB; 12-19-2021, 07:45 PM.

                              Comment


                                #45
                                Hello glen,

                                I removed the link to your email and modified this a bit to keep web crawlers from spamming you.

                                Just a consideration, you might want to send a private message if it has your email in it.
                                Chelsea B.NinjaTrader Customer Service

                                Comment

                                Latest Posts

                                Collapse

                                Topics Statistics Last Post
                                Started by maybeimnotrader, Yesterday, 05:46 PM
                                5 responses
                                24 views
                                0 likes
                                Last Post NinjaTrader_ChelseaB  
                                Started by NRITV, Today, 01:15 PM
                                1 response
                                4 views
                                0 likes
                                Last Post NinjaTrader_Jesse  
                                Started by quantismo, Yesterday, 05:13 PM
                                2 responses
                                16 views
                                0 likes
                                Last Post quantismo  
                                Started by frankthearm, Today, 09:08 AM
                                6 responses
                                27 views
                                0 likes
                                Last Post frankthearm  
                                Started by adeelshahzad, Today, 03:54 AM
                                5 responses
                                33 views
                                0 likes
                                Last Post NinjaTrader_BrandonH  
                                Working...
                                X