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

Creating a multi instrument strategy with maximum number of positions

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

    Creating a multi instrument strategy with maximum number of positions

    Hi there,

    I am new to NinjaTrader and preparing to code / implement a strategy that I am already trading and wanted to check that NT8 can provide the functionality I need before going too far. Apologies for the newbie questions!

    I am using Amibroker for backtesting and Interactive Brokers to place trades in a cash (not margin) account. I have a system that enters long trades when todays price sells off X % below yesterdays low and then places a stop based on the fill price. Exits are managed manually. As I live in Australia and getting a margin account with IB requires setting up a company which I don't want to do for tax reasons.

    I would like to set up a strategy in Ninjatrader that does the following:
    1. Reads from a text file a list of potential stocks to trade including the position size for each stock, stocks will only be traded in the session if entry conditions are met;
    2. Reads the maximum number of positions the system is allowed to open in the session across all stocks from a text file (each stock only opens 1 position);
    3. If a stock in the list drops X % below yesterdays daily low, Ninja Trader enters long for the position size allocated and also places a stop Y% below the fill price (due to the account being non-margin, I cannot place all the orders at the start of the session as the total order values is more than the cash available);
    4. Once the maximum number of trades is reached in the session (e.g. 5 stocks trigger entries and there are only 5 positions allowed), the strategy stops entering new positions;
    5. Exits are managed manually (not within the strategy as they may be a few days later);


    The strategy would be started each day and the list of stocks refreshed in the text file each day.

    I wanted to know the following:
    1. Can all of the above be achieved in managed mode in NT8 (I just started learning C# and am not a programmer so my programming skills are not up to scratch to program in unmanaged mode)?
    2. Are there any limitations that you are aware of in achieving the above in NT8 that I should know?
    3. Can you provide some links on how to handle counting of the number of positions entered across the multiple instruments?


    Many thanks!

    Numbo

    #2
    Hello Numbo,

    While it is possible to read from a file, and it would be possible to add instruments to script with a loop, it would not be supported by NinjaTrader Support to do so (as dynamically adding instruments can cause unexpected behavior especially when optimizing).

    From the help guide:
    "Arguments supplied to AddDataSeries() should be hardcoded and NOT dependent on run-time variables which cannot be reliably obtained during State.Configure (e.g., Instrument, Bars, or user input). Attempting to add a data series dynamically is NOT guaranteed and therefore should be avoided. Trying to load bars dynamically may result into an error similar to: Unable to load bars series. Your NinjaScript may be trying to use an additional data series dynamically in an unsupported manner."


    It would not be possible to find out through the NinjaTrader Platform what the maximum amount of positions are for your connected brokerage. You would need to contact your broker, inquire about this, and then code those limits in the script itself. The NinjaTrader Platform cannot access this information from the brokerage.

    (edit)
    Below I am including a link to a reference sample that demonstrates reading from a text file.


    Yes, you can code logic automate entries based on criteria such as the current price being a certain percent below the low of the previous session and place a stop loss and profit target at a calculated distance.

    Yes, you can also code logic into your script to not place entries based on criteria such as a maximum number of trades reached and reset this at the start of a new session.

    Below is a link to an example that stops trading when a loss amount is hit and resets on the new session.
    Hello, I've updated the DailyLossLimit and DailyLosLimitMultiTrade examples that were posted on the forum for NinjaTrader 7 for NinjaTrader 8. These are often requested and I felt they are good examples to have for NT8. DailyLossLimitExample_NT7 - http://ninjatrader.com/support/forum...241#post451241 (http://ninjatrader


    See below about getting started with NinjaScript.


    Fully automated NinjaScripts are not intended to be managed manually. For strategies where orders (such as exit orders) are intended to be managed manually, the Atm Strategy Methods where created for this purpose. These methods allow the strategy to generate the entry based on logic, but place the order outside of the strategy similar to a manual order so that the order and exit orders generated by the Atm can then be manually managed.



    Below is a link to an official reference sample that demonstrates how to add additional data series.
    You can submit orders to different Bars objects. This allows you the flexibility of submitting orders to different timeframes. Like in live trading, taking entry conditions from a 5min chart means executing your order as soon as possible instead of waiting until the next 5min bar starts building. You can achieve this by


    As well as a link to the help guide on the AddDataSeries() method.

    A link to the help guide on BarsInProgress.


    And a link to the help guide on Multi-Time Frame & Instruments. Please see the section 'How Bar Data is Referenced', and 'Accessing the Price Data in a Multi-Bars NinjaScript'.
    Last edited by NinjaTrader_ChelseaB; 07-03-2017, 07:35 AM.
    Chelsea B.NinjaTrader Customer Service

    Comment


      #3
      Hi Chelsea,

      Many thanks for the response and all the links. I will work my way through them.

      Instead of reading the symbols from a file, I assume I could also create an instrument list (can this be automated) with the symbols to trade on each day and just run the strategy on this. Could the list then be refreshed with new candidates and no longer eligible candidates deleted each day automatically?

      With respect to exiting positions, as the positions are held for multiple days and I am required to log out of Interactive Brokers daily I planned to exiting positions manually. However is there a way that I can use NT to automatically exit the positions rather than using an ATM strategy even though they remain open for a number of days? Can you provide some links on this? How is strategy management affected if Interactive Brokers needs to restart, NT needs to restart, etc. Will the open positions be recognised by NT if it is restarted (and I assume the strategy restarted) and the positions exited when the exit rules are met? Or is there a risk of the current state of the system being lost?

      Thanks!

      Numbo

      Comment


        #4
        Hello Numbo,

        You could loop through an instrument list.

        However, there are no supported methods to modify an instrument list through code. These must be edited manually.

        You can do either or both.
        If you are in a position that is started with Atm Strategy methods, you can call a method to check that Atm position by supplying the Aatm strategy id, and then you can close that position.
        So if you wanted to close the position at a specific time this would be possible.



        You can also move the entry (before it fills) and stop loss and profit target around (after the entry fills) if you wanted.



        Or you can fully automate everything in the strategy and do the same thing without Atm Strategy methods.


        The startup behavior and whether a strategy resumes depends on how the script is written and which startup behavior option is selected.

        Chelsea B.NinjaTrader Customer Service

        Comment


          #5
          Hi Chelsea,

          Thanks for the additional information, I have a couple more questions:

          If the signals are defined on a daily bar, do I need a smaller time series (e.g. 1 minute) for the entries? Or can I use the OnPriceChange method on daily bars to check if an entry was triggered without adding a data series with a shorter interval?

          Do you have an example of looping through an instrument list to limit the maximum number of positions filled of the system? If I run one strategy on an instrument list (lets say the Nasdaq 100), and I have a maximum of 5 positions allowed across all stocks, and positions fill in MSFT, AAPL, GOOG, YHOO and XRAY (one per stock), how do I stop the strategy filling a sixth position on any of the remaining stocks in the instrument list?

          Thanks.

          Numbo.

          Comment


            #6
            Hello Numbo,

            This would depend on how you want your script to function.

            If you want to place orders after a daily bar closes, (and a new session has opened), then it would not be necessary to add a 1 minute series.

            If you are wanting to place orders intra-day before the day bar closes, then a secondary series with smaller granularity would be necessary.

            I can link an example of looping through instruments.


            However, if the strategy is the only strategy placing orders, and these instruments are added to the script, then you can check the Positions collection with the index of the BarsInProgress and find out at any time if the strategy placed a trade to that instrument.


            If you are trying to monitor the account outside of the strategy, you would need to use the Addon methods for this.

            Chelsea B.NinjaTrader Customer Service

            Comment


              #7
              Hi Chelsea,

              Thanks again for all your help. As the list of instruments changes every day, I need to use the looping code instead of hard coding the instruments.

              When trying to implement the code to loop through the instrument lists in NT8:
              Code:
              InstrumentList myList = NinjaTrader.Cbi.InstrumentList.InstrumentLists.First(list => list.Name == "FOREX");
              if (myList == null) return;
              foreach (Instrument instrument in myList.Instruments)
              {
              	Print(instrument.FullName);
              }
              I get the error message 'NinjaTrader.CBI.InstrumentList' does not contain a definition for 'InstrumentLists'. Does this code work in NT8? If so what could be the problem?

              Where do I place this code? Is it in the State == State.Configure section? Do I need to add a data series for each instrument (e.g. using a foreach statement)?

              Its not really clear to me how this would work. Does the strategy run on one instrument that it is applied to in the Strategy Grid and then using the foreach loop on the OnBarUpdate method loop through all other instruments in the instrument list looking for an entry signal?

              Another question, the settings in the Strategy Analyser window override the settings hard coded in the code. Is there a way to make the coded settings override the settings in the strategy analyser window?

              Thanks!

              Comment


                #8
                Hello Numbo,

                If you are adding instruments dynamically I would not suggest using the Strategy Analyzer with that script.


                There does appear to be changes to this unsupported code on the backend. Please try the following instead:
                Code:
                InstrumentList myList = NinjaTrader.Cbi.InstrumentList.DbGet("FOREX");
                if (myList == null)
                	return;
                
                foreach (Instrument instrument in myList.Instruments)
                {
                	Print(instrument.FullName);
                }
                Chelsea B.NinjaTrader Customer Service

                Comment


                  #9
                  Thanks, this works. And thanks for the reminder not to dynamically add the instrument data series using this unsupported code - noted, I will do it differently.

                  Numbo

                  Comment

                  Latest Posts

                  Collapse

                  Topics Statistics Last Post
                  Started by maybeimnotrader, Yesterday, 05:46 PM
                  2 responses
                  20 views
                  0 likes
                  Last Post maybeimnotrader  
                  Started by adeelshahzad, Today, 03:54 AM
                  5 responses
                  32 views
                  0 likes
                  Last Post NinjaTrader_BrandonH  
                  Started by stafe, 04-15-2024, 08:34 PM
                  7 responses
                  32 views
                  0 likes
                  Last Post NinjaTrader_ChelseaB  
                  Started by merzo, 06-25-2023, 02:19 AM
                  10 responses
                  823 views
                  1 like
                  Last Post NinjaTrader_ChristopherJ  
                  Started by frankthearm, Today, 09:08 AM
                  5 responses
                  22 views
                  0 likes
                  Last Post NinjaTrader_Clayton  
                  Working...
                  X