• If this is your first visit, you will have to register before you can post. To view messages, please scroll below and select the forum that you would like to visits. Questions? Be sure to check out the Forum FAQ.

Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

Alternative to OnStartup() for NT8

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

    Alternative to OnStartup() for NT8

    What is the most similar alternative to OnStartup(), that was used in NT7 ?

    Is it the protected override void OnStateChange() method when State == State.DataLoaded ?

    #2
    Yes, State.DataLoaded would be the equivalent in terms of timing. Both OnStateChange() + State.DataLoaded, and OnStartup(), fire right before the script begins processing historical data.

    Depending on what you are doing, you might even consider using State.Historical, which fires as soon as the script actually starts processing historical bars.
    Dave I.NinjaTrader Product Management

    Comment


      #3
      Thank you, clear now.

      Comment


        #4
        In NT7 I used OnStartUp to A) see if the user input Logging was true or not and then B) If true use streamwriter to create a log file entry of the various variables used. This worked well as this first create/append was for the CSV file's header/first row as later in OnBarUpdate each bar's data would get logged.

        In NT8 I've added:
        Code:
        else if (State == State.DataLoaded)
        {
            if (logging)
            {
                // Create Log File for the Current Instrument or add to the existing Log File for the Current Instrument //
                using (StreamWriter sw = File.AppendText(path + Instrument.MasterInstrument.Name + " - StrategyName.csv"))  
                {
                    sw.WriteLine("Label 1, Label 2, Label 3," + Variable1 + "," + Variable2 );
                }
            }
            // Create a Log Event in NinjaTrader's Log Tab //
            Log("StrategyName for " + Instrument.MasterInstrument.Name + " has started.", NinjaTrader.Cbi.LogLevel.Information);
        }
        However when compiling I get a lot of "The name "Variable1" does not exist in the current context"

        All strategy used variables begin at the top of the Strategy class:
        Code:
        public class StrategyName : Strategy
        {
            // Strategy Variables //
            private string Variable1 = "Default Example";
            private string Variable2 = "Default Example";
            etc.
        So why can't (State == State.DataLoaded) see these variables?
        Should they not be placed where they are then?

        Comment


          #5
          Hello antrux,

          Thank you for writing in.

          I don't see anything in the code you've provided that would be preventing those variables from being seen.

          Could you please provide your script (or a sample script) that demonstrates these compile errors so I may test on my end?
          Zachary G.NinjaTrader Customer Service

          Comment


            #6
            Code:
            #region Using declarations
            using System;
            using System.IO;
            using System.Collections.Generic;
            using System.ComponentModel;
            using System.ComponentModel.DataAnnotations;
            using System.Linq;
            using System.Text;
            using System.Threading.Tasks;
            using System.Windows;
            using System.Windows.Input;
            using System.Windows.Media;
            using System.Xml.Serialization;
            using NinjaTrader.Cbi;
            using NinjaTrader.Gui;
            using NinjaTrader.Gui.Chart;
            using NinjaTrader.Gui.SuperDom;
            using NinjaTrader.Gui.Tools;
            using NinjaTrader.Data;
            using NinjaTrader.NinjaScript;
            using NinjaTrader.Core.FloatingPoint;
            using NinjaTrader.NinjaScript.Indicators;
            using NinjaTrader.NinjaScript.DrawingTools;
            #endregion
            
            //This namespace holds Strategies in this folder and is required. Do not change it. 
            namespace NinjaTrader.NinjaScript.Strategies
            {
                public class StrategyName : Strategy
                {
                    // Strategy Global Variables //
                    private string userName = Environment.UserName;
                    private string path = "c:\\Users\\";
                    private string desktop = "\\Desktop\\Trade Log\\";
                    private string buyStatus1 = "---";
                    private string buyStatus2 = "---";
                    private string buyStatus3 = "---";
                    private string buyStatus4 = "---";
                    private string buyStatus5 = "---";
                    private string sellStatus1 = "---";
                    private string sellStatus2 = "---";
                    private string sellStatus3 = "---";
                    private string sellStatus4 = "---";
                    private double currentCash;
                    private double spendingCash;
                    private int sharesToBuy;
                    private int barsSincePurchase;
                    private double avgPrice = 0;
                    private int quantity = 0;
                    // Add Screen Plots //
                    private SMA SMA1;
                    private SMA SMA2;
                    private SMA SMA3;
                    
                    protected override void OnStateChange()
                    {
                        if (State == State.SetDefaults)
                        {
                            Description                            = @"Description";
                            Name                                = "StrategyName";
                            Calculate                            = Calculate.OnBarClose;
                            EntriesPerDirection                        = 1;
                            EntryHandling                            = EntryHandling.AllEntries;
                            IsExitOnSessionCloseStrategy                    = false;
                            ExitOnSessionCloseSeconds                    = 30;
                            IsFillLimitOnTouch                        = false;
                            MaximumBarsLookBack                        = MaximumBarsLookBack.TwoHundredFiftySix;
                            OrderFillResolution                        = OrderFillResolution.Standard;
                            Slippage                            = 0;
                            StartBehavior                            = StartBehavior.AdoptAccountPosition;
                            TimeInForce                            = TimeInForce.Gtc;
                            TraceOrders                            = true;
                            RealtimeErrorHandling                        = RealtimeErrorHandling.IgnoreAllErrors;
                            StopTargetHandling                        = StopTargetHandling.PerEntryExecution;
                            BarsRequiredToTrade                        = 200;
                            // Disable this property for performance gains in Strategy Analyzer optimizations
                            // See the Help Guide for additional information
                            IsInstantiatedOnEachOptimizationIteration            = true;
                            PercentPerTrade                            = 10;
                            PerTradeLimit                            = 1000;
                            PercentDrop                            = 5;
                            PercentIncrease                            = 3;
                            WaitPeriod                            = 7800;
                            Logging                                = true;
                            SlowSellCount                            = 4;
                            PerSharePriceLimit                        = 200;
                        }
                        else if (State == State.Configure)
                        {
                        }
                        else if (State == State.DataLoaded)
                        {
                            SMA1                                = SMA(4);
                            SMA1                                = SMA(6);
                            SMA1                                = SMA(100);
                            SMA1.Plots[0].Brush                        = new SolidColorBrush(Colors.Blue);
                            SMA2.Plots[0].Brush                        = new SolidColorBrush(Colors.LawnGreen);
                            SMA3.Plots[0].Brush                        = new SolidColorBrush(Colors.Crimson);
                            AddChartIndicator(SMA1);
                            AddChartIndicator(SMA2);
                            AddChartIndicator(SMA3);
                            if (logging)
                            {
                                // Create Log File for the Current Instrument or add to the existing Log File for the Current Instrument //
                                using (StreamWriter sw = File.AppendText(path + userName + desktop + Instrument.MasterInstrument.Name + " - StrategyName.csv"))  
                                {
                                    sw.WriteLine("Date Time,Price Movement,$ to Buy?,Above Price Limit?,Buy Status,Price Recovered?,Price Status," + percentIncrease + " Increase?,Sell Status,Bars Since Purchase,Current Close Price,Avg Buy Price,Shares,Current Cash,Spending Cash" + "," + "STRATEGY SETTINGS:" + "," + "Percent Per Trade: " + percentPerTrade + "," + "Per Trade $ Limit: " + perTradeLimit + "," + "Percent Drop: " + percentDrop + "," + "Percent Increase: " + percentIncrease + "," + "Slow Sell Wait Period: " + waitPeriod + "," + "Enable Logging: " + logging + "," + "Slow Sell Limit: " + slowSellCount + "," + "Per Share $ Limit: " + perSharePriceLimit);
                                }
                            }
                            // Create a Log Event in NinjaTrader's Log Tab //
                            Log("StrategyName for " + Instrument.MasterInstrument.Name + " has started.", NinjaTrader.Cbi.LogLevel.Information);
                        }
                    }
            
                    protected override void OnBarUpdate()
                    {
                    
                        
                        
                        
                        //Still Working            
                        
                        
                        
                    }
            
                    #region Properties
                    [Range(1, double.MaxValue)]
                    [NinjaScriptProperty]
                    [Display(ResourceType = typeof(Custom.Resource), Name="PercentPerTrade", Description="Description", Order=1, GroupName="NinjaScriptStrategyParameters")]
                    public double PercentPerTrade
                    { get; set; }
            
                    [Range(1, double.MaxValue)]
                    [NinjaScriptProperty]
                    [Display(ResourceType = typeof(Custom.Resource), Name="PerTradeLimit", Description="Description", Order=2, GroupName="NinjaScriptStrategyParameters")]
                    public double PerTradeLimit
                    { get; set; }
            
                    [Range(1, double.MaxValue)]
                    [NinjaScriptProperty]
                    [Display(ResourceType = typeof(Custom.Resource), Name="PercentDrop", Description="Description", Order=3, GroupName="NinjaScriptStrategyParameters")]
                    public double PercentDrop
                    { get; set; }
            
                    [Range(1, double.MaxValue)]
                    [NinjaScriptProperty]
                    [Display(ResourceType = typeof(Custom.Resource), Name="PercentIncrease", Description="Description", Order=4, GroupName="NinjaScriptStrategyParameters")]
                    public double PercentIncrease
                    { get; set; }
            
                    [Range(5, int.MaxValue)]
                    [NinjaScriptProperty]
                    [Display(ResourceType = typeof(Custom.Resource), Name="WaitPeriod", Description="Description", Order=5, GroupName="NinjaScriptStrategyParameters")]
                    public int WaitPeriod
                    { get; set; }
            
                    [NinjaScriptProperty]
                    [Display(ResourceType = typeof(Custom.Resource), Name="Logging", Description="Description", Order=6, GroupName="NinjaScriptStrategyParameters")]
                    public bool Logging
                    { get; set; }
            
                    [Range(0, int.MaxValue)]
                    [NinjaScriptProperty]
                    [Display(ResourceType = typeof(Custom.Resource), Name="SlowSellCount", Description="Description", Order=7, GroupName="NinjaScriptStrategyParameters")]
                    public int SlowSellCount
                    { get; set; }
            
                    [Range(1, double.MaxValue)]
                    [NinjaScriptProperty]
                    [Display(ResourceType = typeof(Custom.Resource), Name="PerSharePriceLimit", Description="Description", Order=8, GroupName="NinjaScriptStrategyParameters")]
                    public double PerSharePriceLimit
                    { get; set; }
                    #endregion
            
                }
            }

            Comment


              #7
              Hello antrux,

              Please note that C# is case-sensitive.

              I see that you are declaring some variables as uppercase (example public bool Logging), but then trying to access them from within your script with a lowercase letter (logging).

              Correct the casing of your variables and the script will be able to compile.
              Last edited by NinjaTrader_ZacharyG; 07-22-2016, 02:56 PM.
              Zachary G.NinjaTrader Customer Service

              Comment


                #8
                Just damn. You are da man Zach. I don't care what everyone else says.

                Thank you.

                Comment


                  #9
                  I see how that happened now. The Wizard of NT7 accepted Uppercase and 'converted' to lower on insertion but NT8's Wizard allows them to stay capital. Seen in bold below.

                  NT7 Wizard Generated Example:
                  #region Properties
                  [Description("")]
                  [GridCategory("Parameters")]
                  public int MyInput
                  {
                  get { return myInput; }
                  set { myInput = Math.Max(1, value); }
                  }
                  #endregion

                  NT8 Wizard Generated Example:
                  #region Properties
                  [Range(1, int.MaxValue)]
                  [NinjaScriptProperty]
                  [Display(ResourceType = typeof(Custom.Resource), Name="MyInput", Order=1, GroupName="NinjaScriptStrategyParameters")]
                  public int MyInput
                  { get; set; }
                  #endregion

                  Comment


                    #10
                    Hello antrux,

                    NinjaTrader 7 creates a public variable and a private variable when you're creating user defined inputs in the wizard. The private variable is lowercased and the public uppercased. These private variables are located within the Variables region.

                    NinjaTrader 8, instead, creates only a public variable with just a get; set;

                    get and set are called accessors. I would highly suggest taking a look at this link on MSDN for more information about Properties in C#: https://msdn.microsoft.com/en-us/library/w86s7x04.aspx

                    So rather than:
                    Code:
                    private int myVariable;
                    public MyVariable
                    {
                         get { return myVariable; }
                         set { variable = value; }
                    }
                    It is shortened to:
                    Code:
                    public MyVariable
                    { get; set; }
                    The private variable is missing completely (but the concept as done in NT7 still exists in the background).
                    Last edited by NinjaTrader_ZacharyG; 07-22-2016, 03:22 PM.
                    Zachary G.NinjaTrader Customer Service

                    Comment


                      #11
                      Well thanks for getting all technical on me. I was actually trying to avoid reading that page but now I've done it. Not sure if I 100% understand it but I can at least make use of it now. I'm probably gonna have to re-read that page again in ten minutes though. Thanks.

                      You can forget getting that basket of chocolates that I send every Christmas now.

                      Comment

                      Latest Posts

                      Collapse

                      Topics Statistics Last Post
                      Started by FMtrader, 03-15-2019, 02:30 AM
                      6 responses
                      31 views
                      0 likes
                      Last Post James108  
                      Started by timko, Today, 08:18 AM
                      0 responses
                      0 views
                      0 likes
                      Last Post timko
                      by timko
                       
                      Started by victorsmith, Today, 06:00 AM
                      0 responses
                      3 views
                      0 likes
                      Last Post victorsmith  
                      Started by sohailashraf, Yesterday, 10:18 PM
                      0 responses
                      6 views
                      0 likes
                      Last Post sohailashraf  
                      Started by jjnc2006, Yesterday, 07:36 PM
                      0 responses
                      15 views
                      0 likes
                      Last Post jjnc2006  
                      Working...
                      X