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

Newbie needs help

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

    Newbie needs help

    Hey everyone!

    I am brand new to ninja trader. I am coming from thinkorswim thinkscript and have self taught myself to code in their script format. I have just begun the learning process of the NinjaScript and getting used to it but not fast enough. I am hoping with your help I can speed up the process which in turn will allow me to view a fully functional script with my logic to study and base coding off of.

    I think my logic is simple but I am running into issues when it comes to apply multi charts (multiple time frame analysis)

    I currently have a script developed for the primary chart (which will always be the 5-minute chart)

    What I need is to include in my logic the 15-minute current low price and 15-minute 5-simple period moving average.

    I need the logic to play out that the 15-minute low price >= to the 15-minute sma.

    I already have the 5-minute logic complete and have begun to or attempt to develop the 15minute multichart but have become stuck.

    Can someone please help me code this process to save some time.

    The end result should be that my current strategy and entry price confirmation will also include that the condition of the 15-minute low is >= to the 15minute 5sma in order to enter long.

    Thanks in advance!

    My current code below:


    namespace NinjaTrader.NinjaScript.Strategies
    {
    public class SMAtrendUnlocked : Strategy
    {
    private SMA SMA1;
    private SMA SMA2;
    private DM DM1;
    private ATR ATR1;
    private SMA SMA3;
    private SMA SMA4;

    protected override void OnStateChange()
    {
    if (State == State.SetDefaults)
    {
    Description = @"Enter the description for your new custom Strategy here.";
    Name = "SMAtrendUnlocked";
    Calculate = Calculate.OnEachTick;
    EntriesPerDirection = 1;
    EntryHandling = EntryHandling.AllEntries;
    IsExitOnSessionCloseStrategy = true;
    ExitOnSessionCloseSeconds = 30;
    IsFillLimitOnTouch = false;
    MaximumBarsLookBack = MaximumBarsLookBack.TwoHundredFiftySix;
    OrderFillResolution = OrderFillResolution.Standard;
    Slippage = 0;
    StartBehavior = StartBehavior.WaitUntilFlat;
    TimeInForce = TimeInForce.Gtc;
    TraceOrders = false;
    RealtimeErrorHandling = RealtimeErrorHandling.StopCancelClose;
    StopTargetHandling = StopTargetHandling.PerEntryExecution;
    BarsRequiredToTrade = 20;
    // Disable this property for performance gains in Strategy Analyzer optimizations
    // See the Help Guide for additional information
    IsInstantiatedOnEachOptimizationIteration = true;
    FiveSMA2 = 5;
    FivaSMA1 = 5;
    Sharesize = 1000;
    FiveSMA0 = 5;
    DMIplusconfirm = 30;
    }
    else if (State == State.Configure)
    {
    SetProfitTarget(CalculationMode.Currency, 150);
    SetStopLoss(CalculationMode.Currency, 100);

    // Add a 15 minute Bars object to the strategy
    AddDataSeries(Data.BarsPeriodType.Minute, 15);
    }
    else if (State == State.DataLoaded)
    {
    SMA1 = SMA(Close, Convert.ToInt32(FivaSMA1));
    SMA1.Plots[0].Brush = Brushes.Goldenrod;
    AddChartIndicator(SMA1);
    SMA2 = SMA(Close, Convert.ToInt32(FiveSMA2));
    DM1 = DM(Close, 14);
    DM1.Plots[0].Brush = Brushes.DarkSeaGreen;
    DM1.Plots[1].Brush = Brushes.DodgerBlue;
    DM1.Plots[2].Brush = Brushes.Crimson;
    AddChartIndicator(DM1);
    ATR1 = ATR(Close, 14);
    SMA3 = SMA(Close, Convert.ToInt32(FiveSMA0));
    }
    }


    protected override void OnBarUpdate()
    {
    if (CurrentBar < BarsRequiredToTrade)
    return;

    if (SMA4 == null)
    {
    // Note: Bars are added to the BarsArray and can be accessed via an index value
    // E.G. BarsArray[1] ---> Accesses the 5 minute Bars object added above
    SMA4 = SMA(BarsArray[1], 5);
    }

    if (BarsInProgress != 0)
    return;

    if (CurrentBars[0] < 2)
    return;


    // Set 1
    if ((Low[1] >= SMA1[1])
    && (Low[2] >= SMA2[2])
    && (High[0] > High[1])
    && (DM1.DiPlus[0] >= DMIplusconfirm)
    && (ATR1[0] >= 0.05))
    {
    EnterLong(Convert.ToInt32(Sharesize), "");
    }

    // Set 2
    if (GetCurrentBid(0) < SMA3[0])
    {
    ExitLong(Convert.ToInt32(Sharesize), @"5mastop", @"");
    }


    }

    #2
    Hello dorony,

    Thank you for your note.

    Assuming the 15 minute series is the secondary series added, you could use,

    Code:
    if(Lows[1][0] >= SMA(Closes[1], 5)[0])
    Where if the low of the current bar, is higher than a 5 period sma of the secondary series.

    See Closes section of our helpguide,


    Please let us know if you need further assistance.
    Alan P.NinjaTrader Customer Service

    Comment


      #3
      Thank you for replying. Greatly appreciated.

      Let me back track a bit. Every day I am learning how to code and have developed my code now from scratch and beginning to learn how everything fits into place.

      To request a more simple task in order to get a better understanding of secondarySeries, I want to first learn how to plot a 15minute 5sma on the 5min chart.

      I have researched and studied the concepts needed to get this done but I am having trouble.

      It would be great if you could show me the code needed to plot the 15-minute 5sma on the 5minute chart.

      I think my problem is in knowing how to enable the secondarySeries (which I have added in the private section) and what else needs to be added to have the code call out the 15min data and to plot the 15-minute 5sma on the 5-minute chart.

      Here is my current code. All I want to do is plot the 15-minute 5ma. This way I can learn how everything is placed needed to get it to plot. I think from there. This would really help speed up my learning curve as I am stuck here. You can see that I have already attempted the process of plotting this line. Can you please fill in the gaps for me.

      Thank you so much!

      public class Practicefromscratch : Strategy
      {
      private SMA SMA5;
      private SMA SMA15;
      private Series<double> primarySeries;
      private Series<double> secondarySeries;
      protected override void OnStateChange()
      {
      if (State == State.SetDefaults)
      {
      Description = @"Enter the description for your new custom Strategy here.";
      Name = "Practicefromscratch";
      Calculate = Calculate.OnBarClose;
      EntriesPerDirection = 1;
      EntryHandling = EntryHandling.AllEntries;
      IsExitOnSessionCloseStrategy = true;
      ExitOnSessionCloseSeconds = 30;
      IsFillLimitOnTouch = false;
      MaximumBarsLookBack = MaximumBarsLookBack.TwoHundredFiftySix;
      OrderFillResolution = OrderFillResolution.Standard;
      Slippage = 0;
      StartBehavior = StartBehavior.WaitUntilFlat;
      TimeInForce = TimeInForce.Gtc;
      TraceOrders = false;
      RealtimeErrorHandling = RealtimeErrorHandling.StopCancelClose;
      StopTargetHandling = StopTargetHandling.PerEntryExecution;
      BarsRequiredToTrade = 20;
      // Disable this property for performance gains in Strategy Analyzer optimizations
      // See the Help Guide for additional information
      IsInstantiatedOnEachOptimizationIteration = true;

      }
      else if (State == State.Configure)
      {
      // Adding 15min Price Data
      AddDataSeries(BarsPeriodType.Minute, 15);
      }
      else if (State == State.Historical)
      {
      primarySeries = new Series<double>(this);
      secondarySeries = new Series<double>(SMA(BarsArray[1], 50));
      }
      else if (State == State.DataLoaded)
      {
      SMA5 = SMA(Close,5);
      SMA5.Plots[0].Brush = Brushes.Cyan;
      AddChartIndicator(SMA5);
      SMA15 = SMA(BarsArray[1],5);



      }
      }

      protected override void OnBarUpdate()
      {
      if (BarsInProgress != 0)
      return;

      if (CurrentBars[0] < 2)
      return;



      // Enter Long
      if ((Low[2] >= SMA5[2])
      && (Low[1] >= SMA5[1])
      && (High[0] > High[1]))
      {
      EnterLong(100, "");
      }

      // Exit Long
      if (GetCurrentBid(0) < SMA5[0])
      {
      ExitLong(100,@"",@"");
      }

      // Enter Short
      if ((High[2] <= SMA5[2])
      && (High[1] <= SMA5[1])
      && (Low[0] < Low[1]))
      {
      EnterShort(100,"");
      }

      // Exit Short
      if (GetCurrentAsk(0) > SMA5[0])
      {
      ExitShort(100,@"",@"");
      }
      }
      }
      }

      Comment


        #4
        Hello dorony,

        I've attached a sample MA Cross strategy, where 1 moving average is based off the primary series, and the second MA is based off the secondary series. The strategy adds the plots to the chart it is applied to.

        You may also find the following sample helpful for understanding multi series scripts,


        Please let us know if you need further assistance.
        Attached Files
        Alan P.NinjaTrader Customer Service

        Comment


          #5
          Thank you sir!

          This should keep me busy for a while. Will let you know if it doesn't work for me.

          Comment


            #6
            Hey Alan,

            I attempted to add the code in the same fashion and it didn't work. I then went on to add the attachment of the strategy you gave me.

            When I added to a chart, only the seagreen moving average populated. So the strategy you provided me doesn't work for me either.

            Is this because I am using NinjaTrader 8?

            After reviewing some more. The 15min SMA is actually plotting but stops in the past and doesnt remain current.

            Would you know why it stops plotting the sma?

            This is on the code you provided me
            Attached Files
            Last edited by dorony; 01-29-2018, 08:48 PM.

            Comment


              #7
              Hello dorony,

              My mistake, AddChartIndicator can not be used if additional data series are being used, see note 3 at the following link,



              I modified the strategy and instead set the value of the SMA's to plots, and the indicator visual looks as expected.

              Please let us know if you need further assistance.
              Attached Files
              Alan P.NinjaTrader Customer Service

              Comment


                #8
                Hey Thanks.. Ill take a look at it.

                Do any conditions on the OnBarUpdate script effect the actual plot?

                Comment


                  #9
                  Hello dorony,

                  Yes, the following sets the value of the plot on each bar update.

                  Code:
                  Values[0][0] = SMA(BarsArray[1], Fast)[0];
                  Values[1][0] = SMA(BarsArray[0],Slow)[0];
                  Please let us know if you need further assistance.
                  Alan P.NinjaTrader Customer Service

                  Comment


                    #10
                    Hey Alan,

                    I am still having trouble. Would it be possible if I can just provide you with my code and then help me input the correct script/code and parameters for the 15-minute 5sma to plot on my 5-minute chart.

                    Not sure what I am doing wrong, but I tried various things and I am still stumped.

                    Code:
                    public class Practicefromscratch : Strategy
                    	{
                    		private SMA SMA5;
                    		private SMA SMA15;
                    		
                    		protected override void OnStateChange()
                    		{
                    			if (State == State.SetDefaults)
                    			{
                    				Description									= @"Enter the description for your new custom Strategy here.";
                    				Name										= "Practicefromscratch";
                    				Calculate									= Calculate.OnBarClose;
                    				EntriesPerDirection							= 1;
                    				EntryHandling								= EntryHandling.AllEntries;
                    				IsExitOnSessionCloseStrategy				= true;
                    				ExitOnSessionCloseSeconds					= 30;
                    				IsFillLimitOnTouch							= false;
                    				MaximumBarsLookBack							= MaximumBarsLookBack.TwoHundredFiftySix;
                    				OrderFillResolution							= OrderFillResolution.Standard;
                    				Slippage									= 0;
                    				StartBehavior								= StartBehavior.WaitUntilFlat;
                    				TimeInForce									= TimeInForce.Gtc;
                    				TraceOrders									= false;
                    				RealtimeErrorHandling						= RealtimeErrorHandling.StopCancelClose;
                    				StopTargetHandling							= StopTargetHandling.PerEntryExecution;
                    				BarsRequiredToTrade							= 20;
                    				// Disable this property for performance gains in Strategy Analyzer optimizations
                    				// See the Help Guide for additional information
                    				IsInstantiatedOnEachOptimizationIteration	= false;
                    			
                    			}
                    			else if (State == State.Configure)
                    			{
                    				// Adding 15min Price Data
                    				     AddDataSeries(BarsPeriodType.Minute, 15);
                    			
                    			}
                    				else if (State == State.DataLoaded)
                    				{
                    					SMA15 = SMA(BarsArray[1],5);
                    					SMA15.Plots[0].Brush = Brushes.Cyan;
                    					SMA5 = SMA(Close,5);
                    					SMA5.Plots[0].Brush = Brushes.Cyan;
                    					AddChartIndicator(SMA5);
                    					
                    					
                    					
                    			}
                    		}
                    
                    		protected override void OnBarUpdate()
                    		{	   
                    			
                    			if (CurrentBars[0] < 1 || CurrentBars[1] < 1)
                    				return;
                    
                    			Values[0][0] = SMA(BarsArray[1], 5)[0];
                    			
                    			
                    			// Enter Long
                    			if ((Low[2] >= SMA5[2])
                    			&& (Low[1] >= SMA5[1])
                    			&& (High[0] > High[1]))
                    		
                    				
                    	    	{
                    				EnterLong(100, "");
                    			}
                    			
                    			// Exit Long
                    			if (GetCurrentBid(0) < SMA5[0])
                    			{
                    				ExitLong(100,@"",@"");
                    			}
                    			
                    			// Enter Short
                    			if ((High[2] <= SMA5[2])
                    			&& (High[1] <= SMA5[1])
                    			&& (Low[0] < Low[1])
                    			&& (Highs[1][0] <= SMA15[0]))
                    
                    			{
                    				EnterShort(100,"");
                    			}
                    			
                    			// Exit Short
                    			if (GetCurrentAsk(0) > SMA5[0])
                    			{
                    				ExitShort(100,@"",@"");
                    			}
                    		}
                    	}
                    }

                    Comment


                      #11
                      Hello dorony,

                      In (State == State.DataLoaded) you still have AddChartIndicator, which I mentioned can not be used if additional data series are being used, see note 3 at the following link,


                      The sample I provided shows the correct way to set the plots.
                      Support for the development of custom automated trading strategies using NinjaScript.


                      Please let us know if you need further assistance.
                      Alan P.NinjaTrader Customer Service

                      Comment


                        #12
                        Thanks for your assistance. It is greatly appreciated.

                        Still doesn't work without it.
                        Attached Files

                        Comment


                          #13
                          Hello dorony,

                          What is the issue you are having?

                          Are you seeing any errors in the log tab?

                          Your CurrentBar check requires only 1 bar however you are taking an SMA of 5. You should see the following link on CurrentBar checks,
                          Make sure you have enough bars in the data series you are accessing


                          You should either use BarsInProgress to control which series you are referring to with Low[0], or use Lows[1][0] to specify the low of a specific series. For an example of using BarsInProgress, see under True Event Driven OnBarUpdate() Method at the following link,


                          For an example of using Lows to specify which series you are referencing, see,


                          I look forward to your reply.
                          Alan P.NinjaTrader Customer Service

                          Comment


                            #14
                            Alright! I got it to plot finally!

                            My issue was not adding the AddPlot script in SetDefaults.

                            My question is, how does it now to assign the Addplot to the specific movingavg. The reason I ask,is i don't see any connection between the Addplot function and the Value function.

                            Can you please explain?

                            Also, let me know if I am correct.

                            BarsInProgress and CurrentBars do the same thing but require a different function.

                            BarsInProgress you use the index field [ ] and only call functions within that Array. Or just using CurrentBars you would you would use the index field plus the plural Lows or Highs
                            Attached Files

                            Comment


                              #15
                              Hello dorony,

                              Just below your CurrentBar check, Values[0][0] is how the first plots values are set to the SMA. Values[1][0] is how the seconds plots values are set.

                              See Addplot section of our helpguide,


                              Please let us know if you need further assistance.
                              Alan P.NinjaTrader Customer Service

                              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