Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

Momentum Trading Strategy

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

    Momentum Trading Strategy

    Hi all,

    I want to develop a momentum trading strategy.

    Here is my 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 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>
        /// Enter the description of your strategy here
        /// </summary>
        [Description("Enter the description of your strategy here")]
        public class MyMomentumStrategy2 : Strategy
        {
            #region Variables
            // Wizard generated variables
            private int myInput0 = 1; // Default setting for MyInput0
            // User defined variables (add any user defined variables below)
    		double maxMomentum = 0;
    		// Series of best performing instruments
    		IntSeries InstrumentIndexes;
    		// This DateTimeSeries is for test and debug purpose only
    		DateTimeSeries MomentumChangeDates;
            #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 = true;
    			// I add additional instruments
    			Add("ABC",PeriodType.Day,1);
    			Add("ABT",PeriodType.Day,1);
    			//
    			InstrumentIndexes = new IntSeries(this, MaximumBarsLookBack.Infinite);
    			MomentumChangeDates = new DateTimeSeries(this, MaximumBarsLookBack.Infinite);
            }
    
            /// <summary>
            /// Called on each bar update event (incoming tick)
            /// </summary>
            protected override void OnBarUpdate()
            {
                // Condition set 1
    			// Check if there are enough bars
    			if(CurrentBar<14)return;
    			if(BarsInProgress==0)
    				{
    					// First instrument
    					maxMomentum=Momentum(14)[0];
    					InstrumentIndexes.Set(BarsInProgress);
    					MomentumChangeDates.Set(Time[0]);
    				}
    			else if (maxMomentum<Momentum(14)[0])
    				{
    					// This is for additional instruments
    					maxMomentum=Momentum(14)[0];
    					InstrumentIndexes.Set(BarsInProgress);
    					MomentumChangeDates.Set(Time[0]);
    				}
    			if(BarsInProgress==2)
    				{
    					// For last instrument only:
    					// The Print statement is for test and debug purpose only
    					Print(MomentumChangeDates[0] + " " + InstrumentIndexes[0] + " " + maxMomentum);
    					// Exit previous Long
    					ExitLong(InstrumentIndexes[1]);
    					// Enter new Long
    					EnterLong(InstrumentIndexes[0], DefaultQuantity, "EnterLongSignalName");
    				}	
            }
    
            #region Properties
            [Description("")]
            [GridCategory("Parameters")]
            public int MyInput0
            {
                get { return myInput0; }
                set { myInput0 = Math.Max(1, value); }
            }
            #endregion
        }
    }
    I test it with instrument "A" ("ABC" and "ABT" added). The strategy detects best performing instruments, here is the output:

    10.2.2012 23:00 0 3,14
    13.2.2012 23:00 0 1,24
    14.2.2012 23:00 2 -0,0800000000000018
    15.2.2012 23:00 0 0,980000000000004
    16.2.2012 23:00 0 1,15
    17.2.2012 23:00 2 0,940000000000001
    21.2.2012 23:00 2 1
    The second column is with InstrumentIndexes, that is BarsInProgress for best performing instruments. So the strategy detects them correctly.

    I expect to ExitLong with Instrument_0 on 14.2.2012 23:00 and to EnterLong with Instrument_2. Then ExitLong with Instrument_2 on 15.2.2012 23:00 and EnterLong with Instrument_0, and so on.

    But the strategy executes only one entry on 27.01.2012 (the first day) and only one exit on 25.01.2013 (the last day).

    What is wrong with my strategy?

    #2
    Hello Valyo,
    Welcome to the forum and I am happy to assist you.

    You have set the value for InstrumentIndexes at BarsInProgress == 0. Thus it will always return 0. Is that what you meant to do.

    If you are trying to enter in one data series and exit on another then please refer to this sample code which is on similar lines


    I would suggest further debugging you code. Please refer to this post which further illustrates how to debug a NinjaScript code with NinjaTrader.
    JoydeepNinjaTrader Customer Service

    Comment


      #3
      Hello Joydeep,

      I corrected the code:

      Code:
      #region Variables
              // Wizard generated variables
              private int myInput0 = 1; // Default setting for MyInput0
              // User defined variables (add any user defined variables below)
      		// Series of max Momentum
      		DataSeries MaxMomentum;
      		// Series of best performing instruments
      		IntSeries InstrumentIndexes;
              #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 = true;
      			// I add additional instruments
      			Add("ABC",PeriodType.Day,1);
      			Add("ABT",PeriodType.Day,1);
      			//
      			MaxMomentum = new DataSeries(this, MaximumBarsLookBack.Infinite);
      			InstrumentIndexes = new IntSeries(this, MaximumBarsLookBack.Infinite);
              }
      
              /// <summary>
              /// Called on each bar update event (incoming tick)
              /// </summary>
              protected override void OnBarUpdate()
              {
                  // Condition set 1
      			// Check if there are enough bars
      			if(CurrentBar<14)return;
      			if(BarsInProgress==0)
      				{
      					// First instrument
      					MaxMomentum.Set(Momentum(14)[0]);
      					InstrumentIndexes.Set(BarsInProgress);
      				}
      			else if (MaxMomentum[0]<Momentum(14)[0])
      				{
      					// This is for additional instruments
      					MaxMomentum.Set(Momentum(14)[0]);
      					InstrumentIndexes.Set(BarsInProgress);
      				}
      			if(BarsInProgress==2 && (InstrumentIndexes[0] != InstrumentIndexes[1]))
      				{
      					// For last instrument only:
      					// The Print statement is for test and debug purpose only
      					Print(Time[0] + " " + InstrumentIndexes[0] + " " + MaxMomentum[0]);
      					// Exit previous Long
      					ExitLong("ExitLongSignalName","EnterLongSignalName");
      					//ExitLong(InstrumentIndexes[1]);
      					// Enter new Long
      					EnterLong(InstrumentIndexes[0], DefaultQuantity, "EnterLongSignalName");
      				}	
              }
      Now MaxMomentum is a DataSeries.
      For every current bar MaxMomentum is set to be equal to the greatest momentum and InstrumentIndexes is the index of the corresponding instrument.
      Then ExitLong and EnterLong are executed only if there is a change in InstrumentIndexes.
      As far as I understand SignalName and FromSignalName are some identifiers for positions.
      So
      Code:
      ExitLong("ExitLongSignalName","EnterLongSignalName");
      means
      Exit Long with identifier "EnterLongSignalName" (if there is such long position) and identify this exit as "ExitLongSignalName"
      Is this correct?
      The above code still doesn't work. It doesn't execute ExitLong. There is only one entry - on the first day and exit on close (on the last day).
      I tried to specify explicitly the instrument:
      Code:
      ExitLong(InstrumentIndexes[1],DefaultQuantity,"ExitLongSignalName","EnterLongSignalName");
      					
      					// Enter new Long
      					EnterLong(InstrumentIndexes[0], DefaultQuantity, "EnterLongSignalName");
      And it doesn't work. There is something I don't understand.

      Comment


        #4
        Hello Valyo,
        You logic for assigning the values for the series InstrumentIndexes is still not clear.

        What exactly you are trying to achieve using it.

        Code:
        if(BarsInProgress==0)
        {
        	// First instrument
        	MaxMomentum.Set(Momentum(14)[0]);
        	[B]InstrumentIndexes.Set(BarsInProgress);[/B]
        }
        else if (MaxMomentum[0]<Momentum(14)[0])
        {
        	// This is for additional instruments
        	MaxMomentum.Set(Momentum(14)[0]);
        	[B]InstrumentIndexes.Set(BarsInProgress);[/B]
        }
        The code as highlighted in bold gets reassigned on BarsInProgress 1 or 2.
        JoydeepNinjaTrader Customer Service

        Comment


          #5
          Hello Joydeep,

          OnBarUpdate() is called for every BarsInProgress. I am trying to set values of InstrumentIndexes[0]. I need it to be equal to BarsInProgress index of the instrument with greatest momentum.

          Is this code correct or I should use:

          if(BarsInProgress==0)
          {
          // First instrument
          MaxMomentum.Set(Momentum(14)[0]);
          InstrumentIndexes[0]=BarsInProgress;
          }
          else if (MaxMomentum[0]<Momentum(14)[0])
          {
          // This is for additional instruments
          MaxMomentum.Set(Momentum(14)[0]);
          InstrumentIndexes[0]=BarsInProgress;
          }
          ?

          Comment


            #6
            Let's say I have opened long position with Instrument_0. On the next day I see that the price of Instrument_1 is increasing faster than the price of Instrument_0, that is

            Momentum(Instrument_1)>Momentum(Instrument_0)
            Then I want to update my portfolio, I want to close my long position with Instrument_0 and to open long position with Instrument_1.

            This is what I am trying to achieve with the strategy.

            Comment


              #7
              Hello Valyo,
              You have coded a multi instrument strategy and as such the variable InstrumentIndexes may get reassigned when a subsequent secondary bars series gets updated (on the same day).

              Yes, the orders will be tagged with the entry order name if coded so.
              JoydeepNinjaTrader Customer Service

              Comment


                #8
                Hello Joydeep,

                For the moment I want the strategy to work with historical data and backtest.

                It seems that InstrumentIndexes.Set(BarsInProgress); works well, because I see different values of InstrumentIndexes in the output screen.

                I just need to set up ExitLong and EnterLong, so that every time when the instrument with highest Momentum changes, I exit long position with the previous instrument and enter long position with the new instrument.

                How can I specify what order I want to exit?

                Yes, the orders will be tagged with the entry order name if coded so.
                How can I code the orders to be tagged with signal names? It seems it is not enough to add strings to ExitLong and EnterLong. Should I add actions with the strategy wizard and with the signal names? Can I do it in the script directly?

                Comment


                  #9
                  Hello Valyo,
                  Tagging the name should be enough to tie an Entry and Exit order. Please refer to this sample code which further demonstrates it.
                  JoydeepNinjaTrader Customer Service

                  Comment


                    #10
                    It works! Deep thanks, Joydeep!

                    The strategy analyzer output is strange. The Instrument column is strange, but I compared Order time values with the Output screen time values and they are the same.

                    One more question: Is there any way to import Forex historical data in the free version of NinjaTrader? I see only Index and Stock master instruments in Instrument Manager.

                    Thanks again.

                    Comment


                      #11
                      Hello Valyo,
                      Yes, Forex is supported in NinjaTrader. However it would depend if your connectivity provider supports forex or not.

                      Please refer to the section "Understanding the data provided by your connectivity provider" from our help guide to know which of our supported connectivity provider supports forex
                      JoydeepNinjaTrader Customer Service

                      Comment


                        #12
                        Hello Joydeep,

                        I connected to Kinetick and now I have Currency instruments. Thanks!

                        Comment

                        Latest Posts

                        Collapse

                        Topics Statistics Last Post
                        Started by Geovanny Suaza, 02-11-2026, 06:32 PM
                        0 responses
                        633 views
                        0 likes
                        Last Post Geovanny Suaza  
                        Started by Geovanny Suaza, 02-11-2026, 05:51 PM
                        0 responses
                        364 views
                        1 like
                        Last Post Geovanny Suaza  
                        Started by Mindset, 02-09-2026, 11:44 AM
                        0 responses
                        105 views
                        0 likes
                        Last Post Mindset
                        by Mindset
                         
                        Started by Geovanny Suaza, 02-02-2026, 12:30 PM
                        0 responses
                        567 views
                        1 like
                        Last Post Geovanny Suaza  
                        Started by RFrosty, 01-28-2026, 06:49 PM
                        0 responses
                        568 views
                        1 like
                        Last Post RFrosty
                        by RFrosty
                         
                        Working...
                        X