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

Aparecen operaciones fantasmas en el Backtesting

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

    Aparecen operaciones fantasmas en el Backtesting

    Tengo una estrategia que corre en chart de 162 minutos, pero tanto las entradas como las salidas desde una barra adicional de 1 minuto. Cuando la hago correr en el Backtest o en el modo demo, se me inunda de operaciones fantasmas, operaciones que en el Chart no exisxten ....??
    Como puedo hacer para que en el backtest, o en la demo, me salga corectamente las operaciones y asi poder ver el resultado en el largo tiempo??
    He utilizado de todo lo que esta a mi alcance usando variables para marcar las entradas y salidas, pero las ignora. Position.MarketPosition == MarketPosition.Flat no lo respeta y me marca mas operaciones, IPosition Position tampoco me funciona. Alguien puede decirme como solucionarlo??

    #2
    Hello PeSil,

    Welcome to the NinjaTrader forums!

    What is the exact issue?

    Are there are orders submitted at times you do not expect the orders to submit?

    Are there times you expecting orders but no order is submitted?

    Use prints and TraceOrders to understand the behavior.
    • Print the values of all conditions along with the time of the bar.
    • In Initialize() set TraceOrders to true.
    • Print the order object in OnOrderUpdate()
    • Save the output from the output window after running a backtest and provide this with your next post.
    • Let us know the time of the order that is either expected or unexpected.

    Below is a link to a forum post that demonstrates using prints to understand behavior.
    Chelsea B.NinjaTrader Customer Service

    Comment


      #3
      Gracias Chelsea. Te envio estas imagenes para ilustrar mejor el problema que se me presenta con NinjaTrader7 . En la primera imagen, he marcado con lineas azules y rojas las entradas y salidas que quedaron marcadas de las operaciones en tiempo real de la estrategia.
      En la segunda pantalla, las operaciones corresponde a hacer correr la estrategia con esos datos ya historicos y como puedes apreciar, las salidas de las operaciones, lineas rojas, superan con creces las salidas en real. Lo he hecho asi para ilustrar mejor el problema. Tanto en el Backtest, como en la porcion de los datos historicos al hacer correr la estrategia, los datos de salida no se corresponden con la realidad
      Agradezco me ayuda.
      Click image for larger version

Name:	MNQ 03-20 (162 Min)  2_1_2020_A.jpg
Views:	369
Size:	94.8 KB
ID:	1082648
      Click image for larger version

