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

Help on Ninjascript

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

    Help on Ninjascript

    Q1
    Code:
    public static bool IsTimeTrue(double starttime, double endtime) 
            {
                if (TimeSpan.Compare(DateTime.Now.TimeOfDay, TimeSpan.FromHours(starttime)) < 0)
                {
                    return false;
                }
                else
                    if (TimeSpan.Compare(DateTime.Now.TimeOfDay, TimeSpan.FromHours(endtime)) > 0)
                        return false;
                    else
                        return true;				
                Print("Mission accomplished");
            }
    The Print() ,is returning an error
    An object reference is required for non static field, method or property "ninjatrader.Strategy.StrategyBase.Print(Strin g)"

    its working fine if i use it inside of OnMarketUpdate(), or OnBarUpdate(),
    may i know whats causing this to come up in a custom method.

    If its non static why am i able to use it in these functions at all, without an object reference
    Last edited by nemesis45; 04-13-2014, 11:47 AM.

    #2
    Q.2
    *NT** Error on getting/setting property 'Buyprint' for strategy 'GetBuySellPrint/d8a88c836b404d7fa3a25c3e92fd1d09': Object of type 'NinjaTrader.Strategy.Prints' cannot be converted to type 'NinjaTrader.Strategy.Prints'.
    **NT** Error on getting/setting property 'Sellprint' for strategy 'GetBuySellPrint/d8a88c836b404d7fa3a25c3e92fd1d09': Object of type 'NinjaTrader.Strategy.Prints' cannot be converted to type 'NinjaTrader.Strategy.Prints'.
    **NT** Error on getting/setting property 'Printslist' for strategy 'GetBuySellPrint/d8a88c836b404d7fa3a25c3e92fd1d09': Object of type 'System.Collections.Generic.LinkedList`1[NinjaTrader.Strategy.Prints]' cannot be converted to type 'System.Collections.Generic.LinkedList`1[NinjaTrader.Strategy.Prints]'.
    **NT** Error on getting/setting property 'Lastprint' for strategy 'GetBuySellPrint/d8a88c836b404d7fa3a25c3e92fd1d09': Object of type 'NinjaTrader.Strategy.Prints' cannot be converted to type 'NinjaTrader.Strategy.Prints'.
    **NT** Error on getting/setting property 'Currentprint' for strategy 'GetBuySellPrint/d8a88c836b404d7fa3a25c3e92fd1d09': Object of type 'NinjaTrader.Strategy.Prints' cannot be converted to type 'NinjaTrader.Strategy.Prints'.

    I have defined my custom class Prints.
    Now, when i declare a Prints object i am getting this error message.

    private static Prints buyprint= new Prints();
    private static Prints sellprint= new Prints();
    private static LinkedList< Prints> printslist = new LinkedList< Prints>();
    private static Prints lastprint = new Prints();
    private static Prints currentprint = new Prints();

    I have declared these in the variables region

    The code is working fine in visual studio. Please help.
    Last edited by nemesis45; 04-12-2014, 11:22 AM.

    Comment


      #3
      Q3

      Q3.

      So i used closes[][], to get the historical 15 min data from OnStartup()

      there are two bars objects i have added, besides a primary tick data(clalculateonbarclose = false)

      so i want to know closes[2][0], will refer to the close of the last 15 min candle?
      or does it refer to the current price? i am guessing right now it refers to close of the last 15 min candle.

      if so, what will be the timestamp at closes[2][0] , is it somehow synced to my computer's clock? i.e if time is 6:35 pm , i get the close of the candle running from 6:15 to 6:30 ?
      or price at 6:30. at least i wish to get the time denominations as in every 15 mins.
      even if strategy starts at 6:35 pm , i want closes[2][0] to refer to price at 6:30 pm




      Also, i want to know if it is possible to use closes[][] in a custom method , so far i have not been able to use it so. Please give me an example of how to do this

      Comment


        #4
        Hello Nemesis45,

        Thank you for your posts.

        You would need to assign an instance of the indicator's class to a variable and then call that variable.Print();. For example:
        Code:
        		public static bool IsTimeTrue(double starttime, double endtime) 
                {
        			var instance =  new MyTestIndicator(); // use the name of your strategy or indicator where 'MyTestIndicator' is listed.
                    if (TimeSpan.Compare(DateTime.Now.TimeOfDay, TimeSpan.FromHours(starttime)) < 0)
                    {
                        return false;
                    }
                    else
                        if (TimeSpan.Compare(DateTime.Now.TimeOfDay, TimeSpan.FromHours(endtime)) > 0)
                            return false;
                        else
                            return true;
                    instance.Print("Mission accomplished");
                }
        For your custom class you would not need to define them as new Prints() or new LinkedList<Prints>() as they are already defined as this by public static Prints or public static LinkedList<Prints>.

        With CalculateOnBarClose = False, the values of Close[2][0] would be the most recent price, the last close would be Closes[2][1]. The TimeStamp being your PC time or the Data Feeds time depends on the provider this information is provided at the following link: http://www.ninjatrader.com/support/h...rical_data.htm

        To access Closes in a custom method please use the following example:
        Code:
        		public void Test()
        		{
        			var instance = new MyTestIndicator(); // use the name of your strategy or indicator where 'MyTestIndicator' is listed.
        			instance.Print(instance.Closes[0][0]);
        		}

        Comment


          #5
          I have the following code

          Code:
          #region Using declarations
          using System;
          using System.ComponentModel;
          using System.Diagnostics;
          using System.Drawing;
          using System.Drawing.Drawing2D;
          using System.Xml.Serialization;
          using System.Collections;
          using System.Collections.Generic;
          using System.Timers;
          using NinjaTrader.Cbi;
          using NinjaTrader.Data;
          using NinjaTrader.Indicator;
          using NinjaTrader.Gui.Chart;
          using NinjaTrader.Strategy;
          #endregion
          
          // This namespace holds all strategies and is required. Do not change it.
          namespace NinjaTrader.Strategy
          {
              /// <summary>
              /// TestLinkedList
              /// </summary>
              [Description("TestLinkedList")]
              public class TestLinkedList : Strategy
              {
                  #region Variables
                  // Wizard generated variables
                  [B]private int myInput  = 1[/B]; // Default setting for MyInput0
          		[B]private LinkedList<double> printlist = new LinkedList<double>();[/B]
          		private double lastprint =0;
          		private double someprint =0;		
          		private static DateTime startuptime = DateTime.MinValue;		
          		[B]private static LinkedListNode<double> currentnode = new LinkedListNode<double>(0.00);[/B]
          		
                  // User defined variables (add any user defined variables below)
                  #endregion
          
                  /// <summary>
                  /// This method is used to configure the strategy and is called once before any strategy method is called.
                  /// </summary>
                  protected override void Initialize()
                  {
                      CalculateOnBarClose = false;
          			Add(PeriodType.Second, 1);
          			startuptime = DateTime.Now;
                  }
          		protected override void OnStartUp()
          		{
          			Timer SecondTimer = new Timer(1000);
          			SecondTimer.Elapsed+=  new ElapsedEventHandler((sender, e) => [B]ProcessPerSecond(currentnode)[/B]);
          			SecondTimer.Enabled = true;
          		}		
          
                  /// <summary>
                  /// Called on each bar update event (incoming tick)
                  /// </summary>
                  protected override void OnBarUpdate()
                  {			
          		
                  }
          		protected void ProcessPerSecond(LinkedListNode<double> somenode)
          		{
          			if(somenode.List!=null)
          			{
          				var instance = new TestLinkedList();
          				while(somenode.Value!=null)
          				{
          					instance.Print("From LList");
          					instance.Print("Price traded = "+somenode.Value);
          					somenode= somenode.Next;
          				}
          			}			
          				[B]currentnode= printlist.Last;[/B]
                                          [B]myInput =5;[/B]
          		}
          		protected override void OnMarketData(MarketDataEventArgs e)
          		{
          			if(e.MarketDataType==MarketDataType.Last)
          			{
          				lock(printlist)
          				{
          				double nowprint = e.Price;
          				if(Math.Round(nowprint,2)!=Math.Round(lastprint,2))
          				{
          					Print("Last Print is"+ nowprint );
          					printlist.AddLast(nowprint);
          					lastprint = nowprint;
          				}
          				}
          				[B]Print("My Input= "+myInput);[/B]
          			}			
          		}
          		
              #region Properties
                  [Description("")]
                  [GridCategory("Parameters")]
                   public int MyInput
                  {
                      get { return myInput; }
                      set { myInput = Math.Max(1, value); }
                  }
          		[B][XmlIgnore()]
          		public LinkedList<double> Printlist
          		{
          			get; set;
          		}[/B]
          		public double Lastprint
          		{
          			get;set;
          		}
          		public double Someprint
          		{
          			get;set;
          		}		
          		[B][XmlIgnore()]
          		public LinkedListNode<double> Currentnode
          		{
          			get{return currentnode;}set{value = currentnode;}
          		}[/B]
                  #endregion
              }
          }
          The problem i am having is that, i can pass an argument outside of OnMarketData(),
          but i am unable to make changes to a static variable declared in class TestLinkedList, outside of OnMarketData().

          Example . please see the variable myInput , i changed its value inside of the timer but it doesnt change to 5. same problem with currentnode object.

          why is this happening? is there a workaround. the getter/setter doesnt seem to work, tho i cant imagine why i would even need a getter setter.

          Can you please provide me some insight into the internal working of ninjascript code.

          For OnMarketData() and OnBarUpdate(), is a new instance of TestLinkedList created every time? why can i set the variables inside of OnMarketData(), but not my custom method.

          Please help , i have been flummoxed by this problem for a while, have tried all workarounds, now only thing i can do is print data onto a file and read from it, but that would significantly add overhead. Please just see the code in bold
          Last edited by nemesis45; 04-14-2014, 09:42 PM.

          Comment


            #6
            declaring the objects as static did not help, now the timer isnt working due to error, so basic problem remains

            Edit: i really need to get it working, the custom methods must be able to handle variables declared in the class, since even if i print to a file, i will need to store the last accessed data,
            Last edited by nemesis45; 04-15-2014, 02:53 AM.

            Comment


              #7
              Hello nemesis45,

              Thank you for your response.

              Your method is defined in the OnBarUpdate() but called within the OnStartUp() method, try placing the method outside of the OnBarUpdate() method. In the current state it could not be called unless OnBarUpdate() was called.

              Please set the variable LinkedList in the Variables section as follows:
              Code:
                      #region Variables
              		private LinkedList<double> printlist;
              Then in the Initialize() method set the LinkedList:
              Code:
                      protected override void Initialize()
                      {
              			printlist = new LinkedList<double>();

              Comment


                #8
                Originally posted by NinjaTrader_PatrickH View Post
                Hello nemesis45,

                Thank you for your response.

                Your method is defined in the OnBarUpdate() but called within the OnStartUp() method, try placing the method outside of the OnBarUpdate() method. In the current state it could not be called unless OnBarUpdate() was called.

                Please set the variable LinkedList in the Variables section as follows:
                Code:
                        #region Variables
                		private LinkedList<double> printlist;
                Then in the Initialize() method set the LinkedList:
                Code:
                        protected override void Initialize()
                        {
                			printlist = new LinkedList<double>();
                Thank you for the quick reply.

                My OnBarUpdate() is empty. i havent put any code in it. currently using a timer to trigger an event per second.

                I have used the linked list variable as you have suggested, it does seem to be working, though i would have to check the overall code with timer .

                I am trying to initialise a timer within Initialise() , as follows
                Code:
                //secondtimer.AutoReset = true;
                			//secondtimer.Interval = 10000;
                			//secondtimer.Elapsed+=  new ElapsedEventHandler((sender, e) => ProcessPerSecond(sender,e,currentnode));
                			//secondtimer.Enabled = true;
                The code is returning an error. will update once i can fix it.
                Edit: fixed, did not initialise it properly

                Could you please detail the difference between Initialise() and OnStartup()?
                when i declare a timer in OnStartup(), it seems that the timer event is being triggered twice, meaning OnStartup() is called twice?(or more than once)
                Last edited by nemesis45; 04-15-2014, 09:36 AM.

                Comment


                  #9
                  1.) The timer isnt working properly at all, i want it to fire every 10 seconds, it sometimes fires earlier, sometimes it fires twice.

                  2.) If i try and initialise other variable like,
                  Code:
                  private static double lastprint=0;
                  		private static double someprint=0;
                  in Initialise(), or Onstartup(), the code is returning an error on runtime - OnMarketData(), the value cannot be null

                  I am using these two in OnMarketData(), implies that OnMarketData() is being called before them?

                  so far my code is
                  Code:
                  #region Using declarations
                  using System;
                  using System.ComponentModel;
                  using System.Diagnostics;
                  using System.Drawing;
                  using System.Drawing.Drawing2D;
                  using System.Xml.Serialization;
                  using System.Collections;
                  using System.Collections.Generic;
                  using System.Timers;
                  using NinjaTrader.Cbi;
                  using NinjaTrader.Data;
                  using NinjaTrader.Indicator;
                  using NinjaTrader.Gui.Chart;
                  using NinjaTrader.Strategy;
                  #endregion
                  
                  // This namespace holds all strategies and is required. Do not change it.
                  namespace NinjaTrader.Strategy
                  {
                  	
                      /// <summary>
                      /// TestLinkedList
                      /// </summary>
                      [Description("TestLinkedList")]
                      public class TestLinkedList : Strategy
                      {
                          #region Variables
                          // Wizard generated variables
                  		private static DateTime startuptime; 		
                  		private static LinkedList<double> printlist;
                  		private static double lastprint=0;
                  		private static double someprint=0;		
                  		private static LinkedListNode<double> currentnode;
                  		private static System.Timers.Timer secondtimer;
                  				
                  				
                          // User defined variables (add any user defined variables below)
                          #endregion
                  
                          /// <summary>
                          /// This method is used to configure the strategy and is called once before any strategy method is called.
                          /// </summary>
                          protected override void Initialize()
                          {
                              CalculateOnBarClose = false;
                  			Add(PeriodType.Second, 1);
                  			startuptime = DateTime.Now;
                  			LinkedList<double> printlist = new LinkedList<double>();
                  					
                  			LinkedListNode<double> currentnode = new LinkedListNode<double>(0.00);
                  			secondtimer = new Timer();
                  			secondtimer.AutoReset = true;
                  			secondtimer.Interval = 10000;
                  			secondtimer.Elapsed+=  new ElapsedEventHandler((sender, e) => ProcessPerSecond(sender,e,currentnode));
                  			secondtimer.Enabled = true;	
                          }
                  		protected override void OnStartUp()
                  		{	
                  						
                  			//GC.KeepAlive(GlobalVariables.secondtimer);
                  			
                  		}		
                  
                          /// <summary>
                          /// Called on each bar update event (incoming tick)
                          /// </summary>
                          protected override void OnBarUpdate()
                          {			
                  		
                          }
                  		protected override void OnTermination()
                  		{
                  			// Cleans up our Timer object
                  			secondtimer.Dispose();
                  			currentnode =null;
                  			printlist =null;
                  			
                  		}
                  		protected void ProcessPerSecond(object sender, EventArgs e,LinkedListNode<double> somenode)
                  		{
                  			var instance = new TestLinkedList();
                  			if(Math.Round(somenode.Value,1)!= 0&&somenode!=null)
                  			{
                  				if(Math.Round(somenode.Value,1) != Math.Round(printlist.Last.Value,1))
                  				{
                  					while(somenode!=null)
                  					{
                  						instance.Print("From LList");
                  						instance.Print("Last="+somenode.Value);
                  						somenode = somenode.Next;
                  					}
                  				}
                  			}
                  			instance.Print("here");
                  			currentnode= printlist.Last;			
                  		}
                  		protected override void OnMarketData(MarketDataEventArgs e)
                  		{
                  			if(e.MarketDataType==MarketDataType.Last)
                  			{
                  				lock(printlist)
                  				{
                  				double nowprint = e.Price;
                  				if(Math.Round(nowprint,2)!=Math.Round(lastprint,2))
                  				{
                  					Print("Last Print is"+ nowprint );
                  					printlist.AddLast(nowprint);
                  					lastprint = nowprint;
                  				}
                  				}				
                  			}
                  			
                  		}
                  		
                      #region Properties
                          [Description("")]
                          [GridCategory("Parameters")]		
                  		
                  		public DateTime Startuptime
                  		{
                  			get;set;
                  		}		
                          #endregion
                      }
                  }
                  I had used OnStartUp() to initialise my LinkedList and other variables, instead of Initialise(), since NT help guide suggested that Initialise() may be called more than once, but OnStartup() is called only once prior to all logic execution

                  Edit: The OnTermination() isnt working too, when i try to dispose off the timer using,

                  secondtimer.Dispose();, it continues to print from timer event even though it should not.
                  Last edited by nemesis45; 04-15-2014, 10:05 AM.

                  Comment


                    #10
                    with your approach, i am getting an error,

                    **NT** Error on getting property 'Printlist' for strategy 'TestLinkedList/999959afee294c95ae37c07d35a38008': Object reference not set to an instance of an object.
                    **NT** Error on calling 'OnMarketData' method for strategy 'TestLinkedList/999959afee294c95ae37c07d35a38008': Value cannot be null.

                    It's only when i use,

                    #region Variables
                    // Wizard generated variables
                    private LinkedList<double> printlist = new LinkedList<double>();

                    that i can get the code to work.

                    Comment


                      #11
                      Hello nemesis45,

                      Thank you for your response.

                      My mistake on the OnBarUpdate(), I did not notice that the custom method was outside of the brackets. I would recommend adding a Print() statement within the custom method to verify it is being called properly.

                      For the custom variables it should just be the following in Initialize():
                      Code:
                      			printlist = new LinkedList<double>();
                      					
                      			currentnode = new LinkedListNode<double>(0.00);
                      Initialize() is called when the strategy is started and only once, and used to intialize any items such as DataSeries objects. OnStartUp() is called after Initiliaze() and before OnBarUpdate(), so after initialization and before processing the bars objects and is used to set items only once in the code.

                      May I test the full .cs file? Please attach the strategy's .cs file to you response in it's most updated version even with errors. You will find the file in the following directory on your PC: (My) Documents\NinjaTrader 7\bin\Custom\Strategy.

                      Comment


                        #12
                        My bad on the Initialise(), your code working perfectly with printlist

                        Here is the complete cs file.
                        Attached Files

                        Comment


                          #13
                          Hello nemesis45,

                          Thank you for your response.

                          What are your settings for your test? Data Series, Bar Type and DaysToLoad. In addition, is this a backtest or in real-time?

                          Comment


                            #14
                            Originally posted by NinjaTrader_PatrickH View Post
                            Hello nemesis45,

                            Thank you for your response.

                            What are your settings for your test? Data Series, Bar Type and DaysToLoad. In addition, is this a backtest or in real-time?
                            I am not using OnBarUpdate() method at all, so these shouldnt apply.
                            In OnMarketUpdate()
                            I am checking for MarketDataType == MarketDataType.Last
                            so only the last traded values are being printed/ put into list

                            It is real time, since i am using OnMarketData()

                            Comment


                              #15
                              Hello nemesis45,

                              Thank you for your response.

                              Can you provide a copy of the strategy using the custom method in OnStartUp() and the use of OnTermination() that is not working?

                              Comment

                              Latest Posts

                              Collapse

                              Topics Statistics Last Post
                              Started by usazencort, Today, 01:16 AM
                              0 responses
                              1 view
                              0 likes
                              Last Post usazencort  
                              Started by kaywai, 09-01-2023, 08:44 PM
                              5 responses
                              603 views
                              0 likes
                              Last Post NinjaTrader_Jason  
                              Started by xiinteractive, 04-09-2024, 08:08 AM
                              6 responses
                              23 views
                              0 likes
                              Last Post xiinteractive  
                              Started by Pattontje, Yesterday, 02:10 PM
                              2 responses
                              22 views
                              0 likes
                              Last Post Pattontje  
                              Started by flybuzz, 04-21-2024, 04:07 PM
                              17 responses
                              230 views
                              0 likes
                              Last Post TradingLoss  
                              Working...
                              X