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

Can I use AccountItem properties when I backtest huge Stock Instrument lists?

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

    Can I use AccountItem properties when I backtest huge Stock Instrument lists?

    Hi there,

    I do a lot of backtesting on instrument lists such as the S&P500 or Russell 1000.

    At the moment I use fixed stop loss values (e.g. 1000$ risk per trade).

    Now I want to take the next step and calculate the SL dynamically based on the account size (e.g. take 1% risk per trade based on AccountItem.NetLiquidation).

    As far as I understand, Ninja Trader runs the backtest in parallel. Is there a way to run the backtest sequentially in terms of execution date of each trade so that my strategy knows my NetLiquidation value when entering a new trade?​

    E.g.
    Date NetLiquidation Risk in $
    Jan 2000 100.000 1000
    ...
    ...
    March 2002 140.000 1400
    Thanks,
    Lukas

    #2
    Hello Lukas,

    Thank you for your post.

    In order to get AccountItem information, such as AccountItem.NetLiquidation, you may use the OnAccountItemUpdate() method in your strategy:


    When running a backtest in the Strategy Analyzer, you would see these values updated sequentially based on each trade execution and not in parallel. You may verify this by using Print statements throughout your script and checking the NinjaScript Output window.

    When it comes to accessing AccountItem information, it is important to keep in mind which values are supported by your provider. For a table of providers and which items are supported, please see the "Account Values Supported by Provider" section at the following link:


    Please let me know if I may be of further assistance.
    Emily C.NinjaTrader Customer Service

    Comment


      #3
      Hi Emily,

      thank your for your quick reply.

      However, I'm struggling to add an account to my strategies.

      When I execute my strategies without an account, just with

      Code:
      EnterLongStopMarket(0, true, amountStocks, stopEntryPrice, "Long");                    
      SetStopLoss(CalculationMode.Price, slPrice );​
      it works fine.

      Now I have added an account like so:

      Code:
      State == State.SetDefaults
      
      lock (Account.All)
      myAccount = Account.All.FirstOrDefault(a => a.Name == "SimAccount1");​

      Code:
      OnBarUpdate()
      
      Instrument myInstrument = Instrument.GetInstrument(Bars.Instrument.MasterInstrument.Name);
      
      EntryOrder = myAccount.CreateOrder(myInstrument, OrderAction.Buy, OrderType.StopMarket, OrderEntry.Automated, TimeInForce.Gtc, amountStocks, 0, stopEntryPrice, null, "Long", Core.Globals.MaxDate, null);
      
      myAccount.Submit(new[] { EntryOrder });​


      But it does not work, I'm getting back this error message:

      "SimAccount1, There is no market data available to drive the simulation engine. affected Order: Buy 135 StopMarket @ 4,38"

      Comment


        #4
        Hello Lukas,

        Thank you for your reply.

        Fortunately, when working with a NinjaScript strategy, OnAccountItemUpdate() will already be subscribed to the account on which the strategy is running. You do not need to manually set the account you would like the updates from; that would only be applicable from scripts that are not strategies, such as an AddOn or Indicator script.

        When you start a new strategy from the Strategy wizard in the editor, this is an additional method that is available as shown in the screenshots below:If your strategy has already been created, you may manually add the method with the syntax shown in the help guide:
        Code:
        protected override void OnAccountItemUpdate(Account account, AccountItem accountItem, double value)
        {
        
        }
        You could try adding a print statement inside of the method as shown in the help guide here to get a better idea of how the method is called as items are updated:
        Code:
        protected override void OnAccountItemUpdate(Account account, AccountItem accountItem, double value)
        {
          Print(string.Format("{0} {1} {2}", account.Name, accountItem, value));
        
          // output:
          // Sim101 BuyingPower 103962.5
          // Sim101 CashValue 103962.5
          // Sim101 GrossRealizedProfitLoss 3962.5
          // Sim101 RealizedProfitLoss 3962.5
        }​
        To get Net Liquidation specifically, it could look like the following:
        Code:
        protected override void OnAccountItemUpdate(Account account, AccountItem accountItem, double value)
        {
        if (accountItem == AccountItem.NetLiquidation)
        Print(String.Format("Acct: {0} NetLiquidation: {1}", account.Name, value));
        }​
        I hope this helps to clarify. Please let me know if you have any additional questions or concerns.
        Emily C.NinjaTrader Customer Service

        Comment


          #5
          Hi Emily,

          this was exactly what I did before I tried the approach that I have described above.

          I don't know what I'm doing wrong, but the NinjaScript Output remains empty. Apparently the OnAccountItemUpdate method is never called when I'm running the backtest.

          This is what I have implemented into my strategie at the moment:

          Code:
          protected override void OnAccountItemUpdate(Account account, AccountItem accountItem, double value)
                  {
                        Print("OnAccountItemUpdate");
                      Print(string.Format("{0} {1} {2}", account.Name, accountItem, value));
          
                    // output:
                    // Sim101 BuyingPower 103962.5
                    // Sim101 CashValue 103962.5
                    // Sim101 GrossRealizedProfitLoss 3962.5
                    // Sim101 RealizedProfitLoss 3962.5
                  }​

          Comment


            #6
            Hello lakman184,

            Thank you for your reply.

            Are you still getting errors in the Log, such as the one you previously mentioned?
            • "SimAccount1, There is no market data available to drive the simulation engine. affected Order: Buy 135 StopMarket @ 4,38"
            This error means that either your connection is not enabled for real-time data for the instrument the order was submitted to, or the order is being placed to an instrument with an expired contract.

            So I may assist you more accurately, please answer all of the following questions:
            • What version of NinjaTrader are you using? Please provide the entire version number. This can be found under Help -> About (Example: 8.?.?.?)
            • Who are you connected to? This is displayed in green in the lower left corner of the Control Center window.
            • Are you connected to your data feed provider when running this test?
            • What instrument(s) (and expiry if applicable) have you selected?
            • What Data Series Type have you selected? Example: Tick, Minute, Day
            • What From and To date is selected?
            • Do you receive an error on the screen? Are there errors on the Log tab of the Control Center? If so, what do these errors report?
            ​I appreciate your patience and look forward to your reply.
            Emily C.NinjaTrader Customer Service

            Comment


              #7
              Hi Emily,

              basically the backtests are running fine and I don't receive any error messages, except the issue that I don't get back any account item related information.

              I'm backtesting on Stock Instrument lists, timeframes are Daily, Weekly, Monthly. I don't have any active connection to a data provider during backtest, since I use historical EoD data from Kinetick.

              I use NT version 8.0.27.1 64-bit.

              To clarify once again: I have no problem with the backtest itself.

              My point was: How can I do the backtests including a simulated account so that I can set the stop loss for each trade relative to the net liquidation value of the sim account.

              I start the backtests from New -> Strategy Analyzer.

              When I implement the OnAccountItemUpdate method as you suggested, it doesn't seem to be called during the backtest. At least the NinjaScript output window remains empty, although the method should write something into the output window with every account update.

              In the post above you can see my current implementation of OnAccountItemUpdate.

              And this is my output windows after running a backtest over 500 Stock symbols from 2005 to 2021:

              Click image for larger version

