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

sum close in a series

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

    sum close in a series

    Hello,

    I try to Sum all closes between
    (ChartBars.GetBarIdxByX(chartControl, cursorPointX) - ChartBars.ToIndex);

    I cant figure out how to do it.
    Anyone can tell me?

    int bar = Math.Abs(ChartBars.GetBarIdxByX(chartControl, cursorPointX) - ChartBars.ToIndex);
    double volume = Volume.GetValueAt(bar);
    double close = Close.GetValueAt(ChartBars.GetBarIdxByX(chartContr ol, cursorPointX));

    for (double i = close; i >= ChartBars.ToIndex; i++);
    double[] doubleArray = {close};
    double sum1 = doubleArray.Sum();
    {close}; always return answer from double close = Close.GetValueAt(ChartBars.GetBarIdxByX(chartContr ol, cursorPointX));
    If i input i it returns i is not define.
    I dont know how to use For loop to gather all the closes and sum them. It seems to me something is missing.

    I would also like to reduce the number of decimals:
    Can i use
    {
    // Round CurrentValue to one decimal place
    FormatDecimals
    =
    1
    ;
    }
    }
    protected
    override
    void
    OnMarketData(MarketDataEventArgs
    marketDataUpdate)
    {
    CurrentValue
    =
    marketDataUpdate.Price;
    }

    problem i get error message class member declaration expected

    Ty
    Last edited by frankduc; 05-16-2019, 07:38 AM.

    #2
    Hello frankduc,
    Thanks for your post.

    Where in the code are you trying to sum all of the closes of the series? (ie. OnBarUpdate(), OnRender(), etc.)

    Is this a custom Market Analzyer Column script?
    Josh G.NinjaTrader Customer Service

    Comment


      #3
      The way i see it it seems to be OnRender.

      int bar = Math.Abs(ChartBars.GetBarIdxByX(chartControl, cursorPointX) - ChartBars.ToIndex);
      double volume = Volume.GetValueAt(bar);
      double close = Close.GetValueAt(ChartBars.GetBarIdxByX(chartContr ol, cursorPointX));
      for (double i = close; i >= ChartBars.ToIndex; i++);
      double[] doubleArray = {close};
      double sum1 = doubleArray.Sum();

      The way i understand it and im a newbie in coding.
      int bar = Math.Abs(ChartBars.GetBarIdxByX(chartControl, cursorPointX) - ChartBars.ToIndex);
      include all the bars between (ChartBars.GetBarIdxByX(chartControl, cursorPointX) - ChartBars.ToIndex);

      double close = Close.GetValueAt(ChartBars.GetBarIdxByX(chartContr ol, cursorPointX));
      Give me the closeprice at cursorPointX

      I want to Sum all the closeprices included in all the bars between (ChartBars.GetBarIdxByX(chartControl, cursorPointX) - ChartBars.ToIndex);

      I have been told to use For to gather all the closes in bar but cant figure how to do it.According to tutorial you can gather close by
      // loop through only the rendered bars on the chart
      for
      (
      int
      barIndex
      =
      ChartBars.FromIndex;
      barIndex
      <=
      ChartBars.ToIndex;
      barIndex++)

      I'm stuck i dont know what to do.
      Any pointers? I have to be able to manipulate the price, volume, bars of determined series to code my formulas. I want to know how to use For loop to manipulate those series of data.

      Thank you


      namespace NinjaTrader.NinjaScript.Indicators
      {
      public class SampleDisplayBarsAgo : Indicator
      {
      private SharpDX.Direct2D1.Brush textBrush;

      protected override void OnStateChange()
      {
      if (State == State.SetDefaults)
      {
      Description = @"Enter the description for your new custom Indicator here.";
      Name = "SampleDisplayBarsAgo";
      Calculate = Calculate.OnBarClose;
      IsOverlay = true;
      DisplayInDataBox = true;
      DrawOnPricePanel = true;
      DrawHorizontalGridLines = true;
      DrawVerticalGridLines = true;
      PaintPriceMarkers = true;
      ScaleJustification = NinjaTrader.Gui.Chart.ScaleJustification.Right;
      //Disable this property if your indicator requires custom values that cumulate with each new market data event.
      //See Help Guide for additional information.
      IsSuspendedWhileInactive = true;

      }
      else if (State == State.Historical)
      {
      //add event handler
      if (ChartControl != null) ChartControl.MouseUp += ChartControl_MouseUp;
      }
      else if (State == State.Terminated)
      {
      //remove event handler
      if (ChartControl != null) ChartControl.MouseUp -= ChartControl_MouseUp;
      }
      }

      private void ChartControl_MouseUp(object sender, MouseButtonEventArgs e)
      {
      //cause a refresh to poll after up click
      ForceRefresh();
      }

      protected override void OnBarUpdate()
      {
      //Add your custom indicator logic here.
      }

      public override void OnRenderTargetChanged()
      {
      textBrush = Brushes.Red.ToDxBrush(RenderTarget);
      }

      protected override void OnRender(ChartControl chartControl, ChartScale chartScale)
      {
      if (IsInHitTest) return;
      if (ChartBars != null)
      {
      //get the X and Y point of the cursor and convert them to pixels
      int cursorPointX = ChartingExtensions.ConvertToHorizontalPixels(chart Control.MouseDownPoint.X, chartControl);
      int cursorPointY = ChartingExtensions.ConvertToVerticalPixels(chartCo ntrol.MouseDownPoint.Y, chartControl);

      //get the right most bar ToIndex, and subtract the current cursor point to get a BarsAgo
      int bar = Math.Abs(ChartBars.GetBarIdxByX(chartControl, cursorPointX) - ChartBars.ToIndex);
      double volume = Volume.GetValueAt(bar);
      double close = Close.GetValueAt(ChartBars.GetBarIdxByX(chartContr ol, cursorPointX));

      for (double i = close; i >= ChartBars.ToIndex; i++);
      double[] doubleArray = {close};
      double sum1 = doubleArray.Sum();

      double newbar = (bar/2.62)+bar;
      double newbar1 = bar;

      //define a font
      NinjaTrader.Gui.Tools.SimpleFont simpleFont = chartControl.Properties.LabelFont ?? new NinjaTrader.Gui.Tools.SimpleFont("Arial", 12);

      // the advantage of using a SimpleFont is they are not only very easy to describe
      // but there is also a convenience method which can be used to convert the SimpleFont to a SharpDX.DirectWrite.TextFormat used to render to the chart
      // Warning: TextFormat objects must be disposed of after they have been used
      SharpDX.DirectWrite.TextFormat textFormat1 = simpleFont.ToDirectWriteTextFormat();

      // Once you have the format of the font, you need to describe how the font needs to be laid out
      // Here we will create a new Vector2() which draws the font according to the to top left corner of the chart (offset by a few pixels)
      SharpDX.Vector2 upperTextPoint = new SharpDX.Vector2(cursorPointX, cursorPointY);
      // Warning: TextLayout objects must be disposed of after they have been used

      //make a string of text
      string textString = "BarsAgo:" + bar.ToString() + " \n 3.27: " + ((bar / 3.27)+bar).ToString()

      SharpDX.DirectWrite.TextLayout textLayout1 = new SharpDX.DirectWrite.TextLayout(NinjaTrader.Core.Gl obals.DirectWriteFactory, textString, textFormat1, ChartPanel.X + ChartPanel.W, textFormat1.FontSize);

      // With the format and layout of the text completed, we can now render the font to the chart
      RenderTarget.DrawTextLayout(upperTextPoint, textLayout1, textBrush, SharpDX.Direct2D1.DrawTextOptions.NoSnap);

      }

      Comment


        #4
        frankduc,

        What are you trying to accomplish here specifically? Why not just use the primary price series to get the sum of the closes?

        Code:
        private double sumOfCloses;
        protected override void OnBarUpdate()
        {
            sumOfCloses += Close[0];[COLOR=#008000]//sum of all closes in the primary price series[/COLOR]
            Print(sumOfCloses.ToString("N1"));[COLOR=#008000]//would format the price to one decimal[/COLOR]
        }
        Is there a reason you need to use OnRender() to get the closing values? Do you want to get the sum of the Closes for only the bars that are rendered on your chart, or every close in the price series?
        Last edited by NinjaTrader_JoshG; 05-16-2019, 11:55 AM.
        Josh G.NinjaTrader Customer Service

        Comment


          #5
          As you can see in the chart there is 480 barsago from the top of the trend to the beginning of the chart. I want to SUM all close prices. In fact its a 400 volumes chart bars. I want to SUM each close of each 480 bars. Than use it in my calculation (formulas) and create an arithmetic mean by dividing the total sum of the prices by the number of bars.

          More i want to be able to enlarge the number of bars. Make a cumulative average of the numbers of bars i want by using the price. Like 2.0 = 720 bars i want to be able to create a cumulative average of those 720 bars but i need the price and need to know how to gather and sum those segment of data.

          thank you
          Attached Files

          Comment


            #6
            frankduc,

            My snippet would allow you to increase/decrease the number of bars on the chart and get the cumulative total of closes for the entire series. You could easily divide that value by the number of bars being used to get your average. Without setting the days to load directly(in the Data Series properties) for this amount of bars though I would not have any information on how to increase the number of bars in the series.

            If your intent is to have say 960 bars on your chart and divide that into two groups of 480 you could do that with a 'for' loop by iterating through the bars you are interested in.

            All of this assumes that you can use OnBarUpdate() for your final goal. Nothing you have told me leaves me to believe you need to use OnRender().


            Josh G.NinjaTrader Customer Service

            Comment


              #7
              I want the Sum of all closes for that specific index. int bar = Math.Abs(ChartBars.GetBarIdxByX(chartControl, cursorPointX) - ChartBars.ToIndex);

              But i only can get the Close for the cursor pointX with the getvalueat method double close = Close.GetValueAt(ChartBars.GetBarIdxByX(chartContr ol, cursorPointX));

              There must be a way a method to Sum all the closes in the index.

              Anyway if i do this

              int bar = Math.Abs(ChartBars.GetBarIdxByX(chartControl, cursorPointX) - ChartBars.ToIndex);
              double volume = Volume.GetValueAt(bar);
              double close = Close.GetValueAt(ChartBars.GetBarIdxByX(chartContr ol, cursorPointX));
              double close1 = Close.GetValueAt(ChartBars.ToIndex);

              double[] doubleArray = {close,close1};
              double sum1 = doubleArray.Sum();

              sum1 is equal to the price at cursoX + price at
              ChartBars.ToIndex

              I just need to get all the closes between them.

              Your code snippet allow to sum all the closes in the chart not specifically the index.
              As for enlarging the index is there anyone who made something similar i can inspire or copy?
              Im not sure anyway where to put the code to make it work.

              Thank you
              Last edited by frankduc; 05-17-2019, 08:42 AM.

              Comment


                #8
                frankduc,

                If you want to iterate over ALL of the bars in the series up to the point where you clicked you would need to use a Price Series like the previous snippet. As a hint, if you wanted to iterate over all the VISIBLE bars on the chart up to the point of where you clicked you could do something similar to the following snippet:

                Code:
                protected override void OnRender(ChartControl chartControl, ChartScale chartScale)
                {
                    Point cursorPoint = chartControl.MouseDownPoint;
                    int x = (int)cursorPoint.X;
                    int clickedBarIndex = ChartBars.GetBarIdxByX(chartControl, x);
                
                    double sumOfCloses = 0;
                    double avgClose = 0;
                
                    for (int i = 0; i <= clickedBarIndex; i++)
                    {
                        sumOfCloses += Bars.GetClose(i);
                        avgClose = sumOfCloses / (clickedBarIndex+1);
                    }
                
                    Print("The average close from the first visible bar on the chart to where I clicked was : "+avgClose);
                }
                Josh G.NinjaTrader Customer Service

                Comment


                  #9
                  Sorry don't want to abuse but why i always get an error message saying (i) dont exist in the context.

                  int bar = Math.Abs(ChartBars.GetBarIdxByX(chartControl, cursorPointX) - ChartBars.ToIndex);
                  double volume = Volume.GetValueAt(bar);
                  double close = Close.GetValueAt(ChartBars.GetBarIdxByX(chartContr ol, cursorPointX));
                  int clickedBarIndex = ChartBars.GetBarIdxByX(chartControl, cursorPointX);

                  double Closes = 0;
                  for (int i = 0; i <= clickedBarIndex; i++);
                  {
                  double[] doubleArray = {i};
                  double sum1 = doubleArray.Sum();
                  }


                  According to you its impossible to get the Closes using For loop in that form? I thought i could simply use
                  double[] doubleArray = {i}; and all the closes would be included in doubleArray and than i sum and thats it.
                  Something sure im learning even if i dont get what i want.
                  Last edited by frankduc; 05-17-2019, 12:52 PM.

                  Comment


                    #10
                    frankdux,

                    why i always get an error message saying (i) dont exist in the context
                    This is a generic C# error. I suggest searching the web for why you are getting that error when creating an array. I also suggest taking a look at the NinjaScript option for creating custom data structures, Series<t> .

                    Series<t> -- https://ninjatrader.com/support/help...s/?seriest.htm

                    According to you its impossible
                    I did not say any other method was impossible. These are the only two ways that I see would be easily accomplished through NinjaScript.

                    I thought i could simply use
                    double[] doubleArray = {i}; and all the closes would be included in doubleArray and than i sum and thats it.
                    I am not sure why you would think that. Looks to me like you are trying to create an array with bar indexes, but something isnt right there. That said, I do not work with arrays on a regular basis so you would need to go check out some C# resources to find out how to do this correctly. I also suggest looking at the Series<t> objects at the above link.
                    Last edited by NinjaTrader_JoshG; 05-17-2019, 02:04 PM.
                    Josh G.NinjaTrader Customer Service

                    Comment


                      #11
                      I did it! It works thank you for the info.

                      Now like i said i try to enlarge the scope of the index. The index is int bar = Math.Abs(ChartBars.GetBarIdxByX(chartControl, cursorPointX) - ChartBars.ToIndex);

                      All the data from cursorPointX to the beginning of the chart.

                      In the indicator there is a line : int cursorPointY = ChartingExtensions.ConvertToVerticalPixels(chartCo ntrol.MouseDownPoint.Y, chartControl);

                      I just realize that Y only give you the close of where you click. Right?

                      I think im not clear what i meant to do is to create a CMA (cumulative moving average only for the index).

                      So i could use the CMA

                      protected override void OnBarUpdate()
                      {
                      sum += Input[0];

                      Value[0] = sum / (CurrentBar + 1);
                      }


                      Is CurrentBar by default number of bars? Cause sum / by currentBar = the CMA
                      So the Input should be the close price?

                      By the way i included the CMA in my indicator it give at the end the result of the CMA but its not drawing the line. I think its because of


                      #region Properties

                      [Browsable(false)]
                      [XmlIgnore]
                      public Series<double> CumulativeMovingAverage
                      {
                      get { return Values[0]; }
                      }
                      #endregion

                      I get an error message :

                      class, delegate, enum, interface, struct expected
                      type name expected

                      any idea why?
                      Last edited by frankduc; 05-20-2019, 12:58 PM.

                      Comment


                        #12
                        frankduc,

                        What is cursorPointY?
                        That is the Y-Coordinate of where your mouse clicked and reflects a value on the Y-Axis.

                        Is CurrentBar by default volume?
                        No, CurrentBar reflects a bar index. It does not have a concept of a bar type or period, including Volume.

                        So the Input should be the close price?
                        I am not certain on what the logic of your code should be doing. If "Input[0]" represents a user input I am not sure that would be the same thing as the math in my example.
                        Josh G.NinjaTrader Customer Service

                        Comment


                          #13
                          How do i create another position in the chart like CursorX ? Lets say a Point Z.

                          I want to be able to create an average between 200 bars before Cursor X and the end of the chart. So i can get other positions in the chart.

                          int clickedBarIndex = (ChartBars.GetBarIdxByX(chartControl, Position Z)); for exemple
                          int clickedBarIndex1 = (ChartBars.GetBarIdxByX(chartControl, Position A))
                          int clickedBarIndex 2= (ChartBars.GetBarIdxByX(chartControl, Position B))


                          and manipulate the data to make different calculations base on position.

                          Like dividing any uptrend in the chart by a previous opposite downtrend.

                          Thank you

                          Comment


                            #14
                            frankduc,

                            Typically a "Z Position" would only be used in a 3D space and I am not really sure how you would add an Z-Coordinate to a button click.

                            If the intent it to get a second point aside from where you the user clicked that would be up to you as I do not have much advice for that one. It would likely require a second click to collect a second point or you would need to do some fancy math to find the second point you wanted.

                            Josh G.NinjaTrader Customer Service

                            Comment


                              #15
                              Would it be possible if i used something like barsback or barsperiod. There must be a method to count the bars?

                              Lets say i want a pointZ from 200 bars before cursorX

                              That would be int clickedBarIndex = ((ChartBars.GetBarIdxByX(chartControl, cursorPointX))/ 2.0) +
                              (ChartBars.GetBarIdxByX(chartControl, cursorPointX) "theorically"

                              that would equal the number of bars , lets say 200 bars

                              Than some NT method i dont know yet would count minus 300 bars from CursorX. 300 bars back from cursorX gives PointZ

                              Than i can apply

                              int bar = Math.Abs(ChartBars.GetBarIdxByX(chartControl, cursorPointX) -
                              (ChartBars.GetBarIdxByX(chartControl, PointZ)

                              );

                              Cause if i cant set limitation to the downtrend and uptrend zone on the chart my calculation cant happen and my indicator goes to the trash.
                              Maybe using hours (divide period between 10am to 10:30 / 9am to 10am

                              ty
                              Last edited by frankduc; 05-21-2019, 07:56 AM.

                              Comment

                              Latest Posts

                              Collapse

                              Topics Statistics Last Post
                              Started by junkone, Today, 11:37 AM
                              0 responses
                              1 view
                              0 likes
                              Last Post junkone
                              by junkone
                               
                              Started by quantismo, 04-17-2024, 05:13 PM
                              5 responses
                              34 views
                              0 likes
                              Last Post NinjaTrader_Gaby  
                              Started by proptrade13, Today, 11:06 AM
                              1 response
                              5 views
                              0 likes
                              Last Post NinjaTrader_Clayton  
                              Started by love2code2trade, 04-17-2024, 01:45 PM
                              4 responses
                              34 views
                              0 likes
                              Last Post love2code2trade  
                              Started by cls71, Today, 04:45 AM
                              2 responses
                              10 views
                              0 likes
                              Last Post eDanny
                              by eDanny
                               
                              Working...
                              X