• Тинькофф Банк-лучшие банковские продукты еще выгоднее
    Выбирайте продукт от банка Тинькофф
  • Уважаемые форумчане, друзья и посетители!
    Поступило предложение ( ссылка на обсуждение ) на сбор средств поддержания форума в рабочем состоянии с 1 июня ( оплата хостинга, бэкап ежедневный на другой хостинг и тд), отчетность будет предоставляться ежемесячно. Пока на ЮMoney ( яндекс деньги), доступно картой перевод, далее добавлю другие способы. Сумму перевода указывайте на ваш выбор исходя из своих возможностей.
    Форум продолжает свою работу благодаря Вашим пожертвованиям.

NinjaTrader Событие OnTimer

NinjaCoder

New Member
NinjaTrader
Здравствуйте.
Я хотел бы узнать, в NinjaTrader 7 есть событие OnTimer (или что-то типа этого), при наступлении которого выполняется мой код. Если да, то можно пример кода.
Спасибо.
 
Есть
Код:
private System.Windows.Forms.Timer myTimer = new System.Windows.Forms.Timer();

           

if(true)
                {
                    myTimer.Start();
                }
                else
                {
                    myTimer.Stop();
                }
.....
 
Есть
Код:
private System.Windows.Forms.Timer myTimer = new System.Windows.Forms.Timer();

          

if(true)
                {
                    myTimer.Start();
                }
                else
                {
                    myTimer.Stop();
                }
.....
Большое спасибо за ответ. Я в мире Ninjatrader новичок, да и с C# не сильно дружу.
P.S. Приятно видеть старых знакомых.
 
Прошу помощи у знающих.
Нижеприведенный код должен вызывать MessageBox при наступления события Timer.
MessageBox вызывается, но в произвольном порядке, и более того, когда стратегия удалена с графика и из "Стратегии" в основном окне NT, MessageBox всё-равно появляется.
Подскажите как исправить.
Код:
#region Using declarations
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Xml.Serialization;
using System.Windows.Forms;
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>
    /// TEst
    /// </summary>
    [Description("TEst")]
    public class MyTestServer : Strategy
    {
        #region Variables
        // Wizard generated variables
        private int myInput0 = 1; // Default setting for MyInput0
        // User defined variables (add any user defined variables below)
        private static System.Timers.Timer aTimer;
        #endregion
       
        private IOrder entryOrder = null;
       
        /// <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;
            aTimer = new System.Timers.Timer();
            aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
            aTimer.Interval = 7000;
            aTimer.Enabled = true;
        }

        /// <summary>
        /// Called on each bar update event (incoming tick)
        /// </summary>
        protected override void OnBarUpdate()
        {

        }
       
        protected override void OnTermination()
        {
            aTimer.Enabled = false;
            aTimer.Stop();
            aTimer.Close();
           
        }
       
        private static void OnTimedEvent(object source, ElapsedEventArgs e)
        {
            MessageBox.Show("yyyyyyyyyyyyyyyyyyyyyyyyyyyy");
        }

        #region Properties
        [Description("")]
        [GridCategory("Parameters")]
        public int MyInput0
        {
            get { return myInput0; }
            set { myInput0 = Math.Max(1, value); }
        }
        #endregion
    }
}
 
Код:
        protected override void OnTermination()
        {          
                myTimer.Dispose();
        }
А если не поможет вырубай хуком справа :-)

Код:
        protected override void OnTermination()
        {
            if (timer != null)
            {
                timer.Enabled = false;
                timer = null;
            }
        }
 
Код:
        protected override void OnTermination()
        {         
                myTimer.Dispose();
        }
А если не поможет вырубай хуком справа :-)

Код:
        protected override void OnTermination()
        {
            if (timer != null)
            {
                timer.Enabled = false;
                timer = null;
            }
        }
Пробовал, но....
Вот как это всё работает (
)
P.S. сервис качество сильно снизил.
 
Попробуйте
.Dispose();
на все ресурсы что вы захватили. Чудес в этой железяке не бывает. Что то не так запрограммировано. На видео вижу, что выскакивает. Но нужен код, без него не догадаться, что и как.
Если увидим, то возможно кто то и подскажет, что не так.
 
Попробуйте
.Dispose();
на все ресурсы что вы захватили. Чудес в этой железяке не бывает. Что то не так запрограммировано. На видео вижу, что выскакивает. Но нужен код, без него не догадаться, что и как.
Если увидим, то возможно кто то и подскажет, что не так.
Немного изменит код, вроде ситуация улучшилась, но... Но выполнение метода происходит не с указанным интервалом, о чём говорит лог.
Ну и сам код:
Код:
#region Using declarations
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Xml.Serialization;
using System.Timers;
using NinjaTrader.Cbi;
using NinjaTrader.Data;
using NinjaTrader.Indicator;
using NinjaTrader.Strategy;

#endregion

// This namespace holds all strategies and is required. Do not change it.
namespace NinjaTrader.Strategy
{
    /// <summary>
    /// TEst
    /// </summary>
    [Description("TEst")]
    public class MyTestServer : Strategy
    {
        #region Variables
        // Wizard generated variables
        private int myInput0 = 1; // Default setting for MyInput0
        // User defined variables (add any user defined variables below)
        #endregion
       
        private static System.Timers.Timer aTimer;
        private IOrder entryOrder = null;
       
        /// <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;
           
           
            aTimer = new System.Timers.Timer();
            aTimer.Interval = 20000;
            aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
            aTimer.Enabled = true;
           
        }

