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

One instrument - many many open trades

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

    One instrument - many many open trades

    Need some help with a layout here guys.

    I want to develop a strategy on a single instrument, which can have an arbitrary number of positions open at any time. Many longs and many shorts, all with there own stop and take profit levels.

    I've had a lot of success programming strategies with just one open trade at a time, using EnterLong(), EnterShort(), SetStopLoss(), and SetProfitTarget().

    I guess my question is, can I use the same functions if I anticipate many trades open at once? I know I have to rework a lot of the logic I have in place, but aside from that. I'm trying to figure out the best way to use the signal names ... something like EnterLong("Long" + someLongIntTradeCounter) ... does this make sense? Then I'd use that same string for the stops and take profits. Is this the best way to handle the above problem or will I be overcomplicating something NT already does?

    Keep in mind if I do the above, and backtest for say a year, I may end up with Long1254363 as a trade counter ... I'm not sure if there are any problems with that.

    I hope this was clear.

    #2
    Hello Locke,

    Thank you for your note.

    Your layout looks good and you have the right idea for trade counter in the signal name.

    You would want to increase the EntriesPerDirection property to allow you to have multiple trades in each direction that you are wanting.

    Let me know if I can be of further assistance.
    Cal H.NinjaTrader Customer Service

    Comment


      #3
      Ok, getting an error where only the first trade executes. And then after that in the output window I get:

      **NT** Error on calling 'OnExecution' method for strategy 'LclVolMulti/7f49bb5cf2b743c2bfb957e19d36ecfd': Object reference not set to an instance of an object.

      So it goes through one complete trade entry and exit, but then this error pops out, presumably after the 2nd trade signal goes through and it enters OnExecution().

      Here is a really basic structure of the order process:
      In OnBarUpdate() : resets stuff - tradedPx, stopPx, takeProfitPx, and sets entryOrder = null;
      Then it checks condtions, and enters a trade using either EnterLong() or EnterShort().
      like this:
      entryOrder = EnterLong(DefaultQuantity,
      "Long"+counterLong);


      In OnExecution: I'll put the code ..
      protectedoverridevoid OnExecution(IExecution execution)
      {
      if (entryOrder != null && entryOrder != execution.Order)
      {
      Print(Time[
      0] + " Traded at " + execution.Order.AvgFillPrice);
      }
      // end if

      if (entryOrder != null && entryOrder == execution.Order)
      {
      tradedPx = execution.Order.AvgFillPrice;
      Print(Time[
      0] + " Traded entry at " + tradedPx);

      if (execution.MarketPosition == MarketPosition.Long)
      {
      my_SetStopLoss(
      "Long"+counterLong, true);
      my_SetProfitTarget(
      "Long"+counterLong, true);
      }
      // end if

      if (execution.MarketPosition == MarketPosition.Short)
      {
      my_SetStopLoss(
      "Short"+counterShort, false);
      my_SetProfitTarget(
      "Short"+counterShort, false);
      }
      // end if
      } // end if
      } // end OnExecution()

      Comment


        #4
        Locke,

        Are you getting the two prints from the OnExecution?

        Have you check the my_SetStopLoss() methods that you have created and see if they are generating the error?
        Cal H.NinjaTrader Customer Service

        Comment


          #5
          I get the print statement in the trade entry part.
          3/12/2015 6:28:00 PM Traded entry at 1.4881
          3/12/2015 6:28:00 PM Setting Short stop loss = 1.4891

          And then the error, that's it.

          In OnBarUpdate() on the very next bar I reset entryOrder = null, so that first if block and print statement probably never gets hit. I'm basically overwriting entryOrder for , well, every trade entry, but immediately on the next calc. Before, when I had this working perfectly for only one trade at a time, I wouldn't reset entryOrder until the previous trade had exited (not sure this matters at all).

          I'm not sure if the takeprofit or stop loss is causing the error. I do get that trade execution. I get the trade entry, the exit, and then no more trade entries.

          There's nothing fancy in my stop loss wrappers - here is one of them:
          // Wrapper to put all SetStopLoss in one spot; longOrShort true = long
          privatevoid my_SetStopLoss(String input, bool longOrShort)
          {
          // set when long
          if(longOrShort)
          {
          stopPx = Math.Round(tradedPx-NumStopTicks*myTickSize,
          5);
          SetStopLoss(input, CalculationMode.Price, stopPx,
          false);
          }
          // end if

          //set when short
          if(!longOrShort)
          {
          stopPx = Math.Round(tradedPx+NumStopTicks*myTickSize,
          5);
          SetStopLoss(input, CalculationMode.Price, stopPx,
          false);
          }
          // end if

          Print(Time[
          0] + " Setting " + (longOrShort ? "Long stop loss = " : "Short stop loss = ")+ stopPx);
          }
          // end my_SetStopLoss

          Comment


            #6
            Locke,

            I would advise adding some prints with numbers to see where the logic might be breaking down.

            Example -
            Code:
            protectedoverridevoid OnExecution(IExecution execution)
            {
            [B]Print(1);[/B]
            if (entryOrder != null && entryOrder != execution.Order)
            {
            Print(Time[0] + " Traded at " + execution.Order.AvgFillPrice);
            } // end if
            
            [B]Print(2);[/B]
            if (entryOrder != null && entryOrder == execution.Order)
            {
            tradedPx = execution.Order.AvgFillPrice;
            Print(Time[0] + " Traded entry at " + tradedPx);
            
            [B]Print(3);[/B]
            if (execution.MarketPosition == MarketPosition.Long)
            { 
            [B]Print(3.1);[/B]
            my_SetStopLoss("Long"+counterLong, true);
            [B]Print(3.2);[/B]
            my_SetProfitTarget("Long"+counterLong, true);
            [B]Print(3.3);[/B]
            } // end if
            
            [B]Print(4);[/B]
            if (execution.MarketPosition == MarketPosition.Short)
            {
            [B]Print(4.1);[/B]
            my_SetStopLoss("Short"+counterShort, false);
            [B]Print(4.2);[/B]
            my_SetProfitTarget("Short"+counterShort, false);
            [B]Print(4.3);[/B]
            } // end if
            } // end if
            } // end OnExecution()
            The concept here is create a trail and follow the trail when it breaks. If the trail doesn't end and works all the way through, then move on to the next method and apply the same concept.
            Cal H.NinjaTrader Customer Service

            Comment


              #7
              3/12/2015 6:28:00 PM Hi in GoShort
              3/12/2015 6:28:00 PM Traded entry at 1.4881
              3/12/2015 6:28:00 PM Hi in exec short1
              3/12/2015 6:28:00 PM Setting Short stop loss = 1.4891
              3/12/2015 6:28:00 PM Hi in exec short2
              3/12/2015 6:28:00 PM Hi in exec short3
              3/12/2015 7:04:00 PM Hi in GoLong
              **NT** Error on calling 'OnExecution' method for strategy 'LclVolMulti/a5df74b0a2f24559b35182ca49579096': Object reference not set to an instance of an object.


              My log.

              privatevoid GoLong()
              {
              Print(Time[
              0] + " Hi in GoLong ");
              entryOrder = EnterLong(DefaultQuantity,
              "Long"+counterLong);
              }
              // end GoLong()

              The go long function.
              So it breaks when I set entryOrder a 2nd time. It had been set to null previous to this (that's in OnBarUpdate()).
              I'm getting stumped here. Unless there is some quirk with using EnterLong and EnterShort I don't know about.

              Comment


                #8
                This really driving me nuts.
                In OnBarUpdate() I set entryOrder = null.
                Then I go thru my condtions, and EITHER set entryOrder = EnterLong() or EnterShort() (with the wrapper).
                In OnExecution, the stops and take profits are set. All of this uses a unique string for each trade.

                Now, when entryOrder is set back to null in OnBarUpdate(), and the original trade hasn't been exited, does that mess anything up? I'd think no, because the set stop and take profit still works for the first trade.

                I put in all the print statements. It makes it's way back to GoLong (for the 2nd trade entry) just fine. It's when it goes back into OnExecution() (the third time I suppose. 1 for entry, 1 for exit, and now for entry again) that it gives me this object ref not set error.

                **NT** Enabling NinjaScript strategy 'LclVolMulti/95fe6d84f7734626adbe98ec4c8c904d' : On starting a real-time strategy - StrategySync=WaitUntilFlat SyncAccountPosition=False EntryHandling=UniqueEntries EntriesPerDirection=10 StopTargetHandling=ByStrategyPosition ErrorHandling=StopStrategyCancelOrdersClosePositio ns ExitOnClose=False Set order quantity by=Strategy ConnectionLossHandling=KeepRunning DisconnectDelaySeconds=10 CancelEntryOrdersOnDisable=True CancelExitOrdersOnDisable=True CalculateOnBarClose=False MaxRestarts=4 in 5 minutes
                3/12/2015 6:28:00 PM Hi in GoShort1
                3/12/2015 6:28:00 PM Hi in GoShort2
                3/12/2015 6:28:00 PM Traded entry at 1.4881
                3/12/2015 6:28:00 PM Hi in exec short1
                3/12/2015 6:28:00 PM Setting Short stop loss = 1.4891
                3/12/2015 6:28:00 PM Hi in exec short2
                3/12/2015 6:28:00 PM Hi in exec short3
                3/12/2015 7:04:00 PM Hi in GoLong1
                3/12/2015 7:04:00 PM Hi in GoLong2
                **NT** Error on calling 'OnExecution' method for strategy 'LclVolMulti/95fe6d84f7734626adbe98ec4c8c904d': Object reference not set to an instance of an object.

                Comment


                  #9
                  Locke,

                  Is there nothing else getting called after this method?

                  I don't see an issue with this method and wouldn't expect to get the Object reference error.
                  Cal H.NinjaTrader Customer Service

                  Comment


                    #10
                    Cal, no that's it. It doesn't seem that complicated, I just wanted to make sure I had all calls in the appropriate place. I'm running out of things to test.

                    Comment


                      #11
                      Locke,

                      Can you export your strategy and send it to me so I can test on my end?

                      File -> Utilities -> Export NinjaScript -> Regular export

                      Send it to platformsupport [at] ninjatrader [dot] com with ATTN Cal in the subject and reference this thread in the body
                      Cal H.NinjaTrader Customer Service

                      Comment


                        #12
                        Cal.. this is crazy. I commented out this first block from OnExecution() and it worked. I have this code in other programs and it works fine.

                        if (entryOrder != null && entryOrder != execution.Order)
                        {
                        Print(Time[0] + " Traded at " + execution.Order.AvgFillPrice);
                        } // end if


                        How crazy is that? So that has to remain a mystery to me for now. I have another issue.

                        So it works, but back to my original original original question. I'd like to use EnterLong(), EnterShort(), SetStopLoss() and SetProfitTarget() to manage many many trades.

                        However, now that my code is working, I'm seeing that even though I put a unique string in for my EnterLong and EnterShort trades, it will cancel out the old one and put the new trade on. That is, I enter a long. I have stops and take profit set for it. I get an enter short signal and it calls EnterShort with a different string ID. It closes the first long, and then enters the short.

                        This is behavior I want sometimes, but not here. I thought using the string IDs would handle this? If not, do I have to use different order functions to get the behavior I want?

                        Thanks sir.

                        Comment


                          #13
                          Locke,

                          You would need to use Unmanaged approached for this. You cannot have two working orders for opposite directions using Managed Approach
                          Cal H.NinjaTrader Customer Service

                          Comment

                          Latest Posts

                          Collapse

                          Topics Statistics Last Post
                          Started by knighty6508, Today, 01:20 AM
                          2 responses
                          8 views
                          0 likes
                          Last Post knighty6508  
                          Started by franatas, Today, 01:53 AM
                          0 responses
                          1 view
                          0 likes
                          Last Post franatas  
                          Started by knighty6508, Today, 01:17 AM
                          0 responses
                          9 views
                          0 likes
                          Last Post knighty6508  
                          Started by tierraany, Today, 01:06 AM
                          0 responses
                          4 views
                          0 likes
                          Last Post tierraany  
                          Started by Wilmarobyi, Today, 12:48 AM
                          0 responses
                          3 views
                          0 likes
                          Last Post Wilmarobyi  
                          Working...
                          X