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

Need Help with SwingHigh and SwingLow

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

    Need Help with SwingHigh and SwingLow

    All,

    I need some help here.

    Can someone please show me how I can find the number of bars a swing high and a swing low occurred and add those values to the chart?

    I know there are a lot of examples of this in the forum, but for some reason I still cannot get it it work.

    Any help will be appreciated.

    Thanks,

    -Omer

    #2
    Hello omermirza,

    Thank you for your post.

    To clarify, do you mean you're using the built in Swing indicator and you want to know how many bars the latest Swing High or Swing Low plotted over, or how many bars since the last Swing High or Swing Low plots? Could you provide a sample of what you've tried so I have a better idea of what you're attempting to do?

    Thanks in advance; I look forward to assisting you further.
    Kate W.NinjaTrader Customer Service

    Comment


      #3
      Hi Kate,

      It doesn't matter how it's accomplished, with or without the indicator. I'm just trying to count how many bars ago that last swing high occurred as well as the last swing low. Then I want to add those values to my chart indicating "The last swing high was 7 bars ago", or something like that.

      For example, if you look at this chart we can see that the swing low was 14 bars ago and the swing high was 30 bars ago.

      Click image for larger version

Name:	example.PNG
Views:	411
Size:	21.4 KB
ID:	1136969

      Comment


        #4
        Hello omermirza,

        Thank you for your reply.

        There's actually a pair of methods within the Swing indicator that will return the last Swing High or Swing Low within a specific lookback period. If you set the lookback to a pretty high number where there's likely to have been a swing high or swing low, you can use that to print the last swing to the chart. I'm attaching an example indicator that does just that.

        Please let us know if we may be of further assistance to you.
        Attached Files
        Kate W.NinjaTrader Customer Service

        Comment


          #5
          Thank you so much for that Kate! One last thing, I want to take the Swing Low Bars Ago Value and subtract that from the Swing High Bars Ago value and pass that to the Stochastic "K" Value so it dynamically updates. Is this possible?

          Thanks - Omer.

          Comment


            #6
            Hello omermirza,

            Thank you for your reply.

            That would be possible if you call a new instance of the Stochastic indicator each time. Also, keep in mind you can't have a negative value for K.

            So, something like this (assume we have assigned the Swing High Bars ago and Swing Low bars ago values to variables)

            if (SwingLowBarsAgo > SwingHighBarsAgo)
            {
            int BarsAgoDifference = SwingLowBarsAgo - SwingHighBarsAgo;

            // call a new instance of the Stochastics indicator and assign the K value to a variable
            double MyStochasticsValue = Stochastics(PeriodD, BarsAgoDifference, Smooth).K[0];
            }

            Please let us know if we may be of further assistance to you.
            Kate W.NinjaTrader Customer Service

            Comment


              #7
              Thanks - Once I have that, how do I call that in my strategy and add that stochastics to the chart?

              // Set 1
              if (CrossBelow(Stochastics1.K, 80, 1))
              {
              EnterShort(Convert.ToInt32(DefaultQuantity), "");
              }

              // Set 2
              if (CrossAbove(Stochastics1.K, 20, 1))
              {
              ExitShort(Convert.ToInt32(DefaultQuantity), "", "");
              }

              Comment


                #8
                Hello omermirza,

                Thank you for your reply.

                It'd certainly be simplest to set this up in the Strategy Builder because that will add the necessary code to add the Stochastics to the chart for you. Here's an example in code, though:

                Code:
                // create a variable to hold an instance of the Stochastics indicator
                private Stochastics Stochastics1;
                
                protected override void OnStateChange()
                {
                if (State == State.SetDefaults)
                {
                Description = @"Enter the description for your new custom Strategy here.";
                Name = "ExampleAddStochastics";
                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)
                {
                }
                else if (State == State.DataLoaded)
                {
                // assign the instance to our created variable
                Stochastics1 = Stochastics(Close, 7, 14, 3);
                // set plot colors for the Stochastics indicator applied to the chart
                Stochastics1.Plots[0].Brush = Brushes.DodgerBlue;
                Stochastics1.Plots[1].Brush = Brushes.Goldenrod;
                // add the instance of the indicator to a chart
                AddChartIndicator(Stochastics1);
                }
                }
                
                protected override void OnBarUpdate()
                {
                if (BarsInProgress != 0)
                return;
                
                if (CurrentBars[0] < 1)
                return;
                
                // Set 1
                if (CrossBelow(Stochastics1.K, 80, 1))
                {
                }
                // further code goes here.
                
                }
                }
                Please let us know if we may be of further assistance to you.
                Kate W.NinjaTrader Customer Service

                Comment


                  #9
                  HI Kate - I know how to add any indicator to the chart.

                  What I'm asking for is to use the newly created MyStochasticsValue indicator with the updated K value in my strategy. The K value is derived from subtracting the SwingHighBarsAgo from SwingLowBarsAgo.

                  I can't seem to use that Stochastics with my K value or add it to my chart.

                  Here's my code below:

                  #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 AdaptiveCycle : Strategy
                  {

                  private Stochastics Stochastics1;

                  private Swing Swing1;

                  private double numofbars;

                  private int bars, shighbars;

                  private double shigh, slow;



                  protected override void OnStateChange()
                  {
                  if (State == State.SetDefaults)
                  {
                  Description = @"Enter the description for your new custom Strategy here.";
                  Name = "AdaptiveCycle";
                  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;
                  //Strength = 5;
                  }
                  else if (State == State.Configure)
                  {
                  }
                  else if (State == State.DataLoaded)
                  {

                  Stochastics1 = Stochastics(Close, 3, 5, 3);
                  Swing1 = Swing(Close, 10);
                  AddChartIndicator(Stochastics1);

                  }
                  }

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

                  Print("Swing1.SwingHighBar: " + Swing1.SwingHighBar(0, 1, 100));
                  Print("Swing1.SwingLowBar: " + Swing1.SwingLowBar(0,1, 100));

                  if(Swing1.SwingHighBar(0,1,100) > -1)
                  {
                  Draw.TextFixed(this, "HighText", "The last Swing High bar was " + Swing1.SwingHighBar(0,1,100) + " Bars ago", TextPosition.TopRight);
                  }
                  if(Swing1.SwingLowBar(0,1,100) > -1)
                  {
                  Draw.TextFixed(this, "LowRightText", "The last Swing Low bar was " + Swing1.SwingLowBar(0,1,100) + " Bars ago", TextPosition.BottomRight);
                  }

                  shigh = Swing1.SwingHighBar(0, 1, 100);
                  slow = Swing1.SwingLowBar(0, 1, 100);



                  numofbars = (shigh-slow);
                  int cycle = Convert.ToInt32(numofbars);

                  cycle = Math.Abs(cycle);


                  if(Swing1.SwingLowBar(0,1,100) > -1)
                  {
                  Draw.TextFixed(this, "LowText", "Cycle Bars are " + cycle + " Bars", TextPosition.BottomLeft);
                  }

                  //Draw.TextFixed(this, "NinjaScriptInfo", cycle, TextPosition.BottomRight);


                  if (shigh < slow)
                  {
                  //Stochastics1 = Stochastics(Close, 3, cycle, 3);
                  //AddChartIndicator(Stochastics1);

                  // call a new instance of the Stochastics indicator and assign the K value to a variable
                  double MyStochasticsValue = Stochastics(3, cycle, 3).K[0];
                  // print MyStochasticsValue;

                  //AddChartIndicator(MyStochasticsValue);

                  // Set 1
                  if (CrossBelow(MyStochasticsValue.K[0], 80, 1))
                  {
                  EnterShort(Convert.ToInt32(DefaultQuantity), "");
                  }

                  // Set 2
                  if (CrossAbove(MyStochasticsValue.K[0], 20, 1))
                  {
                  ExitShort(Convert.ToInt32(DefaultQuantity), "", "");
                  }



                  }



                  }
                  }
                  }

                  Attached are the errors I get
                  Attached Files

                  Comment


                    #10
                    Essentially I think this section needs to be updated:


                    if (shigh < slow)
                    {


                    // call a new instance of the Stochastics indicator and assign the K value to a variable
                    double MyStochasticsValue = Stochastics(3, cycle, 3).K[0];



                    // Set 1
                    if (CrossBelow(MyStochasticsValue.K[0], 80, 1))
                    {
                    EnterShort(Convert.ToInt32(DefaultQuantity), "");
                    }

                    // Set 2
                    if (CrossAbove(MyStochasticsValue.K[0], 20, 1))
                    {
                    ExitShort(Convert.ToInt32(DefaultQuantity), "", "");
                    }



                    }

                    Comment


                      #11
                      Hello omermirza,

                      Thank you for your reply.

                      If you wish to use your calculated values in a CrossBelow or CrossAbove statement, you would need to save them to a Series<T> variable or a plot (which is also a series), since the Cross methods require a series to calculate. It should be noted that you cannot update the stochastics indicator once it's added to the chart, so if you need that plotted you'd need to plot it from within your strategy.

                      I've created an example using your code that will calculate the new K Value and assigns it to a plot, then plots it as well as lines to show the 20 and 80 points.

                      Please let us know if we may be of further assistance to you.


                      Attached Files
                      Kate W.NinjaTrader Customer Service

                      Comment


                        #12
                        Once again - thank you so much Kate, that's exactly what I wanted. I would have never figured that out myself.

                        Thanks!

                        Comment


                          #13
                          Hi Kate,

                          Quick question - will the K value update while I'm in a trade?

                          Comment


                            #14
                            Hello omermirza,

                            This is Jim responding on behalf of Kate who is out of the office at this time.

                            The CalculatedKValue in Kate's example will update with new bar updates regardless if you are in a trade or not.

                            We look forward to assisting.
                            JimNinjaTrader Customer Service

                            Comment


                              #15
                              Thanks Jim - Let's say I did not want the value to update if I was in a trade, is that possible?

                              Comment

                              Latest Posts

                              Collapse

                              Topics Statistics Last Post
                              Started by rtwave, 04-12-2024, 09:30 AM
                              2 responses
                              20 views
                              0 likes
                              Last Post rtwave
                              by rtwave
                               
                              Started by tsantospinto, 04-12-2024, 07:04 PM
                              5 responses
                              67 views
                              0 likes
                              Last Post tsantospinto  
                              Started by cre8able, Today, 03:20 PM
                              0 responses
                              6 views
                              0 likes
                              Last Post cre8able  
                              Started by Fran888, 02-16-2024, 10:48 AM
                              3 responses
                              49 views
                              0 likes
                              Last Post Sam2515
                              by Sam2515
                               
                              Started by martin70, 03-24-2023, 04:58 AM
                              15 responses
                              115 views
                              0 likes
                              Last Post NinjaTrader_Jesse  
                              Working...
                              X