        /// <summary>
        /// Called on each bar update event (incoming tick)
        /// </summary>
        protected override void OnBarUpdate()
        {

        }
       
        protected override void OnTermination()
        {
            aTimer.Enabled = false;
            aTimer.Stop();
            aTimer.Dispose();
            Print("Exit: " + DateTime.Now.ToString());
        }
       
        public void OnTimedEvent(object source, ElapsedEventArgs e)
        {
            DateTime date1 = new DateTime(2008, 5, 1, 8, 30, 52);
            Print(DateTime.Now.ToString());
        }

        #region Properties
        [Description("")]
        [GridCategory("Parameters")]
        public int MyInput0
        {
            get { return myInput0; }
            set { myInput0 = Math.Max(1, value); }
        }
        #endregion
    }
}

Output window:
33ynbc7.png
 
Код:
#region Using declarations
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Xml.Serialization;
using NinjaTrader.Cbi;
using NinjaTrader.Data;
using NinjaTrader.Indicator;
using NinjaTrader.Gui.Chart;
using NinjaTrader.Strategy;
//using System.Timers;
#endregion

// This namespace holds all strategies and is required. Do not change it.
namespace NinjaTrader.Strategy
{
    /// <summary>
    /// Enter the description of your strategy here
    /// </summary>
    [Description("Enter the description of your strategy here")]
    public class A0 : Strategy
    {
        #region Variables
        // Wizard generated variables
        private int myInput0 = 1; // Default setting for MyInput0
        // User defined variables (add any user defined variables below)
        #endregion
      
        //private System.Timers.Timer aTimer;
        private IOrder entryOrder = null;
        private System.Windows.Forms.Timer    aTimer;
       
        /// <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 = true;
           
            //aTimer = new System.Timers.Timer();
            aTimer = new System.Windows.Forms.Timer();
            aTimer.Interval = 5000;
            //aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
            aTimer.Tick += new EventHandler(OnTimerTick);
            aTimer.Enabled = true;
        }

        /// <summary>
        /// Called on each bar update event (incoming tick)
        /// </summary>
        protected override void OnBarUpdate()
        {
        }
       protected override void OnTermination()
        {
            //aTimer.Enabled = false;
            //aTimer.Stop();
            if (aTimer != null)
            {
                aTimer.Enabled = false;
                aTimer = null;
            }
            //aTimer.Dispose();
            Print("Exit: " + DateTime.Now.ToString());
        }
       /*
        public void OnTimedEvent(object source, ElapsedEventArgs e)
        {
            DateTime date1 = new DateTime(2008, 5, 1, 8, 30, 52);
            Print(DateTime.Now.ToString());
        }
        */

        private void OnTimerTick(object sender, EventArgs e)
        {
            Print(DateTime.Now.ToString());
        }

        #region Properties
        [Description("")]
        [GridCategory("Parameters")]
        public int MyInput0
        {
            get { return myInput0; }
            set { myInput0 = Math.Max(1, value); }
        }
        #endregion
    }
}
 
Код:
#region Using declarations
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Xml.Serialization;
using NinjaTrader.Cbi;
using NinjaTrader.Data;
using NinjaTrader.Indicator;
using NinjaTrader.Gui.Chart;
using NinjaTrader.Strategy;
//using System.Timers;
#endregion

// This namespace holds all strategies and is required. Do not change it.
namespace NinjaTrader.Strategy
{
    /// <summary>
    /// Enter the description of your strategy here
    /// </summary>
    [Description("Enter the description of your strategy here")]
    public class A0 : Strategy
    {
        #region Variables
        // Wizard generated variables
        private int myInput0 = 1; // Default setting for MyInput0
        // User defined variables (add any user defined variables below)
        #endregion
     
        //private System.Timers.Timer aTimer;
        private IOrder entryOrder = null;
        private System.Windows.Forms.Timer    aTimer;
      
        /// <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 = true;
          
            //aTimer = new System.Timers.Timer();
            aTimer = new System.Windows.Forms.Timer();
            aTimer.Interval = 5000;
            //aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
            aTimer.Tick += new EventHandler(OnTimerTick);
            aTimer.Enabled = true;
        }

        /// <summary>
        /// Called on each bar update event (incoming tick)
        /// </summary>
        protected override void OnBarUpdate()
        {
        }
       protected override void OnTermination()
        {
            //aTimer.Enabled = false;
            //aTimer.Stop();
            if (aTimer != null)
            {
                aTimer.Enabled = false;
                aTimer = null;
            }
            //aTimer.Dispose();
            Print("Exit: " + DateTime.Now.ToString());
        }
       /*
        public void OnTimedEvent(object source, ElapsedEventArgs e)
        {
            DateTime date1 = new DateTime(2008, 5, 1, 8, 30, 52);
            Print(DateTime.Now.ToString());
        }
        */

        private void OnTimerTick(object sender, EventArgs e)
        {
            Print(DateTime.Now.ToString());
        }

        #region Properties
        [Description("")]
        [GridCategory("Parameters")]
        public int MyInput0
        {
            get { return myInput0; }
            set { myInput0 = Math.Max(1, value); }
        }
        #endregion
    }
}
Большое спасибо за Ваши ответы.
Код заработал так, как от него требовалось.
Проблемка оказалась не в коде, а в самом NT. NT походу кэширует стратегии и при последующем запуске восстанавливает сессию из кэша. Решение оказалоь простым, просто при выходи из NT, нажал на кнопку "Not to all".
 
Назад
Верх Низ