Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

Stop single instance of strategy

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

    Stop single instance of strategy

    Hello, I am using a single strategy on 3 different charts, I am also using Replikanto. My strategy is set to 3 different session times. I have a daily PNL limit for each, and when it's reached, the strategy uses a CloseAllPositions method using the Account.Flatten(instrumentsToClose); the (NQ 06-24) and a StopStrategy method isStrategyEnabled = false;. My problem is that when these methods are called, it un-enables ALL the other instances of the strategy, all are using the NQ 06-24.

    I've tried to tag the uniqueID ( this.ID) to the stopstrategy for each one I enable, but that didn't seem to work, I re-named and created new strategies for each NQ chart, but that didn't work( all using NQ). I am using the flatten method, because if I use the NinjaTrader.Resource.GuiPositionClose​, the Replikanto follower account does not close the position, it just cancels the SL/TP for strategy and leaves follower order in. If I use a basic ExitShort/Long order, it closes the leader account but adds an opposite position order to the follower account.

    How do I run the same strat for 3 separate sessions, and only stop a single instance when that particular session strat hits my PNL, while also using Replikanto? My work around right now is using AutoIt, to record my mouse XY of the screen, and run a task scheduler that moves the mouse and applies enable strat at certain times.. my strategy session times do not overlap each other. I just want to be able to enable all 3 charts, at say midnight, and they run throughout the day, instead of strat for session 1 hits pnl for 2am-4am and then stops the other two strategies that start at 7am and 830am, I have to come in and enable them again before the next session starts.

    #2
    Hello ryjoga,

    That I am aware of, there isn't a CloseAllPositions() method native to NinjaScript Strategies.

    Is this a custom method that you have written yourself?
    What code is in this custom method?

    Note, that Clicking the Close button on ChartTrader or the SuperDOM or calling Account.Flatten() would disable any running strategies on that isntrument and account.
    Instead, just submit orders in the opposite direction of the position if you would like to close the position without disabling any strategies.
    For example if the position is long 2, send a sell order for a quantity of 2 to flatten the position without disabling strategies.

    If you want to disable a specific strategy instance, call CloseStrategy() from that instance.
    Chelsea B.NinjaTrader Customer Service

    Comment


      #3
      Yes, it's a custom strategy I have written myself.

      The only problem with submitting a sell order to close an opposite buy order, is that I am using replikanto and that will submit a sell order when i want to close it all. Because this is an automated strategy I am not around to manually put an order into close the position.

      Here is the snippet:

      // Calculate the profit and loss for the current session
      double currentSessionProfit = SystemPerformance.AllTrades.TradesPerformance.Curr ency.CumProfit - initialCumProfitOnEnable;
      double currentUnrealizedProfitLoss = Position.GetUnrealizedProfitLoss(PerformanceUnit.C urrency, Close[0]);
      double totalSessionPnL = currentSessionProfit + currentUnrealizedProfitLoss;

      // Check if the combined daily loss limit is reached for the session
      if (totalSessionPnL <= -DailyLossLimit)
      {
      Print("Combined daily loss limit reached. Closing all positions.");
      CloseAllPositions();
      StopStrategy();
      return;
      }

      // Check if the combined daily profit limit is reached for the session
      if (totalSessionPnL >= DailyProfitLimit)
      {
      Print("Combined daily profit limit reached. Closing all positions.");
      CloseAllPositions();
      StopStrategy();
      return;
      }​

      private void CloseAllPositions()
      {
      Print("Attempting to close all positions for " + Instrument.FullName + ".");
      Instrument[] instrumentsToClose = new[] { Instrument };
      Account.Flatten(instrumentsToClose);
      retryCount = 0; // Reset retry count
      retryTimer.Start(); // Start the retry timer
      }

      private void OnRetryTimerElapsed(object sender, System.Timers.ElapsedEventArgs e)
      {
      if (ArePositionsClosed() && AreOrdersCanceled())
      {
      // Stop the retry timer as it's no longer needed
      retryTimer.Stop();

      // All positions closed and all orders canceled successfully, now it's safe to fully disable the strategy
      isStrategyEnabled = false; // Or any other logic to formally stop/disable the strategy
      Print("All positions closed and all orders canceled. Strategy is now safely disabled.");

      // If there are additional cleanup or state-resetting actions needed, include them here
      }
      else
      {
      retryCount++;
      if (retryCount >= MaxRetries)
      {
      // Maximum number of retries reached, log a warning and consider manual intervention
      Print("Warning: Failed to close all positions or cancel all orders after maximum retries. Manual intervention may be required.");
      retryTimer.Stop(); // Stop retrying to prevent an infinite loop
      // Consider setting the strategy to a "requires attention" state or flagging this issue for manual review
      }
      else
      {
      // Retry logic will automatically continue until the timer is manually stopped or the max retries are reached
      Print("Retrying to close all positions and cancel all orders. Attempt: " + retryCount);
      // Optionally, re-invoke the close positions method if you suspect the initial attempt might have failed
      CloseAllPositions();
      }
      }
      }​

      private void StopStrategy()
      {
      // Attempt to close all positions and cancel all orders
      CloseAllPositions();

      // Start the retry timer to periodically check if all positions are closed and orders are canceled
      retryTimer.Start();

      // disabling of the strategy moved into the retry timer's elapsed event handler
      }​

      Comment


        #4
        Hello ryjoga,

        I see that CloseAllPositions() is indeed a custom method you wrote yourself.

        This is calling Account.Flatten() which will disable any strategies running on that instrument and account.

        I don't know any details about how the replikanto works, but using Account.Submit() to submit an order directly to the account would not be seen by the strategies.
        Chelsea B.NinjaTrader Customer Service

        Comment


          #5
          Yep, that just won't work for Replikanto.. I'll try and change it to CloseStrategy() and see if that would work.

          Thank you.

          Comment

          Latest Posts

          Collapse

          Topics Statistics Last Post
          Started by NullPointStrategies, Today, 05:17 AM
          0 responses
          23 views
          0 likes
          Last Post NullPointStrategies  
          Started by argusthome, 03-08-2026, 10:06 AM
          0 responses
          120 views
          0 likes
          Last Post argusthome  
          Started by NabilKhattabi, 03-06-2026, 11:18 AM
          0 responses
          63 views
          0 likes
          Last Post NabilKhattabi  
          Started by Deep42, 03-06-2026, 12:28 AM
          0 responses
          41 views
          0 likes
          Last Post Deep42
          by Deep42
           
          Started by TheRealMorford, 03-05-2026, 06:15 PM
          0 responses
          45 views
          0 likes
          Last Post TheRealMorford  
          Working...
          X