Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

How to close a manually entered trade through a strategy

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

    How to close a manually entered trade through a strategy

    Hello There,

    I am interested in knowing if there is a way to close a trade through a strategy after it was entered manually?

    E.g. If I go long on ES manually in "Sim101" and after the trade is on is there a way for me to close that trade through a strategy with ExitLong()?

    I tried the following
    Entered long manually for ES
    Created a strategy that had the following:

    private Account myAccount;

    in OnStateChange() -> if (State == State.SetDefaults)

    lock (Account.All)
    myAccount = Account.All.FirstOrDefault(a => a.Name == "Sim101");​

    In OnBarUpdate()

    foreach (Position position in myAccount.Positions)
    {
    int qty = position.Quantity;
    Print("Quantity: " + qty);
    Print("Position: " + position.MarketPosition.ToString());
    if (position.MarketPosition == MarketPosition.Long)
    ExitLong(qty);
    }​

    Enabled the strategy on ES with "Start Behavior" as Immediately submit but that did not exit the trade.

    Is there a way to do this? If yes what am I missing in my code snippet?

    #2
    Hello vpatanka,

    Strategy methods are only able to close positions opened by the strategy.

    You will need to submit the order through the Account using the Addon approach.

    Below is a link to the help guide on Account.CreateOrder() and Account.Submit().

    Chelsea B.NinjaTrader Customer Service

    Comment


      #3
      Originally posted by NinjaTrader_ChelseaB View Post
      Hello vpatanka,

      Strategy methods are only able to close positions opened by the strategy.

      You will need to submit the order through the Account using the Addon approach.

      Below is a link to the help guide on Account.CreateOrder() and Account.Submit().

      https://ninjatrader.com/support/help...nt8/submit.htm
      Thanks. I will take a look and give it a try

      Comment


        #4
        Originally posted by vpatanka View Post

        Thanks. I will take a look and give it a try
        Hi Chelsea,

        I tried this in a strategy

        private Account myAccount;
        Order stopOrder = null;
        Instrument myInstrument;​

        In OnStateChange()

        if (State == State.SetDefaults)
        // Find our Sim101 account
        lock (Account.All)
        myAccount = Account.All.FirstOrDefault(a => a.Name == "Sim101");​

        if (State == State.Historical)
        {
        myInstrument = Instrument.GetInstrument("YM 09-24");
        }​

        In OnBarUpdate()

        if (Position.MarketPosition == MarketPosition.Long)
        {
        stopOrder = myAccount.CreateOrder(myInstrument, OrderAction.Sell, OrderType.StopMarket, OrderEntry.Automated, TimeInForce.Day, 1, 0, 1400, "myOCO", "stopOrder", Core.Globals.MaxDate, null);
        myAccount.Submit(new[] { stopOrder });
        }​

        went long on 'YM 09-24', enabled the strategy for YM 09-24 with Start Behavior as "Immediately Submit" on 1min chart and was expecting the strategy to close my long position on bar close but it did not.

        What am I missing?
        Last edited by vpatanka; 08-30-2024, 01:43 PM.

        Comment


          #5
          Hello vpatanka,

          The strategy does not have a position as the strategy did not place the entry order.

          if (Position.MarketPosition == MarketPosition.Long)

          You will need to remove this.

          If you want to check the account position you can use PositionAccount.MarketPosition or <Account>.Positions collection.



          Also, note the script can only place orders to the account when processing realtime data when State is State.Realtime.

          Also, the order will be rejected if "myOCO" has already been used on another order that has been filled or cancelled.
          Chelsea B.NinjaTrader Customer Service

          Comment


            #6
            Originally posted by NinjaTrader_ChelseaB View Post
            Hello vpatanka,

            The strategy does not have a position as the strategy did not place the entry order.

            if (Position.MarketPosition == MarketPosition.Long)

            You will need to remove this.

            If you want to check the account position you can use PositionAccount.MarketPosition or <Account>.Positions collection.



            Also, note the script can only place orders to the account when processing realtime data when State is State.Realtime.

            Also, the order will be rejected if "myOCO" has already been used on another order that has been filled or cancelled.

            Thanks. I updated it to PositionAccount.MarketPosition for the if condition and enabled it again for YM 09-24 but it didn't execute the closing order so I am still missing something or doing something wrong.


            Here a copy of the full strategy I am using to enable on 1 min chart of YM 09-24. There are no other orders with "myOCO".

            I tried changing State == State.RealTime (not sure if that's the correct update) but that still did not execute the closing order

            public class ManualAssistance : Strategy
            {
            private Account myAccount;
            Order stopOrder = null;
            Instrument myInstrument;

            protected override void OnStateChange()
            {
            if (State == State.SetDefaults)
            {
            Description = @"ManualAssistance";
            Name = "ManualAssistance";
            Calculate = Calculate.OnBarClose;
            EntriesPerDirection = 10;
            EntryHandling = EntryHandling.AllEntries;
            IsExitOnSessionCloseStrategy = true;
            ExitOnSessionCloseSeconds = 30;
            IsFillLimitOnTouch = false;
            MaximumBarsLookBack = MaximumBarsLookBack.TwoHundredFiftySix;
            OrderFillResolution = OrderFillResolution.Standard;
            Slippage = 0;
            StartBehavior = StartBehavior.WaitUntilFlat;
            TimeInForce = TimeInForce.Gtc;
            TraceOrders = false;
            RealtimeErrorHandling = RealtimeErrorHandling.StopCancelClose;
            StopTargetHandling = StopTargetHandling.PerEntryExecution;
            BarsRequiredToTrade = 20;
            // Disable this property for performance gains in Strategy Analyzer optimizations
            // See the Help Guide for additional information
            IsInstantiatedOnEachOptimizationIteration = true;

            // Find our Sim101 account
            lock (Account.All)
            myAccount = Account.All.FirstOrDefault(a => a.Name == "Sim101");
            }
            else if (State == State.Configure)
            {
            }
            else if (State == State.DataLoaded)
            {
            }

            if (State == State.Historical)
            {
            myInstrument = Instrument.GetInstrument("YM 09-24");
            }
            }

            protected override void OnBarUpdate()
            {
            if (CurrentBar < BarsRequiredToTrade) return;

            if (BarsInProgress != 0)

            foreach (Position position in myAccount.Positions)
            {
            if (PositionAccount.MarketPosition == MarketPosition.Long)
            {
            stopOrder = myAccount.CreateOrder(myInstrument, OrderAction.Sell, OrderType.StopMarket, OrderEntry.Automated, TimeInForce.Day, 1, 0, 1400, "myOCO", "stopOrder", Core.Globals.MaxDate, null);
            myAccount.Submit(new[] { stopOrder });
            }
            }
            }
            }​

            Never mind. I have it working now. Thanks a lot
            Last edited by vpatanka; 08-30-2024, 02:21 PM.

            Comment


              #7
              Originally posted by vpatanka View Post


              Thanks. I updated it to PositionAccount.MarketPosition for the if condition and enabled it again for YM 09-24 but it didn't execute the closing order so I am still missing something or doing something wrong.


              Here a copy of the full strategy I am using to enable on 1 min chart of YM 09-24. There are no other orders with "myOCO".

              I tried changing State == State.RealTime (not sure if that's the correct update) but that still did not execute the closing order

              public class ManualAssistance : Strategy
              {
              private Account myAccount;
              Order stopOrder = null;
              Instrument myInstrument;

              protected override void OnStateChange()
              {
              if (State == State.SetDefaults)
              {
              Description = @"ManualAssistance";
              Name = "ManualAssistance";
              Calculate = Calculate.OnBarClose;
              EntriesPerDirection = 10;
              EntryHandling = EntryHandling.AllEntries;
              IsExitOnSessionCloseStrategy = true;
              ExitOnSessionCloseSeconds = 30;
              IsFillLimitOnTouch = false;
              MaximumBarsLookBack = MaximumBarsLookBack.TwoHundredFiftySix;
              OrderFillResolution = OrderFillResolution.Standard;
              Slippage = 0;
              StartBehavior = StartBehavior.WaitUntilFlat;
              TimeInForce = TimeInForce.Gtc;
              TraceOrders = false;
              RealtimeErrorHandling = RealtimeErrorHandling.StopCancelClose;
              StopTargetHandling = StopTargetHandling.PerEntryExecution;
              BarsRequiredToTrade = 20;
              // Disable this property for performance gains in Strategy Analyzer optimizations
              // See the Help Guide for additional information
              IsInstantiatedOnEachOptimizationIteration = true;

              // Find our Sim101 account
              lock (Account.All)
              myAccount = Account.All.FirstOrDefault(a => a.Name == "Sim101");
              }
              else if (State == State.Configure)
              {
              }
              else if (State == State.DataLoaded)
              {
              }

              if (State == State.Historical)
              {
              myInstrument = Instrument.GetInstrument("YM 09-24");
              }
              }

              protected override void OnBarUpdate()
              {
              if (CurrentBar < BarsRequiredToTrade) return;

              if (BarsInProgress != 0)

              foreach (Position position in myAccount.Positions)
              {
              if (PositionAccount.MarketPosition == MarketPosition.Long)
              {
              stopOrder = myAccount.CreateOrder(myInstrument, OrderAction.Sell, OrderType.StopMarket, OrderEntry.Automated, TimeInForce.Day, 1, 0, 1400, "myOCO", "stopOrder", Core.Globals.MaxDate, null);
              myAccount.Submit(new[] { stopOrder });
              }
              }
              }
              }​

              Never mind. I have it working now. Thanks a lot

              One last question -
              Currently I am declaring and initiating my Instrument explicitly (as below)

              Instrument myInstrument = Instrument.GetInstrument("YM 09-24");

              Is there a way for the strategy code to automatically get that Instrument object based on the chart that strategy is enabled for and if so how would I do that?

              Thanks again
              Last edited by vpatanka; 08-30-2024, 02:27 PM.

              Comment


                #8
                Hello vpatanka,

                Thank you for your reply.

                The PositionAccount.MarketPosition would be the account position of the account the strategy is enabled on.
                You would not need to nest this in a loop of all of the account positions. Its a one thing OR the other thing type situation.

                Instrument is the instrument the strategy is enabled on.

                Below is a link to the help guide.



                Trying printing the PositionAccount.MarketPosition to confirm this is returning long.

                Below is a link to a support article on adding debugging prints to understand behavior.
                Chelsea B.NinjaTrader Customer Service

                Comment

                Latest Posts

                Collapse

                Topics Statistics Last Post
                Started by NullPointStrategies, Today, 05:17 AM
                0 responses
                50 views
                0 likes
                Last Post NullPointStrategies  
                Started by argusthome, 03-08-2026, 10:06 AM
                0 responses
                126 views
                0 likes
                Last Post argusthome  
                Started by NabilKhattabi, 03-06-2026, 11:18 AM
                0 responses
                69 views
                0 likes
                Last Post NabilKhattabi  
                Started by Deep42, 03-06-2026, 12:28 AM
                0 responses
                42 views
                0 likes
                Last Post Deep42
                by Deep42
                 
                Started by TheRealMorford, 03-05-2026, 06:15 PM
                0 responses
                46 views
                0 likes
                Last Post TheRealMorford  
                Working...
                X