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

Issue with Strategy Code

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

    Issue with Strategy Code

    I am new to coding and trying to get a simple RSI strategy developed. Below is the code i put together. Need some assistance identifying where I am going wrong since I keep getting errors. Any help is greatly appreciated. Thanks

    region Using declarations
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.ComponentModel.DataAnnotations;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Windows;
    using System.Windows.Input;
    using System.Windows.Media;
    using System.Xml.Serialization;
    using NinjaTrader.Cbi;
    using NinjaTrader.Gui;
    using NinjaTrader.Gui.Chart;
    using NinjaTrader.Gui.SuperDom;
    using NinjaTrader.Gui.Tools;
    using NinjaTrader.Data;
    using NinjaTrader.NinjaScript;
    using NinjaTrader.Core.FloatingPoint;
    using NinjaTrader.NinjaScript.Indicators;
    using NinjaTrader.NinjaScript.DrawingTools;
    #endregion

    //This namespace holds Strategies in this folder and is required. Do not change it.
    namespace NinjaTrader.NinjaScript.Strategies
    {
    public class MACDStrategy : Strategy
    {
    private MACD macd;
    private double macdavg;
    private double MACDDiff;

    protected override void OnStateChange()
    {
    if (State == State.SetDefaults)
    {
    Description = @"Enter the description for your new custom Strategy here.";
    Name = "MACDStrategy";
    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;
    Fast = 12;
    Slow = 26;
    Smooth = 9;

    }
    else if (State == State.Configure)
    {
    }

    else if (State == State.DataLoaded)
    {
    macd = MACD(Close, Fast, Slow, Smooth);
    macdavg = MACD(Close, Fast, Slow, Smooth).Avg[0];
    }
    }

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

    MACDDiff = macd[0]-macdavg;

    if(MACDDiff[1]<0 && MACDDiff[0]>0)
    EnterLong();

    if(MACDDiff[1]>0 && MACDDiff[0]<0)
    EnterShort();

    }
    region Properties
    [NinjaScriptProperty]
    [Display(ResourceType = typeof(Custom.Resource), Name = "Fast Period", GroupName = "NinjaScriptStrategyParameters", Order = 0)]
    public int Fast
    { get; set; }

    [NinjaScriptProperty]
    [Display(ResourceType = typeof(Custom.Resource), Name = "Slow Period", GroupName = "NinjaScriptStrategyParameters", Order = 0)]
    public int Slow
    { get; set; }

    [NinjaScriptProperty]
    [Display(ResourceType = typeof(Custom.Resource), Name = "Smooth", GroupName = "NinjaScriptStrategyParameters", Order = 0)]
    public int Smooth
    { get; set; }

    #endregion

    }
    }


    #2
    Hello algospoke,

    Welcome to the NinjaTrader forums!

    Please provide the full error message, including line numbers, or a screenshot of the error you would like assistance with.

    Below I am also providing a link to a forum post with helpful resources on getting started with NinjaScript and C#.



    One thing I am noticing is that you are trying to subtract an entire series from a single double value.

    macd[0]-macdavg;

    Where you trying to get the most recent bar double value of the macdavg?

    MACDDiff = macd[0]-macdavg[0];
    Chelsea B.NinjaTrader Customer Service

    Comment


      #3
      Chelsea,

      Thanks for the quick response! See attached for pic of error code.

      In words, I am trying to make a strategy that does the below:

      For each new bar, calculate the difference the MACD and the MACD Average and call it MACDDiff

      Then I want to compare the MACDDiff of the current bar to the MACDDiff of the previous bar. If the MACDDiff went from a negative number to a positive number then I want to EnterLong

      Opposite for Entering short

      Thanks
      Attached Files

      Comment


        #4
        Hello algospoke,

        The errors in the screenshot are stating that a double, which is a single number value (with a decimal), cannot be indexed ([0] is an index).

        MACDDiff is a double, a single value, and is not a Series<double>.

        Declare this as a Series<double> and instantiate a new object in State.DataLoaded if you want to be able to get values for previous bars.
        Chelsea B.NinjaTrader Customer Service

        Comment


          #5
          I changed MACDDiff to a Series<double> but getting another error. See below for error and code

          Click image for larger version

