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

[CODE] - State.Configure or OnBarUpdate placement?

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

    [CODE] - State.Configure or OnBarUpdate placement?

    Hi there,

    I currently have this code setting variables for performance metrics. They're supposed to be defined whenever a trade completes:

    Code:
    private void calculate_Performance()
    					{
    						profit_GrossProfit = Math.Round(SystemPerformance.AllTrades.TradesPerformance.GrossProfit,2);
    						profit_GrossLoss = Math.Round(SystemPerformance.AllTrades.TradesPerformance.GrossLoss,2);
    						profit_Commissions = Math.Round(SystemPerformance.AllTrades.TradesPerformance.Commission,2);
    						profit_Totals = Math.Round((profit_GrossProfit + profit_GrossLoss) - profit_Commissions,2);
    					}
    Would State.Configure be the proper place for this, or would it a better match for OnBarUpdate?

    I also have one for risk tolerance that's currently sitting in State.Configure, but again, thinking it should be considered for OnBarUpdate instead, based on what the Help Guide outlines as being candidates for State.Configure:

    Code:
    private void calculate_RiskTolerance()
    					{
    						profit_targetLevel = Math.Round(GetAccountValue(AccountItem.CashValue) / 100,0);		//  Calculate our target level, based on available cash
    						profit_failureLevel = profit_targetLevel * -1;											//  Define the failure level based on reverse of the former
    						
    						if (profit_Totals >= profit_targetLevel)												//  If we are above our target level for profit,
    						{	profit_riskLevel = 2;	}															//  our risk tolerance is high.
    					
    						else if (profit_Totals >= 0 && profit_Totals < profit_targetLevel)						//  If we haven't cleared our target level,
    						{	profit_riskLevel = 1;	}															//  our risk tolerance is normal.
    				
    						else if (profit_Totals < 0 && profit_Totals > profit_failureLevel)						//  If we are underperforming or close to shutting down,
    						{	profit_riskLevel = 0;	}															//  our risk tolerance is low.  
    					
    					}
    Please let me know when you have a moment.

    #2
    Hello Spiderbird,

    Thanks for writing in.

    State.Configure is better used for declaring custom resources and adding additional data series.

    OnBarUpdate() will iterate for each bar close, tick, or price change depending on the Calculate property.

    I would advise to place the logic in OnExecutionUpdate() with a check for the signal name of your exit order method. This way you can calculate your performance metrics on the close of a trade. Order objects could also be used instead of finding the Signal Name for the exit.

    We have an example for using Order objects along with OnOrderUpdate() and OnExecutionUpdate() on our forums. I will provide a link along with publicly available documentation on OnExecutionUpdate() and Order objects.

    SampleOnOrderUpdate - https://ninjatrader.com/support/foru...ead.php?t=7499

    Order objects - http://www.ninjatrader.com/support/h...lightsub=Order

    OnExecutionUpdate() - http://www.ninjatrader.com/support/h...xecutionUpdate

    You may also reference the intention of each NinjaScript State in the OnStateChange() documentation - https://ninjatrader.com/support/help...tatechange.htm

    Please let me know if I may be of further assistance.
    JimNinjaTrader Customer Service

    Comment


      #3
      Verifying

      Just to be sure I understand in a basic sense, you're saying the code should probably exist in OnBarUpdate, slotted into the following example based on the OnExecutionUpdate help link you posted:

      Code:
      protected override void OnExecutionUpdate(Execution execution, string executionId, double price, int quantity, MarketPosition marketPosition, string orderId, DateTime time)
      {
        // Remember to check the underlying Order object for null before trying to access its properties
        if (execution.Order != null && execution.Order.OrderState == OrderState.Filled)
            Print(execution.ToString());
      }
      I'm assuming that every parameter shown above in OnExecutionUpdate doesn't need to be explicit. It just has to be defined if you're looking to see if a particular order was filled before doing risk/profit calculations. Is that right?

      Thanks in advance!

      Comment


        #4
        While I'm asking...

        Also, I'm a complete moron for not getting it.. but I have no idea where to initialize variables in NT8.

        With NT7, I just put all bool/double/string etc. variables in OnBarUpdate, and figured they were good to go. Since initializing variables don't seem to belong in either State.SetDefaults or State.Configure, does the following code typically go into something like State.DataLoaded? Does it depend on the nature of what you're attempting to do?

        Code:
        				double stopPrice;			//  The defined price where orders should execute.
        				string stopPrice_string = "";	//  The associated string that explains how stopPrice was achieved.
        				
        				bool
        				stopPrice_Defined,								
        				stopPrice_Partial;
        
        				private Order longOrder = null;
        				private Order shortOrder = null;
        Thanks in advance for any answer you can give.

        - Spider

        Comment


          #5
          Hello Spiderbird,

          My recommendation was to use OnExecutionUpdate() for calculating your Trade performance instead of in OnBarUpdate(), as this would method would fire after the execution of an order, where you can easily see when an exit order closes a position.

          Declaring variables in a method like OnBarUpdate() or within a branch such as a condition in OnStateChange() would make them local to that section of code. If you want to add variables that will retain their value outside of that one iteration, you should declare the variable outside of the method you are using. For NinjaScripts, you would make a private or public member variable in the NinjaScript class.

          For general questions on using C# I would recommend to reference the Programming Concepts section of the NinjaTrader 7 help guide or reference external resources.

          NT7 Programming Concepts - https://ninjatrader.com/support/help...g_concepts.htm

          You would not need to use every parameter in OnExecutionUpdate() to detect when your exit occurs. You would only need to use information from the Order object within the Execution object to match the Order object you assigned your exit order to, or use the Signal Name from the Exit Order to detect when the trade is closed.

          Please see the "Finding the executions of a particular Order object" example in the OnExecutionUpdate() page of the help guide for an example on detecting the Signal name in OnExecutionUpdate(). The code provided is for Entry methods, but would be used similarly for Exit methods. You can also reference the SetProfitTarget() and SetStopLoss() documentation for the signal names for those methods.

          SampleOnOrderUpdate will provide a good example for using Order objects throughout your strategy should you wish to use them.

          SetProfitTarget() - https://ninjatrader.com/support/help...ofittarget.htm

          SetStopLoss() - https://ninjatrader.com/support/help...etstoploss.htm

          If you have any additional questions, please let me know.
          JimNinjaTrader Customer Service

          Comment


            #6
            Fantastic! Just one clarification...

            Hi Jim,

            I really appreciate the involved reply. Understood about the order objects and when to call them after execution. Also very much appreciate the link to NT Programming Concepts. I didn't know that existed.

            For this particular paragraph, I have one final clarification to ask:

            Originally posted by NinjaTrader_Jim View Post
            Declaring variables in a method like OnBarUpdate() or within a branch such as a condition in OnStateChange() would make them local to that section of code. If you want to add variables that will retain their value outside of that one iteration, you should declare the variable outside of the method you are using. For NinjaScripts, you would make a private or public member variable in the NinjaScript class.
            I understood everything you typed above. For the underlined part, where specifically outside the method are you referring to?

            Like the example I have, I have about 800+ lines of code that's just nothing but initializing variables (bool, double, int, string defaults, sbyte, byte, etc.) that I normally would use and reference during OnBarUpdates. I know it depends on the nature of how the variable is going to be used on context. I still need help understanding:
            1. Do these types of variables get initialized outside of the OnStateChange() area if the variable names stay constant, and just their values change as new data comes in?
            2. If the need to be in OnStateChange(), which particular category (SetDefaults, Configure, Active, DataLoaded, Historical, RealTime, etc.) do they generally go to optimize processing and runtime efficiency for NT? I'm leaning towards DataLoaded, but again, I'm not sure if context and purpose of the variable makes a difference here.


            Let me know when you have a moment, and thanks again for the detailed answers from before.

            Comment


              #7
              Hello Spiderbird,

              I understood everything you typed above. For the underlined part, where specifically outside the method are you referring to?
              Private and public member variables (of a class) would be declared inside the class.

              Code:
              public class MyCustomStrategy : Strategy
              {
              	private int myPrivateInt;
              	public int myPublicInt;
              1. Do these types of variables get initialized outside of the OnStateChange() area if the variable names stay constant, and just their values change as new data comes in?
              2. If the need to be in OnStateChange(), which particular category (SetDefaults, Configure, Active, DataLoaded, Historical, RealTime, etc.) do they generally go to optimize processing and runtime efficiency for NT? I'm leaning towards DataLoaded, but again, I'm not sure if context and purpose of the variable makes a difference here.
              I'm not really sure how to answer your first question. If you declare a variable within a class, you can use it throughout the class and it will retain its value. If you declare it within a method that variable will only exist for when that method is called.

              The OnStateChange() documentation and NinjaScript LifeCycle explains the intended purpose for each State and how they iterate. State.DataLoaded is a good place to reinitialize variables so the strategy can be used in the Strategy Analyzer's Optimizer with IsInstantiatedOnEachOptimizationIteration. How you write the strategy and optimize it will be very subjective to your own implementation.

              I would recommend to use the Strategy Builder tool to create some simple strategies with user defined variables and use "View Code" to observe the how the Builder creates the NinjaScript syntax.

              I'll include publicly available documentation to the items discussed.

              Strategy Builder 301 - https://www.youtube.com/watch?v=HCyt90GAs9k

              OnStateChange() - https://ninjatrader.com/support/help...tatechange.htm

              NinjaScript LifeCycle - https://ninjatrader.com/support/help...fecycle_of.htm

              IsInstantiatedOnEachOptimizationIteration - https://ninjatrader.com/support/help...niteration.htm

              Please let me know if I may be of further assistance.
              JimNinjaTrader Customer Service

              Comment


                #8
                Okay, need to get specific here...

                Hi Jim,

                Thanks for posting all of that. I was away for the holidays and am now coming back to the thread after reviewing all your links and references. FYI, the 401 video on YouTube came at the problem I'm having a little better, since I don't use the Strategy Builder for anything beyond the NT8 code framework.

                Got and understood the reference to class variables. I'm all set with that.

                The OnStateChange() documentation is where I'm struggling. Not in the broader concepts it states, but the specific examples of what goes there.

                For example, here's what's at the bottom of the OnStateChange() page for reference:

                Code:
                else if (State == State.Configure)
                  { 
                    // Adds a 5-minute Bars object to the strategy and is automatically assigned
                    // a Bars object index of 1 since the primary data the strategy is run against
                    // set by the UI takes the index of 0.       
                    AddDataSeries("AAPL", BarsPeriodType.Minute, 5);     
                  }
                So yeah, got it. DataSeries are idea for going there. It's also stated in the "State.Configure' "This state is where you should..." table on this page:



                Here's what's missing... examples of what code is placed in the other states, irregardless of what approach is taken by someone using the strategy builder, or working directly in the NinjaScript Editor (like me).

                I've even put in a structured setup in my editor to house the code that goes there. I even put a bit of code I *think* goes in the state.historical section, but I don't really know:.

                Code:
                else if (State == State.Configure)
                			//  Configure is called after a user adds an object to the applied list of objects.
                			// • Add additional data series via AddDataSeries()
                			// • Declare custom resources
                			{}
                			
                			else if (State == State.DataLoaded)	
                			// 	-> DataLoaded is called only once after all data series have been loaded.	
                			// • Use for logic that needs to access data related objects like Bars, Instruments, BarsPeriod, TradingHours
                			// • Notify that all data series have been loaded
                			// • Initialize any class level variables (including custom Series<T> objects)
                				
                			{
                				#region Section 1 - Communications and Reports
                				
                			//  Send SMS to update performance of trading day (done around 10:30AM, Noon, 1:30PM and 3:00PM CDT)
                				if (ToTime(Time[0]) > 103000 && ToTime(Time[0]) < 103200 && marketCheck == 0
                					|| ToTime(Time[0]) > 120000 && ToTime(Time[0]) < 120200 && marketCheck == 1
                					|| ToTime(Time[0]) > 133000 && ToTime(Time[0]) < 133200 && marketCheck == 2
                					|| ToTime(Time[0]) >= 145800 && ToTime(Time[0]) < 150000 && marketCheck == 3)
                					
                				{	marketCheck++;
                					//  Insert e-mail code here (from below)
                				#endregion
                				
                			}
                				
                			else if (State == State.Historical)
                			//  -> Historical is called once the object begins to process historical data. This state is called once when running an object in real-time. 
                			{
                				
                				
                			}
                
                			
                			else if (State == State.Realtime)
                			//  Realtime is called once when the object begins to process realtime data.
                			{
                				
                			}
                So this is my ask... I'd really just like to see *one* example of some hand-written or Strategy generated code that would ideally live there. That way, I can figure out if everything goes in just state.realtime or not.

                Let me know if that makes sense.

                - Spider

                Comment


                  #9
                  Hello Spiderbird,

                  Thanks for your reply.

                  If you are looking for code examples for using OnStateChange() efficiently, I would suggest to take a look at the Best Practices page of the help guide.

                  My previous suggestion was to outline an idea in the Strategy Builder and to observe the resulting code to see how it would be implemented by hand.

                  So this is my ask... I'd really just like to see *one* example of some hand-written or Strategy generated code that would ideally live there. That way, I can figure out if everything goes in just state.realtime or not.
                  Getting down to what you are asking exactly, you would like to know a specific instance when State.Configure would be used? This would be used for either declaring custom resources or adding additional data series. For example, adding a timer. It is also valid to use State.DataLoaded for custom resource generation, and State.Configure does not always need to be used.

                  From SampleCustomEvents:
                  Code:
                  if (State == State.Configure)
                  {
                  	// Initiate our Timer object with an interval of 1000ms (1 second)
                  	myTimer.Tick += new EventHandler(TimerEventProcessor);
                  	myTimer.Interval = 1000;
                  	myTimer.Start();
                  }
                  if (State == State.Terminated)
                  {
                  	myTimer.Dispose();
                  }
                  SampleCustomEvents - https://ninjatrader.com/support/foru...ead.php?t=3478

                  I've included a link to the State Resource Management Best Practices section of the help guide to provide further direction.

                  State Resource Management - https://ninjatrader.com/support/help...urceManagement

                  If this does not provide further direction, could you describe what you are trying to accomplish exactly so we can provide a clearer answer?
                  JimNinjaTrader Customer Service

                  Comment


                    #10
                    Hi Jim,

                    Thanks for those links. The State Resource Management page did the trick, especially the "Resetting class level variables for Strategy Analyzer Optimization" and "Setting up resources that rely on market data" section examples. I can start loading up those sections appropriately and am good to go.

                    For reference, your previous link on SampleCustomEvents (https://ninjatrader.com/support/foru...ead.php?t=3478) contains incorrect import information for NT8. It states:

                    mport instructions:
                    NinjaTrader 8
                    1. Download the file contained in this thread to your PC desktop
                    2. From the Control Center window, select the menu Tools > Import > NinjaScript
                    3. Select the downloaded file
                    #2 above is not available in the Control Center for NT8. In fact, the interface only allows you to import indicators, and not older strategies from what I can tell. You have to cut/paste old code from NT7 to NT8 manually to make that work (like I did).

                    That should be corrected, and I'd suggest a better way of allowing folks to view code on custom indicators rather than forcing the compilation of them... especially if you're working on a script with errors that would prevent you from importing it in the first place.

                    Thanks in advance for your time!

                    Comment


                      #11
                      Hello Spiderbird,

                      The menu item is there. I've attached a screenshot showing the menu item the instructions refer to.

                      The option will allow you to import any NinjaTrader 8 AddOn, Strategy, Indicator, or any other type of NinjaScript found in the NinjaScript Editor.

                      NinjaTrader 8 NinjaScripts have many differences compared to older NinjaTrader 7 NinjaScripts and cannot be imported directly. The programmer will have to go over the code breaking changes to port the script to NinjaTrader 8.

                      Code Breaking changes are documented here - https://ninjatrader.com/support/help...ng_changes.htm

                      Also with importing and exporting, we advise to export NinjaScripts from the Control Center so they are always distributed in a compile-able state. You can always view the .cs file from the exported zip file in a text editor to view code before trying to import it into the platform.

                      If there are any other items that you would like clarification on, please don't hesitate to write back.
                      Attached Files
                      JimNinjaTrader Customer Service

                      Comment

                      Latest Posts

                      Collapse

                      Topics Statistics Last Post
                      Started by GussJ, 03-04-2020, 03:11 PM
                      16 responses
                      3,279 views
                      0 likes
                      Last Post Leafcutter  
                      Started by WHICKED, Today, 12:45 PM
                      2 responses
                      19 views
                      0 likes
                      Last Post WHICKED
                      by WHICKED
                       
                      Started by Tim-c, Today, 02:10 PM
                      1 response
                      9 views
                      0 likes
                      Last Post NinjaTrader_ChelseaB  
                      Started by Taddypole, Today, 02:47 PM
                      0 responses
                      5 views
                      0 likes
                      Last Post Taddypole  
                      Started by chbruno, 04-24-2024, 04:10 PM
                      4 responses
                      52 views
                      0 likes
                      Last Post chbruno
                      by chbruno
                       
                      Working...
                      X