Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

How to Plot a Displaced SMA in a Strategy

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

    How to Plot a Displaced SMA in a Strategy

    Hello, I am trying to code an SMA/DMA Crossover Strategy and am having trouble figuring out how to plot the displaced SMA. As you can see from the attached screen shot, only one line plots. Any suggestions? Code is attached and compiles just fine. Click image for larger version

Name:	A1SMADisplacedCrossoverStrategy.png
Views:	165
Size:	947.8 KB
ID:	1050373

    #2
    Hello JohnS52,

    Thank you for the post.

    In this case, you are already using the correct syntax to plot the SMA however you are using the same SMA so its visual representation would be identical.

    You are using 1 BarsAgo in your logic where you check the value however this does not relate to how the indicator will show visually. Each SMA used has the same period used so they would be overlaid on the chart and would be identical.

    I look forward to being of further assistance.
    JesseNinjaTrader Customer Service

    Comment


      #3
      Hello Jesse - thank you for your reply. I have amended the strategy to use different period names for the SMA and the DMA (but they are the same length). I am attaching a screenshot of the Strategy Analyzer with this modification - still only one indicator is plotted. And idea how to get the displaced SMA plotted? Displaced SMAs plot fine on a chart as an indicator. Of course, if I change the DMA to a different length than the SMA then both lines will plot, red and blue, but then this would then be a simple SMA Crossover, not an SMA/DMA crossover.

      This line of code compiles but the Strategy Analyzer won't run it: DMA2.Plots[1].Brush = Brushes.Blue;
      Attached Files

      Comment


        #4
        Hello JohnS52,

        Thank you for your reply.

        This is correct, you are using the same indicator and comparing it against its self so there is no value change to see a difference. In your code, you used the prior bar (not displacement) for your condition and that is why that can become true because that specifically has a different value than the current bar.

        If you wanted to see two separate Plots, you would need to use two different periods because this is the same indicator and that would allow for different values to be generated. Otherwise what you are seeing would be correct based on the syntax being used.

        In the chart when you manually apply indicators there is also the visual displacement property however this is not the same as the indicators Period. There is also no concept of displacement when reading values from indicators so trying to match the visual Displacement property in code would be difficult. In coding you are instead referencing data by using a BarsAgo from the current bar. If the goal was to compare the value of 1 BarsAgo against the CurrentBar, that is what you have done.

        If you wanted to visually see the values you had used in your conditions to see what your code is doing, you would need to have the strategy plot the values you are using instead of adding the indicator so you can plot the 1 BarsAgo value in the same space as the current value.

        https://ninjatrader.com/support/help...ghtsub=addplot

        I look forward to being of further assistance.



        JesseNinjaTrader Customer Service

        Comment


          #5
          Hello Jesse - I want to visually see the values so I tried adding the Displacement code in State.SetDefaults and received the error message: "The name 'Displacement' does not exist in the current context." I also tried adding it to State.Historical with no success either. So I commented out all the Displacement code. Any suggestions?

          Then I changed the code to GreaterThan/LessThan in place ot CrossAbove/CrossBelow per a suggestion I found at https://ninjatrader.com/support/foru...wizard?t=51795

          Then I ran Strategy Analyzer and manually added the DMA as an orange SMA line to the chart with a -1 displacement to equate with BarsAgo. Now you can see that the Strategy has a 3.43 Max Profit Factor but is actually firing at random times that seem to have little to do with the simple Strategy code. Why would that be?

          Click image for larger version