Name:	image.png
Views:	69
Size:	6.2 KB
ID:	1290752

          region Using declarations
          using System;
          using System.Collections.Generic;
          using System.ComponentModel;
          using System.ComponentModel.DataAnnotations;
          using System.Linq;
          using System.Text;
          using System.Threading.Tasks;
          using System.Windows;
          using System.Windows.Input;
          using System.Windows.Media;
          using System.Xml.Serialization;
          using NinjaTrader.Cbi;
          using NinjaTrader.Gui;
          using NinjaTrader.Gui.Chart;
          using NinjaTrader.Gui.SuperDom;
          using NinjaTrader.Gui.Tools;
          using NinjaTrader.Data;
          using NinjaTrader.NinjaScript;
          using NinjaTrader.Core.FloatingPoint;
          using NinjaTrader.NinjaScript.Indicators;
          using NinjaTrader.NinjaScript.DrawingTools;
          #endregion

          //This namespace holds Strategies in this folder and is required. Do not change it.
          namespace NinjaTrader.NinjaScript.Strategies
          {
          public class MACDStrategy : Strategy
          {
          private MACD macd;
          private double macdavg;
          private Series<double>MACDDiff;

          protected override void OnStateChange()
          {
          if (State == State.SetDefaults)
          {
          Description = @"Enter the description for your new custom Strategy here.";
          Name = "MACDStrategy";
          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;
          Fast = 12;
          Slow = 26;
          Smooth = 9;

          }
          else if (State == State.Configure)
          {
          }

          else if (State == State.DataLoaded)
          {
          macd = MACD(Close, Fast, Slow, Smooth);
          macdavg = MACD(Close, Fast, Slow, Smooth).Avg[0];
          MACDDiff = macd-macdavg;
          }
          }

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

          if(MACDDiff[1]<0 && MACDDiff[0]>0)
          EnterLong();

          if(MACDDiff[1]>0 && MACDDiff[0]<0)
          EnterShort();

          }
          region Properties
          [NinjaScriptProperty]
          [Display(ResourceType = typeof(Custom.Resource), Name = "Fast Period", GroupName = "NinjaScriptStrategyParameters", Order = 0)]
          public int Fast
          { get; set; }

          [NinjaScriptProperty]
          [Display(ResourceType = typeof(Custom.Resource), Name = "Slow Period", GroupName = "NinjaScriptStrategyParameters", Order = 0)]
          public int Slow
          { get; set; }

          [NinjaScriptProperty]
          [Display(ResourceType = typeof(Custom.Resource), Name = "Smooth", GroupName = "NinjaScriptStrategyParameters", Order = 0)]
          public int Smooth
          { get; set; }

          #endregion

          }
          }

          Comment


            #6
            Hello algospoke,

            The macd variable you have declared as a Series<double> and not a double. Use an index on series, do not use an index on doubles.

            macd[0] would be the most recent bar in the series.
            Chelsea B.NinjaTrader Customer Service

            Comment


              #7
              Chelsea,

              I am confused what you are suggesting i change in the code. Can you markup my code from my previous post?

              I already assigned MACDDiff as Series<double>

              Click image for larger version  Name:	image.png Views:	0 Size:	4.1 KB ID:	1291256

              I want to compare MACDDiff of the current bar to the MACDDiff of the previous bar to determine if i want to enter long or enter short. Below are the calculations i was planning on using to determine the value of MACDDiff
              Click image for larger version  Name:	image.png Views:	0 Size:	4.4 KB ID:	1291257

              I am getting the below error message on the line "MACDDiff = macd-macdavg". Why am i getting this error? Can you fix the code?
              Click image for larger version  Name:	image.png Views:	0 Size:	3.8 KB ID:	1291258

              My goal is that if the MACDDiff of the previous bar is less than 0 and the MACDDiff of the current bar is greater than 0 then I want to enter long. See below and let me know if this is correct.
              Click image for larger version  Name:	image.png Views:	0 Size:	5.5 KB ID:	1291259

              Thanks for you help!

              Comment


                #8
                Hello algospoke,

                MACDDiff[0] = macd[0] - macdavg;

                May I have you confirm you are understanding when to use an index and when not to use an index?

                Is the MACDDiff variable a Series or a double? Should this use an index?
                Is the macd variable an indicator (plot series) or a double? Should this use an index?
                is the macdavg variable a Series or a double? Should this use an index?
                Chelsea B.NinjaTrader Customer Service

                Comment


                  #9
                  Chelsea,

                  I am new to coding but my understanding of index is that whenever you want to see the value of a variable X bars ago you would assign it a series double. I tried this MACDDiff, macd, and macdavg but getting error because I use NinjaTrader preprogrammed MACD function and assign it to a variable macd.

                  My question is how would you code the variables MACDDiff, macd, and macdavg so that I can see what their values were X bars ago? Below are the equations that define each variable:

                  macd = MACD(Close, Fast, Slow, Smooth);
                  macdavg = MACD(Close, Fast, Slow, Smooth).Avg[0];
                  MACDDiff = macd-macdavg​

                  Comment


                    #10
                    Hello algospoke,

                    In the scope of the class:
                    Code:
                    private MACD myMACD;
                    In State.DataLoaded:
                    Code:
                    myMACD = MACD(Fast, Slow, Smooth);
                    In OnBarUpdate():
                    Code:
                    Print(Time[0].ToString() + " | MACD: " + myMACD[0]);
                    Print(Time[0].ToString() + " | MACD.Avg[0]: " + myMACD.Avg[0]);
                    Print(Time[0].ToString() + " | MACD.Diff[0]: " + myMACD.Diff[0]);
                    
                    if (myMACD.Diff[1] < 1 && myMACD.Diff[0] > 0)
                    {
                    EnterLong();
                    }
                    Chelsea B.NinjaTrader Customer Service

                    Comment


                      #11
                      Awesome Chelsea! That worked! But I am a little confused...

                      How does myMACD.Diff know to take the difference between MACD and the MACD.Avg? I don't see that in the Ninjascript manual. Can you send me where I could find this in the Ninjascript manual so I can read up on it? Thanks

                      Comment


                        #12
                        Hello algospoke,

                        myMACD holds the MACD indicator instance.

                        The indicator has 3 public plot series that can be accessed.

                        Try adding this indicator to a chart. You can look at the databox to see all of the plots available.

                        Below is a link to the help guide on the MACD indicator.


                        "How does myMACD.Diff know to take the difference between MACD and the MACD.Avg?"

                        That's what is coded in the script. This is an open source script so you can view the code in the NinjaScript Editor.
                        Chelsea B.NinjaTrader Customer Service

                        Comment

                        Latest Posts

                        Collapse

                        Topics Statistics Last Post
                        Started by rhyminkevin, Today, 04:58 PM
                        3 responses
                        47 views
                        0 likes
                        Last Post Anfedport  
                        Started by iceman2018, Today, 05:07 PM
                        0 responses
                        5 views
                        0 likes
                        Last Post iceman2018  
                        Started by lightsun47, Today, 03:51 PM
                        0 responses
                        7 views
                        0 likes
                        Last Post lightsun47  
                        Started by 00nevest, Today, 02:27 PM
                        1 response
                        14 views
                        0 likes
                        Last Post 00nevest  
                        Started by futtrader, 04-21-2024, 01:50 AM
                        4 responses
                        50 views
                        0 likes
                        Last Post futtrader  
                        Working...
                        X