Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

List

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

    List

    Hello
    In the Onbarupdate method I add data to the monthly list
    if (BarsPeriod.BarsPeriodType == BarsPeriodType.Month) and then I want to read it in annual but the list is empty.
    if (BarsPeriod.BarsPeriodType == BarsPeriodType.Year)
    How do I keep the data added to the list?​

    #2
    Hello Gibranes,

    From the given code it is not clear what you are doing in your code, can you post an expanded sample that shows how you are using the list and where it is defined?

    Comment


      #3
      Code:
      public class VariacionAnual : Indicator
          {
              double maxAno;
              double minAno;
              double Apertura;
              double Cierre;
              double RendimientoAnual;
              double variAnual;
              double SumaRendimientoAnual;    
              int Contador=0;
              int Paso=0;
              double smedia;
              double promedio;
              double [] rendimientosMensual=new double[12];
              double [] Desviacion = new double[12];
              double []media1 = new double[12];
              double Sumacuadrado;
              double VolatilidadAnualizada;
              double RatioSharpe;
              int ContadorMes;
              List<double> GuardarVL= new List<double>();
              NinjaTrader.Gui.Tools.SimpleFont myFont = new NinjaTrader.Gui.Tools.SimpleFont("Courier New", 12) { Size = 15, Bold = true };
              
              protected override void OnStateChange()
              {        
                  if (State == State.SetDefaults)
                  {
                      Description                                    = @"Escriba la descripción de su nuevo Indicador personalizado aquí.";
                      Name                                        = "VariacionAnual";
                      //IsVisible = false;
                      IsOverlay = true;
                      Calculate = Calculate.OnPriceChange;
                      AÑOS                = false;
                      
                  }
                  else if (State == State.DataLoaded)
                  {      
                  }        
                  else if (State == State.Configure)
                  {
                    //AddDataSeries(BarsPeriodType.Month, 1);
                    
                  }            
              }
              protected override void OnBarUpdate()
              {                
                if (State != State.Historical)//SOLO HISTORICO
                 return;
                  if (BarsPeriod.BarsPeriodType == BarsPeriodType.Year)//SOLO DATOS ANUALES
               {      
                   Draw.TextFixed(this, "Memsual" , "OBTENER VOLATILIDAD CON MESES",TextPosition.Center,Brushes.Black, myFont, Brushes.Transparent, Brushes.Transparent, 100);
                   ///////////REPRESENTAR AÑOS
                     maxAno = High[0];
                     minAno = Low[0];
                     Apertura= Open[0];
                     Cierre = Close[0];
                     RendimientoAnual = ((Cierre - Apertura)/Apertura) * 100;
                     SumaRendimientoAnual= SumaRendimientoAnual+RendimientoAnual;
                     variAnual = ((maxAno - minAno)/minAno) * 100;
                     double distancia = 105 * TickSize;
                     Draw.Text(this, "Rendimiento" + CurrentBar, String.Format("{0:0.##}",RendimientoAnual), 0, High[0]*distancia , Brushes.Green);
                     Draw.Text(this, "Diferencia" + CurrentBar, String.Format("{0:0.##}",variAnual), 0, Low[0]-distancia, Brushes.Red);    
                     Print (GuardarVL.Count);
                   if (GuardarVL.Count >1)
                  {
                      double lastValue = GuardarVL[GuardarVL.Count - 1];
                      Print("Último valor añadido: " + lastValue);
                  }
               }                
                  
                if (BarsPeriod.BarsPeriodType == BarsPeriodType.Month)//SOLO DATOS MENSUALES
               {      
                   //Draw.TextFixed(this, "Memsual" , "SOLO FUNCIONA CON DATOS MENSUALES",TextPosition.Center,Brushes.Red, myFont, Brushes.Transparent, Brushes.Transparent, 100);            
                  if (CurrentBar<1)
                      return;    
                  ////////////////ETIQUETA AÑOS/// PONER MAS TIEMPO
                  if (AÑOS==true)
                  {
                   if (Bars.GetTime(CurrentBar).Month == 1)
                  {
                      // Dibujar una línea vertical en la fecha actual
                      Draw.VerticalLine(this, "YearLine" + CurrentBar, 0, Brushes.Blue, DashStyleHelper.Solid, 1);
                      double distancia = 1000 * TickSize;
                      double distancia1 = 2000 * TickSize;
                      Draw.Text(this, "VLA" + CurrentBar, String.Format("{0:0.##}",VolatilidadAnualizada)+" VL", 0, High[0] + distancia, Brushes.Black);
                      //Draw.Text(this, "RA" + CurrentBar, String.Format("{0:0.##}",SumaRendimientoAnual)+" RA", 0, High[0] + distancia1, Brushes.Black);
                      GuardarVL.Add(VolatilidadAnualizada);        
                      Print (GuardarVL.Count);
                      Paso=0;
                      ContadorMes=0;
                      SumaRendimientoAnual=0;
                       for (int i = 0; i < 12; i++)
                       {
                      rendimientosMensual[i]=0;
                      Desviacion[i]=0;
                      media1[i]=0;
                      Sumacuadrado=0;
                      smedia=0;
                       }
                  // }
                  }
                  //else
                  //{
                  //    ContadorMes++;
                  //}
                  }//////////FIN ETIQUETA AÑOS
                  // Calcular los valores máximos y mínimos del año            
                     maxAno = High[0];
                     minAno = Low[0];
                     Apertura= Open[0];
                     Cierre = Close[0];
                              
                     variAnual = ((maxAno - minAno)/minAno) * 100;
                     RendimientoAnual = ((Cierre - Apertura)/Apertura) * 100;
                     SumaRendimientoAnual= SumaRendimientoAnual+RendimientoAnual;
                     promedio=SumaRendimientoAnual/12;
                     rendimientosMensual[Paso]=RendimientoAnual;
                     //Print("ASIGNACION "+rendimientosMensual[Paso] + " Paso "+Paso) ;
                     media1[Paso]=RendimientoAnual/12;
                            for (int i = 0; i < Paso; i++)
                          {
                              smedia=media1[i]+smedia;
                          }
                   //REPRESENTACION TEXTO            
                   Draw.Text(this, "Rendimiento" + CurrentBar, String.Format("{0:0.##}",RendimientoAnual), 0, High[0] , Brushes.Green);
                   //Draw.Text(this, "Diferencia" + CurrentBar, String.Format("{0:0.##}",media1[Paso]), 0, Low[0]-2  * TickSize, Brushes.Red);
                   Draw.Text(this, "Diferencia" + CurrentBar, String.Format("{0:0.##}",variAnual), 0, Low[0]-2  * TickSize, Brushes.Red);
                   Draw.TextFixed(this, "Text" , "Promedio: " +String.Format("{0:0.##}",promedio),TextPosition.TopLeft,Brushes.Green, myFont, Brushes.Transparent, Brushes.Transparent, 100);
                   Draw.TextFixed(this, "Text1" , "\nVariacion de minimo a maximo: "+"Poner 390 dias",TextPosition.TopLeft,Brushes.Red, myFont, Brushes.Transparent, Brushes.Transparent, 100);
                  
                   Draw.TextFixed(this, "V", "Rendimiento Anual: "+ String.Format("{0:0.##}",SumaRendimientoAnual), TextPosition.TopRight, Brushes.Green, myFont, Brushes.Transparent, Brushes.Transparent, 100);                            
                    
                   if (Paso==11)//Al empezar por 0 son 12 registros
                   {
                       //Print("Promedio "+promedio);//Es la suma del rendimiento dividido entre 12 meses    
                       promedio=promedio;    
                      // Print ("     ");
                    //Print ("Sincuadrado");
                   for (int i = 0; i < 12; i++)
                   {
                      // Desviacion[i]=rendimientosMensual[i]-promedio;    
                       Desviacion[i]=Math.Pow(rendimientosMensual[i]-promedio,2);    //ELEVAR AL CUADRADO    
                      // Print(Desviacion[i]);
                       Sumacuadrado=Desviacion[i]+Sumacuadrado;
                   }
                   Sumacuadrado=Sumacuadrado/11;
                   Sumacuadrado=Math.Sqrt(Sumacuadrado);
                   VolatilidadAnualizada= Sumacuadrado*Math.Sqrt(12);
                   RatioSharpe=RendimientoAnual/VolatilidadAnualizada;
                   Draw.TextFixed(this, "Volatilidad" , "\n\nVolatilidad Anualizada: "+String.Format("{0:0.##}",VolatilidadAnualizada),TextPosition.TopLeft,Brushes.Blue, myFont, Brushes.Transparent, Brushes.Transparent, 100);
                   Draw.TextFixed(this, "RatioSharpe" , "\n\n\nRatioSharpe (Dividir volatilidad por rentabilidad): "+String.Format("{0:0.##}",RatioSharpe),TextPosition.TopLeft,Brushes.Blue, myFont, Brushes.Transparent, Brushes.Transparent, 100);
                   // Print(VolatilidadAnualizada);
                   }    
                  
                    ++Paso;    
                    }
              }
                  ///////////////////BARINPROGRESS            
          
              #region Poperties    
              [NinjaScriptProperty]
              [Display(Name = "USAR AÑOS", GroupName = "1.0 MTF Parameters", Order = 0)]
              public bool AÑOS
              { get; set; }
               #endregion
          }    
              ///////////////////FIN DEL METODO ONBARUPDATE        
              
          }​

      Comment


        #4
        Hello Gibranes,

        The data won't be kept when changing bar types. I see you have AddDataSeries commented out so the script is running on 1 series which means it can either work the logic for the monthly bars or yearly but not both.

        Comment


          #5
          I do not understand.
          So what would be the solution?​

          Comment


            #6
            Hello Gibranes,

            If you want to use both series at once you would need to use AddDataSeries and use BarsInProgress conditions instead of checking the bars type.

            if(BarsInProgress == 0) // primary
            {
            }
            if(BarsInProgress == 1) // secondary
            {
            }

            Comment


              #7
              Is the value 0 and 1 given based on position?
              else if (State == State.Configure)
              {
              AddDataSeries(BarsPeriodType.Month, 1); //=0
              AddDataSeries(BarsPeriodType.Year, 1);//=1
              }​

              Comment


                #8
                Hello Gibranes,

                the value of BarsInprogress is determined by the series that called OnBarUpdate. In a multi series script the index will change when each series is processing.bars.

                Comment


                  #9
                  If I add two series (monthly and yearly) and my chart opens in daily.
                  which is the main series?

                  if (BarsInProgress == 0) it is daily​

                  Comment


                    #10
                    Hello Gibranes,

                    In that case if your script is running on daily bars the daily bars are the primary or BarsInProgress 0. If the order you added the other 2 series are monthly and yearly then monthly would be BarsInProgress 1 and yearly would be BarsInProgress 2.

                    Comment


                      #11
                      Something is not clear to me, if I have it like this and open my monthly chart
                      Why is “YEAR” printed?
                      else if (State == State.Configure)
                      {
                      AddDataSeries(BarsPeriodType.Month, 1);
                      AddDataSeries(BarsPeriodType.Year, 1);
                      }
                      if(BarsInProgress ==1)
                      {

                      Print(“YEAR”);
                      }​

                      Comment


                        #12
                        Hello Gibranes,

                        Year is printed because you are printing the word year. BarsInProgress 1 would be the monthly series which means that code will get executed, you should type in Month instead so the print matches the series which is being called.

                        In your example it would be

                        Code:
                        if(BarsInProgress ==0)
                        {
                             Print(“DAY”);
                        }​​
                        if(BarsInProgress ==1)
                        {
                             Print(“MONTH”);
                        }​​
                        if(BarsInProgress ==2)
                        {
                             Print(“YEAR”);
                        }​​

                        Comment


                          #13
                          I do not understand this error if I put the chart in monthly it does not give error if I put it in annual.
                          Why does it show in annual if the condition is not met?

                          This line error in CurrentBar--- Draw.Text(this, "VLA" +CurrentBar , String.Format("{0:0.##}",VolatilidadAnualizada)+" VL", 0, High[0] + distancia, Brushes.Black); ​

                          Error al llamar ' OnBarUpdate' método en barra -1: Está accediendo a un índice con un valor que es inválido ya que es fuera de rango. Es decir; tiene acceso a una serie [barsAgo] con un valor de 5 cuando hay sólo 4 barras en la tabla

                          Code:
                          else if (State == State.Configure)
                                      {            
                                          AddDataSeries(BarsPeriodType.Month, 1);            
                                          AddDataSeries(BarsPeriodType.Year, 1);    
                                      }            
                                  }
                          
                                  protected override void OnBarUpdate()
                                  {
                                      if (State != State.Historical)//SOLO HISTORICO
                                     return;    
                                      
                                      if(BarsInProgress ==1)
                                   {                          
                                          int mes =  Times[1][0].Month;
                                          if (mes == 1)
                                          Draw.VerticalLine(this, "YearLine" + CurrentBar, 0, Brushes.Blue, DashStyleHelper.Solid, 1);
                                          if (AÑOS==true)
                                          {
                                          
                                          Paso=0;                
                                          ContadorMes=0;
                                          SumaRendimientoAnual=0;
                                           for (int i = 0; i < 12; i++)
                                         {
                                          rendimientosMensual[i]=0;
                                          Desviacion[i]=0;
                                          media1[i]=0;
                                          Sumacuadrado=0;
                                          smedia=0;    
                                          }
                                                          
                                          Print("MES");
                                          GuardarVL.Add(suma);    
                                          suma++;
                                          
                                         maxAno = High[0];
                                         minAno = Low[0];
                                         Apertura= Open[0];
                                         Cierre = Close[0];    
                                         variAnual = ((maxAno - minAno)/minAno) * 100;
                                         RendimientoAnual = ((Cierre - Apertura)/Apertura) * 100;
                                         SumaRendimientoAnual= SumaRendimientoAnual+RendimientoAnual;
                                         promedio=SumaRendimientoAnual/12;
                                         rendimientosMensual[Paso]=RendimientoAnual;
                                         media1[Paso]=RendimientoAnual/12;
                                                for (int i = 0; i < Paso; i++)
                                              {
                                                  smedia=media1[i]+smedia;
                                              }
                                          //REPRESENTACION TEXTO    
                                        distancia = 1000 * TickSize;    
                                        Draw.Text(this, "VLA" +CurrentBar , String.Format("{0:0.##}",VolatilidadAnualizada)+" VL", 0, High[0] + distancia, Brushes.Black);    
                                        //Draw.Text(this, "Rendimiento" + CurrentBar, String.Format("{0:0.##}",RendimientoAnual),0, High[0] , Brushes.Green);
                                        //Draw.Text(this, "Diferencia" + CurrentBar, String.Format("{0:0.##}",variAnual), 0, Low[0]-2  * TickSize, Brushes.Red);
                                        Draw.TextFixed(this, "Text" , "Promedio: " +String.Format("{0:0.##}",promedio),TextPosition.TopLeft,Brushes.Green, myFont, Brushes.Transparent, Brushes.Transparent, 100);
                                        Draw.TextFixed(this, "Text1" , "\nVariacion de minimo a maximo: "+"Poner 390 dias",TextPosition.TopLeft,Brushes.Red, myFont, Brushes.Transparent, Brushes.Transparent, 100);                
                                        Draw.TextFixed(this, "V", "Rendimiento Anual: "+ String.Format("{0:0.##}",SumaRendimientoAnual), TextPosition.TopRight, Brushes.Green, myFont, Brushes.Transparent, Brushes.Transparent, 100);      
                                      }​

                          Comment


                            #14
                            Hello Gibranes,

                            You need to check and make sure enough data is avaliable before processing, add the following line to the beginning of your OnBarUpdate:

                            protected override void OnBarUpdate()
                            {
                            if(CurrentBars[0] < 1 || CurrentBars[1] < 1 || CurrentBars[2] < 1)
                            return;

                            if (State != State.Historical)//SOLO HISTORICO
                            return;

                            You will also need to make sure you have enough days to load set in the chart to load whatever data you need. ​

                            Comment

                            Latest Posts

                            Collapse

                            Topics Statistics Last Post
                            Started by Geovanny Suaza, 02-11-2026, 06:32 PM
                            0 responses
                            560 views
                            0 likes
                            Last Post Geovanny Suaza  
                            Started by Geovanny Suaza, 02-11-2026, 05:51 PM
                            0 responses
                            325 views
                            1 like
                            Last Post Geovanny Suaza  
                            Started by Mindset, 02-09-2026, 11:44 AM
                            0 responses
                            101 views
                            0 likes
                            Last Post Mindset
                            by Mindset
                             
                            Started by Geovanny Suaza, 02-02-2026, 12:30 PM
                            0 responses
                            547 views
                            1 like
                            Last Post Geovanny Suaza  
                            Started by RFrosty, 01-28-2026, 06:49 PM
                            0 responses
                            547 views
                            1 like
                            Last Post RFrosty
                            by RFrosty
                             
                            Working...
                            X