Name:	A1SMADisplacedCrossoverStrategy_3.png
Views:	188
Size:	989.3 KB
ID:	1050402

          Here is the Strategy code at this point. I am fairly new with C# coding so it is a struggle, but I am committed and want to be successful.

          {
          public class A1SmaDisplacedCrossover : Strategy
          {
          private SMA SMA1;
          private SMA DMA2;

          protected override void OnStateChange()
          {
          if (State == State.SetDefaults)
          {
          Description = @"Enter the description for your new custom Strategy here.";
          Name = "A1SmaDisplacedCrossover";
          Calculate = Calculate.OnPriceChange;
          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;
          SmaPeriod = 13;
          DmaPeriod = 13;
          // Displacment = 1;
          // AddPlot(Brushes.Orange, "SMA");
          }
          else if (State == State.Configure)
          {
          }

          else if (State == State.DataLoaded)
          {
          SMA1 = SMA(Close, Convert.ToInt32(SmaPeriod));
          DMA2 = SMA(Close, Convert.ToInt32(DmaPeriod));
          SMA1.Plots[0].Brush = Brushes.Red;
          DMA2.Plots[0].Brush = Brushes.Blue;
          AddChartIndicator(SMA1);
          AddChartIndicator(DMA2);
          }
          // this code won't run with the lines below added
          // else if(State == State.Historical)
          // {
          // DMA2.Displacement = 1;
          // AddPlot(Brushes.Orange, "DMA2");
          // }
          }

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

          if (CurrentBars[0] < 1)
          return;

          // Set 1
          if (SMA1[0] < DMA2[1])
          {
          EnterLong(Convert.ToInt32(DefaultQuantity), @"Long248");

          }
          // Set 2
          if (SMA1[0] > DMA2[1])
          {
          ExitLong(Convert.ToInt32(DefaultQuantity), @"exitLong", @"Long248");

          }



          }

          #region Properties
          [NinjaScriptProperty]
          [Range(1, int.MaxValue)]
          [Display(Name="SmaPeriod", Order=1, GroupName="Parameters")]
          public int SmaPeriod
          { get; set; }

          [NinjaScriptProperty]
          [Range(1, int.MaxValue)]
          [Display(Name="DmaPeriod", Order=2, GroupName="Parameters")]
          public int DmaPeriod
          { get; set; }
          #endregion

          }
          }


          Comment


            #6
            Hello JohnS52,

            Thank you for your reply.

            Hello Jesse - I want to visually see the values so I tried adding the Displacement code in State.SetDefaults and received the error message: "The name 'Displacement' does not exist in the current context." I also tried adding it to State.Historical with no success either. So I commented out all the Displacement code. Any suggestions?
            Yes, Displacement is not a property of a strategy, again this is a visual only item which applies to only indicators and really only applies toward manually added indicators. To visualize what your strategy is actually doing you should instead plot these values from the strategy.

            To plot these values from the strategy you would need to add two plots, you can see the syntax for that here: https://ninjatrader.com/support/help...s/?addplot.htm

            After adding the two plots, you could set their values to the values of the indicators being used:

            Code:
            Values[0][0] = SMA(Close, Convert.ToInt32(SmaPeriod))[0];
            Values[1][0] = SMA(Close, Convert.ToInt32(DmaPeriod))[1];
            As you used 1 BarsAgo in your code, the plot will be set to that value or what you actually are using in code.


            Then I changed the code to GreaterThan/LessThan in place to CrossAbove/CrossBelow per a suggestion I found at https://ninjatrader.com/support/foru...wizard?t=51795

            Then I ran Strategy Analyzer and manually added the DMA as an orange SMA line to the chart with a -1 displacement to equate with BarsAgo. Now you can see that the Strategy has a 3.43 Max Profit Factor but is actually firing at random times that seem to have little to do with the simple Strategy code. Why would that be?
            When comparing manually added items, this may not align with what the script is actually doing. I would suggest to plot the result and then retest to see what the outcome is when using the specific values you are in code.


            I look forward to being of further assistance.
            JesseNinjaTrader Customer Service

            Comment


              #7
              Thanks so much. That worked perfectly. The strategy needs some tweaking but is basically effective. I am attaching the code in case anyone wants to know. Click image for larger version

Name:	A2SMADisplacerStrategy.png
Views:	166
Size:	83.3 KB
ID:	1050722[ATTACH]n1050723[/ATTACH]

              Comment

              Latest Posts

              Collapse

              Topics Statistics Last Post
              Started by PowersCamille, Today, 09:18 PM
              0 responses
              1 view
              0 likes
              Last Post PowersCamille  
              Started by vtdawsa, Today, 09:15 PM
              0 responses
              1 view
              0 likes
              Last Post vtdawsa
              by vtdawsa
               
              Started by StockJock, Today, 08:52 PM
              0 responses
              2 views
              0 likes
              Last Post StockJock  
              Started by rmicalet, Today, 07:10 PM
              0 responses
              4 views
              0 likes
              Last Post rmicalet  
              Started by cincai, Today, 07:02 PM
              0 responses
              2 views
              0 likes
              Last Post cincai
              by cincai
               
              Working...
              X