Name:	MNQ 03-20 (162 Min)  2_1_2020.jpg
Views:	392
Size:	99.8 KB
ID:	1082647

      Comment


        #4
        Hello PeSil,

        Are you asking why historical (backtest) results are different than real-time results?

        This would be due to how historical data is processed.

        Please see the help guide.


        To have orders fill as accurately as possible, add a 1 tick series for intra-bar granularity and submit orders to this secondary series.

        Below is a link to a forum post that provides direction.


        For accuracy with indicator values, use NinjaTrader 8, enable TickReplay, and have Calculate set to On each tick.


        To understand the differences, use prints and print all values used in conditions, print the order object from OnOrderUpdate(), and enable TraceOrders.

        Below is a link to a forum post on using prints.


        And a link to a forum post on comparing results between historical and real-time.
        Citizens of the NinjaTrader Community, A common question we hear from clients is 'why are results from backtest different from real-time or from market replay?'. Live orders are filled on an exchange with a trading partner on an agreed upon price based on market dynamics. Backtest orders are not using these market dynamics.
        Chelsea B.NinjaTrader Customer Service

        Comment


          #5
          Hola ChelseaB definitivamente no he solucionado el problema y me siguen apareciendo operaciones fantasmas, positivas en su gran mayoría, pero que no son reales a la hora de operar en vivo.
          Le paso copia de mi código para que lo pueda ver. Me interesa sabe la razon del porque me aparecen tantas operaciones fantasmas en backtest y en el chart cuando los datos pasan a ser historicos.


          protected override void Initialize()
          {
          CalculateOnBarClose = true;

          Add(PeriodType.Minute, 1);

          SetProfitTarget("110MFI", CalculationMode.Ticks, 60);
          SetStopLoss("110MFI", CalculationMode.Ticks, 365, false);
          }

          /// <summary>
          /// Called on each bar update event (incoming tick)
          /// </summary>
          protected override void OnBarUpdate()
          {
          if (BarsInProgress == 0
          && E != Time[0].Hour)
          {
          E = Time[0].Hour;
          if (Closes[0][0] < Opens[0][0])
          CA = 1;
          else CA = 0;
          ExitLong(1, "110MFI", "110MFI");
          uNAvEZ = 0;
          return;
          }

          if (BarsInProgress == 1)
          {
          #region Control Perdidas
          if(Bars.FirstBarOfSession == true)
          X = 1;
          if(Bars.FirstBarOfSession == false
          && X == 1)
          {
          X = 0;
          C = 0;
          CC = 0;
          if(Time[0].DayOfWeek == DayOfWeek.Sunday)
          CCW = 0;
          }
          #endregion

          if (ToTime(Time[0]) == ToTime(15, 54, 0)
          ||
          Open[-1] > Obj110 + 7 * TickSize
          ||
          Open[-1] <= Lows[0][0]+(Highs[0][0]-Lows[0][0])/100*25
          )
          ExitLong(1, "110MFI", "110MFI");
          if (
          Position.MarketPosition == MarketPosition.Flat
          && Rising(MFI(8)) == true
          && Open[-1] > Open[0]
          && Open[-1] > Lows[0][0]+(Highs[0][0]-Lows[0][0])/100*25
          && CA == 0
          && uNAvEZ == 0
          // && C <= 6
          && CC <= 0
          // && CCW <= 1
          ||
          Position.MarketPosition == MarketPosition.Flat
          && Rising(MFI(8)) == true
          && Open[-1] > Open[0]
          && Open[-1] > Lows[0][0]+(Highs[0][0]-Lows[0][0])/100*25
          && CA == 1
          && uNAvEZ == 0
          && Opens[0][-1] > Lows[0][0]+(Highs[0][0]-Lows[0][0])/100*67
          // && C <= 6
          && CC <= 0
          // && CCW <= 1
          )
          {
          if (ToTime(Time[0]) >= ToTime(15, 45, 0)
          && ToTime(Time[0]) < ToTime(16, 0, 0))
          return;
          EnterLong(1, DefaultQuantity, "110MFI");
          C++;
          uNAvEZ = 1;
          Obj110 = Open[-1];
          }
          }
          //---------------------------------------------------------------------------------------------------

          if (Performance.AllTrades.Count > 0)
          {
          Trade lastTrade = Performance.AllTrades[Performance.AllTrades.Count -1];
          if(Variable0 != Performance.AllTrades.Count)
          {
          Variable0 = Performance.AllTrades.Count;
          if(lastTrade.ProfitPoints + 0 < 0)
          {
          CC++;
          CCW++;
          }else
          {
          CC = 0;
          CCW = 0;
          }
          }
          }

          Comment


            #6
            Hello PeSil,

            Have you added prints or are you writing to file to see what values are different as I have suggested?

            May I have the output from the real-time and historical to compare?
            Chelsea B.NinjaTrader Customer Service

            Comment


              #7
              Buenas tardes ChelseaB
              Creo haber entendido y que sea un problema sin solución. Luego de estudiar muchisimas horas el comportamiento de la estrategia en el Backtest, Demo y en Real. Las diferencias que surgen, sugieren que hay una falta de información en las velas cuando se ejecuta el objetivo “ProfitTarget” en los modos de prueba.

              El error se manifiesta con claridad, cuando trabajamos con estrategias “Multi Timer”, cuando se usa una temporalidad alta para entrar, otra temporalidad baja para salir y el chart en otra temporalidad alta.

              En esas circunstancias, ciertas funciones tales como, el reconocimiento si estamos o no en el mercado Ninja no las reconoce, “Position.MarketPosition == MarketPosition.Long” y por eso comienza a replicar sin control la operación.

              Comment


                #8
                Tambien al tenere dos vias de salida del merado, una por cumplimiento de objetivo al cierre de la vela de temporalidad baja, y el otro por ProfitTarget. En real sale en un momento y en modo de prueba ya sea en Bactest o sobre el Chart, sale distinto.

                Comment


                  #9
                  Hello PeSil,

                  With orders placed to an added 1 tick series for order fill accuracy and with TickReplay enabled for indicators that process in real-time, I would expect the results to be very similar with only slight differences.

                  With the Position, this updates from the order thread and not from the data thread.

                  Any actions dependent on the position should be triggered from OnPositionUpdate() and not from a data driven method.

                  Chelsea B.NinjaTrader Customer Service

                  Comment


                    #10
                    Buen dia ChelseaB
                    Gracias por la indicación de como manejar las Positions, no lo tenia presente. Si, lograba una aproximación mediante el uso de variables, pero ahora voy a usar: protected override void OnPositionUpdate() que es lo correcto, para analizar las salidas o cambios de Positions. Asi como protected override void OnExecution() para analizar las ejecuciones de ordenes, o, asi como protected override void Initialize() protege los parametros que se inician, tambien en las estrategiaspues. Entiendo que cada vez que ocurre un evento, la plataforma ejecuta el objeto correspondiente de dicha estrategia.
                    También agradezco su explicación del orden de ejecución de las diferentes temporalidades en una estrategia multi timer, o multi instrumentos.
                    Ahora si he mejorado bastante mis estrategias en cuanto a los resultados obtenidos entre Bactest y en vivo.
                    Gracias y Saludos cordiales.

                    Comment

                    Latest Posts

                    Collapse

                    Topics Statistics Last Post
                    Started by bmartz, 03-12-2024, 06:12 AM
                    5 responses
                    32 views
                    0 likes
                    Last Post NinjaTrader_Zachary  
                    Started by Aviram Y, Today, 05:29 AM
                    4 responses
                    12 views
                    0 likes
                    Last Post Aviram Y  
                    Started by algospoke, 04-17-2024, 06:40 PM
                    3 responses
                    28 views
                    0 likes
                    Last Post NinjaTrader_Jesse  
                    Started by gentlebenthebear, Today, 01:30 AM
                    1 response
                    8 views
                    0 likes
                    Last Post NinjaTrader_Jesse  
                    Started by cls71, Today, 04:45 AM
                    1 response
                    7 views
                    0 likes
                    Last Post NinjaTrader_ChelseaB  
                    Working...
                    X