Name:	Screenshot_1.jpg
Views:	154
Size:	19.5 KB
ID:	1243628

              So the question is still: How can I include a SimAccount in my backtest, so that I have a simulated NetLiquidation value available during testing, which I can use to calculate my stop loss.

              Correct me when I'm wrong, but don't I need to add some sort of account object to my strategy? I mean, how should the code/strategy/backtest know which sim account to use and what is the current cash value, net liquidation etc?

              Comment


                #8
                Hello Lukas,

                Thank you for your patience.

                I apologize for any inconvenience; I provided some incorrect information. OnAccountItemUpdate() is only called in real-time and is not called during a backtest, hence the reason you are not seeing any output. One workaround to test your strategy historically would be to use the Playback connection. That said, the Playback connection requires downloaded market replay data or historical tick data in order to function:


                Market Replay data is provided in limited amounts for the most common instruments, so it is likely not available for the period of time you desire or for the stocks you are using. This means you would need to download or import historical tick data from a data provider in order to utilize the historical data playback option:Your strategy would be able to call OnAccountItemUpdate() in real-time so that it can access the values like cash value, net liquidation, etc. though backtesting your strategy does present some challenges due to account events being restricted to real-time only.

                Again, I apologize for the inconvenience due to the incorrect information I provided. Please don't hesitate to reach out with any additional questions or concerns.
                Emily C.NinjaTrader Customer Service

                Comment

                Latest Posts

                Collapse

                Topics Statistics Last Post
                Started by wzgy0920, 04-20-2024, 06:09 PM
                2 responses
                26 views
                0 likes
                Last Post wzgy0920  
                Started by wzgy0920, 02-22-2024, 01:11 AM
                5 responses
                32 views
                0 likes
                Last Post wzgy0920  
                Started by wzgy0920, Yesterday, 09:53 PM
                2 responses
                49 views
                0 likes
                Last Post wzgy0920  
                Started by Kensonprib, 04-28-2021, 10:11 AM
                5 responses
                192 views
                0 likes
                Last Post Hasadafa  
                Started by GussJ, 03-04-2020, 03:11 PM
                11 responses
                3,234 views
                0 likes
                Last Post xiinteractive  
                Working...
                X