Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

6281 operations just after starting the strategy

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

    6281 operations just after starting the strategy

    Hello, good morning, I have designed a strategy that every time I activate it, it shows me on the graph all the operations in a continuous way (that is, without the condition being met, it enters the market, goes short, profit or stop, re-enters the market and so on from the beginning of the graph that I have configured) and in the control center it shows me the total number of operations (today for example it shows me 6281) that the strategy would have carried out.
    Once I activate the strategy it synchronizes, and then it stops executing operations and starts executing the strategy in a correct way.
    How can I avoid this problem???
    I have tried to change the Start behavior and the result is the same.
    Thank you very much​
    Attached Files

    #2
    Hello r68cervera,

    By operations do you mean orders? If so the images shown appears to be the historical backtest portion of the chart, your logic is executed for each bar of historical data so if the entry condition becomes true it will submit a historical entry.

    Comment


      #3
      Hi Jesse, thanks for your reply. Yes, they are orders, but can't that backtest be removed???
      Because I have another identical strategy in a different time frame and it doesn't do this for me.
      I've looked at the possible differences between one and the other and I haven't seen anything.
      Thank you very much.
      Regards​

      Comment


        #4
        Hello r68cervera,

        Yes you would have to disable the strategy from trading historically in its logic.

        Each strategy will work differently as they are programmed differently. To know specifically why its different you could add prints in both strategies and see how they process using the output.

        Comment


          #5
          Hi Jesse, thanks for your reply, but I can't find anything. As I was saying, I have two strategies that do practically the same thing, I use one to go long when it exceeds a certain number of contracts and the other goes short when it exceeds a certain number of contracts, and I can't find any difference.



          protected override void OnBarUpdate()
          {
          //Add your custom strategy logic here.
          if (CurrentBars[0] < 1)
          return;
          BuySellVolume().Update();

          double volumenDeVentas = buySellVolume.Sells[1];

          if (volumenDeVentas < 250)
          {
          EnterShort();

          }
          }


          ​protected override void OnStateChange()

          Slippage = 0;
          StartBehavior = StartBehavior.WaitUntilFlat;
          TimeInForce = TimeInForce.Gtc;​

          Comment


            #6
            Hello r68cervera,

            The code you have shown can work both historically and in realtime. Keep in mind that running two strategies at the same time can cause incorrect positions or sync issues, if you plan to go long and short in the same market you should make a single strategy that does both.
            \You can see examples of using the State and MarketPosition in the following links.

            Join the official NinjaScript Developer Community for comprehensive resources, documentation, and community support. Build custom indicators and automated strategies for the NinjaTrader platforms with our extensive guides and APIs.

            Join the official NinjaScript Developer Community for comprehensive resources, documentation, and community support. Build custom indicators and automated strategies for the NinjaTrader platforms with our extensive guides and APIs.

            Comment


              #7
              Hola Jesse, gracias por tu respuesta.
              Después de leer los link que me has mandado, he probado alguna cosa. He añadido las líneas dentro del OnBarUpdate()

              protected override void OnBarUpdate()
              {

              // only process real-time OnBarUpdate events
              if (State == State.Historical)
              return;
              y entonces no pinta las órdenes históricas en el gráfico, y veo que aparece la estrategia sincronizada, pero entonces cada vez que empieza una barra me ejecuta una orden de entrada al mercado, ya que cuando empieza la barra se cumple la lógica

              // Acceso al volumen de ventas actualizado de BuySellVolume
              // en la linea de abajo tenía puesto buySellVolume.Sells[0] y lo he cambiado por 1 para ver q ocurre
              double volumenDeVentas = buySellVolume.Sells[1];

              if (volumenDeVentas < 250)
              {
              EnterShort();

              }

              a pesar de tener puesto en el código y en la configuración de la estrategia
              Calculate = Calculate.OnBarClose;

              muchas gracias
              un saludo​

              Comment


                #8
                Hi Jesse, thanks for your reply.
                After reading the links you sent me, I tried a few things. I added the lines inside the OnBarUpdate()

                protected override void OnBarUpdate()
                {

                // only process real-time OnBarUpdate events
                if (State == State.Historical)
                return;
                and then it doesn't show the historical orders on the chart, and I see that the synchronized strategy appears, but then every time a bar starts it executes an order to enter the market, since when the bar starts the logic is fulfilled

                // Access to the updated sales volume of BuySellVolume
                // in the line below I had buySellVolume.Sells[0] and I changed it to 1 to see what happens
                double salesVolume = buySellVolume.Sells[1];

                if (salesVolume < 250)
                {
                EnterShort();

                }

                despite having it in the code and in the strategy configuration
                Calculate = Calculate.OnBarClose;

                thank you very much
                regards​

                Comment


                  #9
                  Hello r68cervera,

                  You can use a Print to see why the condition is becoming true, an order will be placed as long as the condition is true. You may need to modify the entry condition to be more specific if it is entering on every bar.

                  Comment


                    #10
                    Hi Jesse, thanks for your reply. I'll tell you about the changes I've made.

                    1- By putting the code inside OnBarUpdate() if (State == State.Historical) return;

                    it no longer shows all the historical orders on the chart, every time I start the strategy it executes an entry order, but ONLY when I start the strategy, and then it continues to work correctly.

                    2- To see something in the OUTPUT, I put the following orders inside State.SetDefaults

                    TraceOrders = true;
                    PrintTo = PrintTo.OutputTab1;

                    and in the OUTPUT it didn't write anything

                    3- and inside OnBarUpdate()
                    if (SalesVolume < 250)
                    {
                    EnterShort();
                    PrintTo = PrintTo.OutputTab1;
                    }
                    and he wrote to me in the OUTPUT

                    01/27/2025 7:53:50 Strategy 'EstComGraf1000200/296401026': Entered internal SetStopTarget() method: Type=Stop FromEntrySignal='' Mode=Ticks Value=80 IsSimulatedStop=False IsMarketIfTouched=False
                    Enabling NinjaScript strategy 'EstComGraf1000200/296401026' : On starting a real-time strategy - StartBehavior=WaitUntilFlat EntryHandling=All entries EntriesPerDirection=1 StopTargetHandling=Per entry execution ErrorHandling=Stop strategy, cancel orders, close positions ExitOnSessionClose=True / triggering 30 seconds before close SetOrderQuantityBy=Strategy ConnectionLossHandling=Recalculate DisconnectDelaySeconds=10 CancelEntriesOnStrategyDisable=False CancelExitsOnStrategyDisable=False Calculate=On bar close IsUnmanaged=False MaxRestarts=4 in 5 minutes
                    01/27/2025 7:54:38 Strategy 'EstComGraf1000200/296401026': Entered internal SubmitOrderManaged() method at 01/27/2025 7:54:38: BarsInProgress=0 Action=SellShort OrderType=Market Quantity=1 LimitPrice=0 StopPrice=0 SignalName='' FromEntrySignal=''

                    which doesn't help me much at the moment, I'll keep looking for something
                    thank you very much​

                    Comment


                      #11
                      Hello r68cervera,

                      PrintTo only changed what output window Print statements go to and won't output anything specific, you don't need to use that. You need to use Print to output text or values to the window.

                      Join the official NinjaScript Developer Community for comprehensive resources, documentation, and community support. Build custom indicators and automated strategies for the NinjaTrader platforms with our extensive guides and APIs.

                      Comment


                        #12
                        Hi Jesse, thanks for your reply and sorry for having made a mistake between Print and Printto
                        I'm going to try to explain myself because this is a bit complicated for me, and right now with the tests I've done I don't really know where to go

                        When I put

                        if (State == State.Historical) return;

                        ​27/01/2025 21:07:30 Strategy 'EstComGraf1000200/296401026': Entered internal SetStopTarget() method: Type=Target FromEntrySignal='' Mode=Ticks Value=40 IsSimulatedStop=False IsMarketIfTouched=False
                        27/01/2025 21:07:30 Strategy 'EstComGraf1000200/296401026': Entered internal SetStopTarget() method: Type=Stop FromEntrySignal='' Mode=Ticks Value=80 IsSimulatedStop=False IsMarketIfTouched=False
                        Enabling NinjaScript strategy 'EstComGraf1000200/296401026' : On starting a real-time strategy - StartBehavior=WaitUntilFlat EntryHandling=All entries EntriesPerDirection=1 StopTargetHandling=Per entry execution ErrorHandling=Stop strategy, cancel orders, close positions ExitOnSessionClose=True / triggering 30 seconds before close SetOrderQuantityBy=Strategy ConnectionLossHandling=Recalculate DisconnectDelaySeconds=10 CancelEntriesOnStrategyDisable=False CancelExitsOnStrategyDisable=False Calculate=On bar close IsUnmanaged=False MaxRestarts=4 in 5 minutes

                        El volumen de ventas es : 0
                        27/01/2025 21:07:39;21143;21148,75;21137;21142;0


                        27/01/2025 21:07:39 Strategy 'EstComGraf1000200/296401026': Entered internal SubmitOrderManaged() method at 27/01/2025 21:07:39: BarsInProgress=0 Action=SellShort OrderType=Market Quantity=1 LimitPrice=0 StopPrice=0 SignalName='' FromEntrySignal=''

                        El volumen de ventas es : 591
                        27/01/2025 21:07:53;21141,75;21141,75;21130,25;21134,75;591

                        it doesn't put any order on the chart, but as soon as I start the strategy the first candle tells me that the value is 0, and then it puts an order to the market, then from there the strategy works correctly




                        y si pongo if (State == State.Historical) return;

                        27/01/2025 10:07:15 Strategy 'EstComGraf1000200/296401026': Entered internal SubmitOrderManaged() method at 27/01/2025 10:07:15: BarsInProgress=0 Action=SellShort OrderType=Market Quantity=1 LimitPrice=0 StopPrice=0 SignalName='' FromEntrySignal=''
                        27/01/2025 10:07:15 Strategy 'EstComGraf1000200/296401026': Ignored SubmitOrderManaged() method at 27/01/2025 10:07:15: BarsInProgress=0 Action=SellShort OrderType=Market Quantity=1 LimitPrice=0 StopPrice=0 SignalName='Sell short' FromEntrySignal='' Reason='Exceeded entry signals limit based on EntryHandling and EntriesPerDirection properties'​


                        When I activate the strategy, it shows me the entire order history on the chart, and places a final order, and then when it closes, the strategy is already activated and starts working correctly.​

                        I'm going to look Reason='Exceeded ​ ........


                        Thank you very much
                        Regards​

                        Comment


                          #13
                          Hello r68cervera,

                          The statement if (State == State.Historical) return; means that any bar marked as historical will return meaning code after that point won't be executed for that bar. That is why no trades show up.

                          In realtime when the value is 0 the entry happens because that is what you asked it to do.

                          double salesVolume = buySellVolume.Sells[1];

                          if (salesVolume < 250)
                          {​

                          If the value is 0 that is less than 250 so the condition is true.

                          The warning Reason='Exceeded entry signals limit based on EntryHandling and EntriesPerDirection properties'​ means you have multiple entry conditions happening in the same direction. On the next bar if you try to enter in the same direction again because the value is 0 again then it will be ignored because you already entered once and that was the max set in the properties. You have to wait for that to exit before doing another entry.

                          Comment


                            #14
                            Hi Jesse, thanks for the answer, but there is one thing I don't understand.
                            1- When I put the statement
                            if (State == State.Historical)
                            and activate the strategy, it sends me an order and it is executed (against the simulated or real account), because the entry condition is met, but then once the order has been executed, (it only executes it once) whether it is profit or stop, the strategy works correctly.

                            2- If I don't put the statement
                            if (State == State.Historical)
                            it shows all the orders on the chart, but nevertheless, the strategy does not enter the market until the condition is met.
                            Thank you very much and thank you for your understanding and patience​

                            Comment


                              #15
                              Hi this code maybe help you
                              .pTimeToExecute (1 REALTIME, 2 HISTORICAL, 3 ALL) is a int property that you can configure from the strategy panel
                              on method OnStateChange()

                              Code:
                              if (State == State.Realtime)
                              {
                              this.IsRealtimeMode = true;
                              Print_Stats("RESUMEN HISTORICO");
                              myPrint("---------------------------------------------------------------------------------------------------------------------------");
                              myPrint("- *** STARTING STRATEGY IN REALTIME *** -");
                              myPrint("---------------------------------------------------------------------------------------------------------------------------");
                              this.EnabledTotrade = ( (this.pTimeToExecute == 1) || (this.pTimeToExecute == 3) );
                              if (this.EnabledTotrade)
                              myPrint(string.Format("- Estrategia en Realtime HABILITADA -"));
                              else
                              myPrint(string.Format("- Estrategia en Realtime INHABILITADA -"));
                              }
                              else if (State == State.Historical)
                              {
                              this.IsRealtimeMode = false;
                              this.EnabledTotrade = ( (this.pTimeToExecute == 2) || (this.pTimeToExecute == 3) );
                              if (this.EnabledTotrade)
                              myPrint(string.Format("- Estrategia en Historical mode HABILITADA -"));
                              else
                              myPrint(string.Format("- Estrategia en Historical mode INHABILITADA -"));
                              }​
                              in OnBarUpdate()

                              Code:
                                  if (!this.EnabledTotrade) return;

                              Comment

                              Latest Posts

                              Collapse

                              Topics Statistics Last Post
                              Started by NullPointStrategies, Yesterday, 05:17 AM
                              0 responses
                              65 views
                              0 likes
                              Last Post NullPointStrategies  
                              Started by argusthome, 03-08-2026, 10:06 AM
                              0 responses
                              139 views
                              0 likes
                              Last Post argusthome  
                              Started by NabilKhattabi, 03-06-2026, 11:18 AM
                              0 responses
                              75 views
                              0 likes
                              Last Post NabilKhattabi  
                              Started by Deep42, 03-06-2026, 12:28 AM
                              0 responses
                              45 views
                              0 likes
                              Last Post Deep42
                              by Deep42
                               
                              Started by TheRealMorford, 03-05-2026, 06:15 PM
                              0 responses
                              50 views
                              0 likes
                              Last Post TheRealMorford  
                              Working...
                              X