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

Timer is getting fired twice.

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

    Timer is getting fired twice.

    Hi,

    I am using a timer , copied directly from your script , only difference is that initialisation is done in Initialise ().
    Here is the 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;
    [B]using System.Windows.Forms;[/B]
    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 LinkedList<double> printlist;
    		private double lastprint;
    		private double someprint;		
    		private LinkedListNode<double> currentnode;
    		[B]private System.Windows.Forms.Timer secondtimer ;	[/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;			
    			currentnode = new LinkedListNode<double>(0.00);
    			printlist = new LinkedList<double>();
    			[B]secondtimer = new System.Windows.Forms.Timer();[/B]
    			
    			//LinkedList<double> printlist = new LinkedList<double>();
    					
    			
            }
    		protected override void OnStartUp()
    		{	
    			
    			[B]secondtimer.Interval = 10000;
    			secondtimer.Tick+=  new EventHandler((sender,e)=>ProcessPerSecond(currentnode));
    			secondtimer.Enabled = true;		[/B]		
    						
    		}		
    
            /// <summary>
            /// Called on each bar update event (incoming tick)
            /// </summary>
            protected override void OnBarUpdate()
            {			
    		
            }
    		protected override void OnTermination()
    		{			
    			[B]secondtimer.Dispose();[/B]
    			// Cleans up our Timer object						
    			
    		}
    		[B]protected void ProcessPerSecond(LinkedListNode<double> somenode)
    		{
    			var instance = new Empty();
    			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"); 
    			instance.Print("Current Time= "+ DateTime.Now);
    			currentnode= printlist.Last;			
    		}[/B]
    		protected override void OnMarketData(MarketDataEventArgs e)
    		{
    			if(e.MarketDataType==MarketDataType.Last)
    			{				
    				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")]		
    		[XmlIgnore()]
    		public LinkedList<double> Printlist
    		{
    			get{return printlist;} set{ printlist=value;}
    		}
    		public double Lastprint
    		{
    			get{return lastprint;} set{lastprint =value ;}
    		}
    		public double Someprint		
    		{
    			get{return someprint;} set{someprint=value;}
    		}
    		[XmlIgnore()]
    		public LinkedListNode<double> Currentnode
    		{
    			get{return currentnode;} set{currentnode=value;}
    		}
    		[XmlIgnore()]
    		public Timer Secondtimer
    		{
    			get{return secondtimer;} set{secondtimer=value;}
    		}
            #endregion
        }
    }
    Everything is working fine, except that the timer is getting fired twice.

    1) why is that System.Timer does not work , but System.Windows.Forms timer works

    2) why is the timer getting fired twice, i tried changing
    var instance = new TestLinkedList(), to another instance of some empty strategy, but i cant understand why the timer is getting fired twice.

    Everything works under visual studio.. I have checked individual logic.
    The Print("here") along with the time is getting printed twice.

    Please help

    #2
    Hello,

    Try changing:
    secondtimer.Tick+= new EventHandler((sender,e)=>ProcessPerSecond(currentn ode));

    To
    secondtimer.Tick+= new EventHandler(ProcessPerSecond());

    Here is a working sample for you.
    Attached Files
    Chelsea B.NinjaTrader Customer Service

    Comment


      #3
      I need to pass an argument to the timer event handler

      Have to use a lambda expression because of that. It works in c#, why not in ninja

      Please also tell me why isnt System.Timers Timer wouldnt work.

      ill give it a try though, lets see at this point any solution would do lol
      Last edited by nemesis45; 04-16-2014, 01:07 PM.

      Comment


        #4
        Hello,

        Have you added using System.Timers; to your script?
        Without this or the timer from System.Windows.Forms the timer object class will not be available.
        http://msdn.microsoft.com/en-us/libr...v=vs.110).aspx

        With System.Timers added the following should work.
        private System.Timers.Timer mytimer = new System.Timers.Timer();

        Just a tip though, System.Timers.Timer is used for scheduled events and not interval events. System.Windows.Forms.Timer is used for interval events.

        I'm not sure about why it is being called twice. Does it print "Here" twice every 10 seconds or just when it is started?

        Also, why is there a public Timer object SecondTimer?
        Are you attempting to expose your timer to another script? (this might be causing issues I'm not sure)
        Last edited by NinjaTrader_ChelseaB; 04-16-2014, 03:05 PM.
        Chelsea B.NinjaTrader Customer Service

        Comment


          #5
          Hi nemesis45,

          I've looked further into this and your usage is correct. The (sender, e) delegate is passed to the EventHandler.Tick correctly, and the function call should be fine too.

          May I have an export of this script to test so that all dependencies are satisfied?

          To export your script do the following:
          • Click File -> Utilities -> Export NinjaScript
          • Enter a unique name for the file in the value for 'File name:'
          • Select the strategy from the objects list on the left -> click the right facing arrow ">" to add the strategy to the export
          • Click the 'Export' button -> click 'yes' to add any referenced indicators to the export -> click OK to clear the export location message


          By default your exported file will be in the following location:
          • (My) Documents/NinjaTrader 7/bin/Custom/ExportNinjaScript/<export_file_name.zip>


          Below is a link to the help guide on Exporting NinjaScripts.
          Chelsea B.NinjaTrader Customer Service

          Comment


            #6
            Hello,

            Have you added using System.Timers; to your script?
            Without this or the timer from System.Windows.Forms the timer object class will not be available.
            http://msdn.microsoft.com/en-us/libr...v=vs.110).aspx
            Yes of course when i used System.Timers. as i said i had checked the code in visual studio.

            Just a tip though, System.Timers.Timer is used for scheduled events and not interval events. System.Windows.Forms.Timer is used for interval events.
            Thanks , i did not know that. But still the curiosity why is one timer working another isnt.
            I'm not sure about why it is being called twice. Does it print "Here" twice every 10 seconds or just when it is started?
            Yes it Prints "Here" twice along with datetime.now every 10 seconds.

            Also, why is there a public Timer object SecondTimer?
            Are you attempting to expose your timer to another script? (this might be causing issues I'm not sure)
            No i just wanted to check with the getter/setter, i had errors on that with other objects earlier. I am not actually using the timer in another script.

            Comment


              #7
              Originally posted by NinjaTrader_ChelseaB View Post
              Hi nemesis45,

              I've looked further into this and your usage is correct. The (sender, e) delegate is passed to the EventHandler.Tick correctly, and the function call should be fine too.

              May I have an export of this script to test so that all dependencies are satisfied?

              To export your script do the following:
              • Click File -> Utilities -> Export NinjaScript
              • Enter a unique name for the file in the value for 'File name:'
              • Select the strategy from the objects list on the left -> click the right facing arrow ">" to add the strategy to the export
              • Click the 'Export' button -> click 'yes' to add any referenced indicators to the export -> click OK to clear the export location message


              By default your exported file will be in the following location:
              • (My) Documents/NinjaTrader 7/bin/Custom/ExportNinjaScript/<export_file_name.zip>


              Below is a link to the help guide on Exporting NinjaScripts.
              http://www.ninjatrader.com/support/h...nt7/export.htm
              Ok i did this. It is exporting the file to the said location.
              Last edited by nemesis45; 04-16-2014, 07:23 PM.

              Comment


                #8
                ok thanks a lot guys i got this working now.

                Problem was when i clicked on apply, then click on ok, when applying strategy to chart.

                somehow the OnTermination() didnt work properly. and the timer got initialised twice.

                Now for the remaining bugs.
                Last edited by nemesis45; 04-17-2014, 01:53 AM.

                Comment


                  #9
                  Hi nemesis45,

                  When you click OK it also applies. There is no need to click Apply if you plan to click OK anyway.

                  OnTermination() is only called if the script is being removed from the chart. If the timer is set in Initialize() and the script is not added, that will create a timer that will never be destroyed and may eventually crash NinjaTrader.

                  I recommend that you create the timer in OnStartUp() instead of Intialize() for this reason.
                  Chelsea B.NinjaTrader Customer Service

                  Comment


                    #10
                    Yes, the timer was set in OnStartup(), as you can see from code file.
                    If OnTermination() worked 100% there shouldnt have been a problem at all.

                    But anyways now i know that it wont work , so still ok .!

                    Comment


                      #11
                      Hello nemesis45,

                      From the code in your post #1, I am seeing that the timer is set in Initialize and is started in OnStartUp().

                      Code:
                       protected override void Initialize()
                              {
                                  CalculateOnBarClose = false;			
                      			currentnode = new LinkedListNode<double>(0.00);
                      			printlist = new LinkedList<double>();
                      			[B]secondtimer = new System.Windows.Forms.Timer();[/B]
                      			//LinkedList<double> printlist = new LinkedList<double>();
                              }
                      		protected override void OnStartUp()
                      		{	
                      			
                      			secondtimer.Interval = 10000;
                      			secondtimer.Tick+=  new EventHandler((sender,e)=>ProcessPerSecond(currentnode));
                      			secondtimer.Enabled = true;				
                      						
                      		}
                      Have you changed this code since that post?
                      Chelsea B.NinjaTrader Customer Service

                      Comment


                        #12
                        Originally posted by NinjaTrader_ChelseaB View Post
                        Hello nemesis45,

                        From the code in your post #1, I am seeing that the timer is set in Initialize and is started in OnStartUp().
                        Have you changed this code since that post?
                        I see, thanks !. I thought i was just initialising it, and setting up in the OnStartup() afterwords, changed the code as you said. works fine.

                        Comment

                        Latest Posts

                        Collapse

                        Topics Statistics Last Post
                        Started by rocketman7, Today, 02:12 AM
                        5 responses
                        23 views
                        0 likes
                        Last Post rocketman7  
                        Started by trilliantrader, 04-18-2024, 08:16 AM
                        7 responses
                        28 views
                        0 likes
                        Last Post NinjaTrader_BrandonH  
                        Started by samish18, 04-17-2024, 08:57 AM
                        17 responses
                        66 views
                        0 likes
                        Last Post NinjaTrader_BrandonH  
                        Started by briansaul, Today, 05:31 AM
                        1 response
                        15 views
                        0 likes
                        Last Post NinjaTrader_Jesse  
                        Started by PaulMohn, Today, 03:49 AM
                        1 response
                        12 views
                        0 likes
                        Last Post NinjaTrader_BrandonH  
                        Working...
                        X