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

logic processing - always in strategy

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

    logic processing - always in strategy

    Hi,
    When running an OnBarUpdate "always in" style strategy (always long or short), and which contains contract quantity logic based on cumulative profit, what will be my best practice in order to ensure the contract quantity logic is processed after one trade exits and before the next trade enters at (OnBarUpdate) ?
    thanks,
    David
    Last edited by trader3000a; 10-12-2023, 04:59 AM.

    #2
    Hello David,

    A trade exiting would mean an exit order being filled, which will update in OnOrderUpdate() with OrderState.Filled, and OnExecutionUpdate(), either of which would be a good time to run the logic.
    Chelsea B.NinjaTrader Customer Service

    Comment


      #3
      Hi Chelsea,

      I'm guessing the SystemPerformance values aren't able to squeeze in between an exit and an entry the way I'd hoped in my always-in strategy, since when attempting this:

      if (SystemPerformance.AllTrades.Count > 0 )
      {
      AccountSize= AccountStartValue + SystemPerformance.AllTrades.TradesPerformance.Curr ency.CumProfit;
      AccountRisk = (AccountSize * .15) / 1250;
      Contracts = (int)Math.Round((AccountRisk));
      }


      or this:

      if (SystemPerformance.AllTrades.Count > 0 )
      {
      Trade lastTrade = SystemPerformance.AllTrades[SystemPerformance.AllTrades.Count - 1];
      double lastProfit = lastTrade.ProfitCurrency;
      AccountSize= AccountSize + lastProfit
      AccountRisk = (AccountSize * .15) / 1250;
      Contracts = (int)Math.Round((AccountRisk));


      within the overrides, once order.OrderState == OrderState.Filled, the "Contracts" value is being updated 1 trade too late each time.

      Is there an alternative method to process my profit/contracts logic in those milliseconds between the exit and entry of an always-in system?

      thanks,
      David
      Last edited by trader3000a; 10-13-2023, 05:45 AM.

      Comment


        #4
        Hello David,

        SystemPerformance is a collection of completed trades.

        This updates after the exit order fills when the position updates in OnPositionUpdate().

        OnOrderUpdate() and OnExecution() will run after each fill.

        If you want to do a calculation before the next entry, do the calculation before submitting the new entry.
        Chelsea B.NinjaTrader Customer Service

        Comment


          #5
          Hi Chelsea,
          Thanks, but I think I'm still behind the learning curve in this area. I've pasted what i'm doing below. I understand that you're limited to a certain degree of assistance, but perhaps you could point me to an example that might help. The "SampleOnOrderUpdate" file goes in a direction from which I can't seem to extrapolate what i need.
          thanks,
          David

          private int Contracts;
          private double AccountSize;​

          protected override void OnBarUpdate()
          {

          if(CurrentBar < BarsRequiredToTrade || BarsInProgress != 0) return;

          // Set the # of contracts for the first trade
          if (SystemPerformance.AllTrades.Count == 0 )
          {
          AccountSize= AccountStartValue;
          Contracts = (int)Math.Round(AccountSize * .15) / 1250;
          }



          // long entry
          if (Close[0] > Close[50] && Close[0] < Close[15])
          {
          EnterLong(Contracts, "LongEntry");
          }

          // short entry
          if (Close[0] < Close[50] && Close[0] > Close[15])
          {
          EnterShort(Contracts, "ShortEntry");
          }

          }

          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.OrderState == OrderState.Filled)
          {
          //Set the # of contracts for the second and all subsequent trades
          AccountSize= AccountStartValue + SystemPerformance.AllTrades.TradesPerformance.Curr ency.CumProfit;
          Contracts = (int)Math.Round(AccountSize * .15) / 1250;

          Print("---------------------");
          Print(Convert.ToString(Times[0][0]));
          Print("AccountSize = " + AccountSize.ToString());
          Print("Contracts = " + Contracts);
          Print("orderstate = " + order.OrderState);
          }

          }​
          Last edited by trader3000a; 10-13-2023, 10:45 AM.

          Comment


            #6
            Hello trader3000a,

            What chelsea had described would be to place that code inside OnbarUpdate instead of OnOrderUpdate or OnExecutionUpdate. If the intention is to recalculate that value before the next entry it would be suggested that code comes before your entry logic inside OnBarUpdate.

            The code //Set the # of contracts for the second and all subsequent trades should go before your // long entry code. That will keep the value updated before the entry orders.
            JesseNinjaTrader Customer Service

            Comment


              #7
              Hi Chelsea, Jesse,

              The issue persists. Please see attachments. I've included both screenshots and the .zip add-on.

              As you can see, after the first trade closes and we are flat, we have a profit update of 34499.99, but the AccountSize variable is not updated with this profit until the close of the second trade.

              "ccontracts" for the second trade should be 7, not 3. "contracts for the third trade should be 10, not 7, and so on.

              Where is my error?

              When i use this type of position sizing code on a strategy which is not always-in, it works correctly, updating before the next entry.

              This is why i asked originally if there is an alternate method, since I can't seem to use the AllTrades data with the AccountSize calc during the miniscule flat period of an always-in approach.

              I'm wondering, since position sizing based on the account size after the close of the most recent trade is fundamental to money management, if you might create a "Sample" strategy for us that works for an always-in approach.

              thanks,
              David
              ​
              Attached Files
              Last edited by trader3000a; 10-14-2023, 08:13 AM.

              Comment


                #8
                Hello trader3000a,

                Because you are doing a reversal you would have to wait at least 1 bar for that information to be updated. The exit is happening at the same time as the entry which does not allow any time for values to be updated. If you need that value to be updated you would need to avoid using the automatic reversal by calling the opposite entry and just use exit orders instead. Wait for the value to be updated by waiting 1 OnBarUpdate event and then submit your re entry.
                JesseNinjaTrader Customer Service

                Comment


                  #9
                  Hi Jesse, Chelsea,

                  Would it be possible, with a reversal system, to move the entire system into the higher granularity of OnPositionUpdate or OnExecutionUpdate, placing the calculation within the flat period after an exit and before an entry? Or is the flat period in these environments simply a data point, nonexistent between the exit and entry? Is there 0 space to exploit between the two positions' execution requests' delivery to and from the exchange?

                  thanks,
                  David

                  Comment


                    #10
                    Hello trader3000a,

                    It does not matter what granularity you use, the entry and exit happen at the exact same time so there is no time for the trade collection to be updated before the next entry. The next update will be on the following OnBarUpdate event after the exit was filled. To have time after the exit and before the next entry would require not using the automatic reversal so you can have at least 1 OnBarUpdate event after the exit fills. That would give the collection time to populate the trade which is an entry + exit.
                    JesseNinjaTrader Customer Service

                    Comment


                      #11
                      Hi Jesse,
                      Is there documentation in the library I can read to better understand the steps taken between NT and the exchange in a reversal system?
                      thanks,
                      David

                      Comment


                        #12

                        Incidentally, I've been able to achieve something very close to the desired result by adding the unrealized profit to the calculation:

                        AccountSize = SystemPerformance.AllTrades.TradesPerformance.Curr ency.CumProfit; + InitialCapital + Position.GetUnrealizedProfitLoss(PerformanceUnit.C urrency, Close[0]);

                        If the unrealized profit is updated at the close of the bar prior to the reversal execution, perhaps I can add a smaller bar series and get an update as close as possible to my primary series

                        but i'm wondering if you could confirm that this is tenable in real time as opposed to something that only works within the backtest environment..

                        David
                        Last edited by trader3000a; 10-16-2023, 09:26 AM.

                        Comment


                          #13
                          Hello trader3000a,

                          There is not any specific information about reversals besides a note in the managed approach documentation letting you know that calling the opposite entry will both exit the position and reverse it.

                          For the trade performance to be updated you would have to wait for the exit to be filled and then on the following OnBarUpdate it will contain a paired trade so you can access that data. Using the automatic reversal will not allow that to be checked between the exit and entry because they are in the same OnBarUpdate event.
                          JesseNinjaTrader Customer Service

                          Comment

                          Latest Posts

                          Collapse

                          Topics Statistics Last Post
                          Started by jxs_xrj, 01-12-2020, 09:49 AM
                          6 responses
                          3,290 views
                          1 like
                          Last Post jgualdronc  
                          Started by Touch-Ups, Today, 10:36 AM
                          0 responses
                          8 views
                          0 likes
                          Last Post Touch-Ups  
                          Started by geddyisodin, 04-25-2024, 05:20 AM
                          11 responses
                          61 views
                          0 likes
                          Last Post halgo_boulder  
                          Started by Option Whisperer, Today, 09:55 AM
                          0 responses
                          8 views
                          0 likes
                          Last Post Option Whisperer  
                          Started by halgo_boulder, 04-20-2024, 08:44 AM
                          2 responses
                          24 views
                          0 likes
                          Last Post halgo_boulder  
                          Working...
                          X