Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

sample strategy with stop loss and profit target.

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

    sample strategy with stop loss and profit target.



    people with nt,


    i'm interested in evaluating how strategies with stop loss and profit target orders can perform, and it is the advanced versions with onorder and onexecution sections that i'm interested in.


    nt does make a minimal sample strategy available with a stop loss. i request that nt make available a simple sample strategy with onorder and onexecution sections that uses both a stop loss and a profit target order for entries. from there i should be able to make some changes as necessary.


    very well, thanks, regards.

    #2
    Hello rtwave,

    Thanks for your post.

    You could view the SampleOnOrderUpdate reference sample linked below from the NinjaTrader help guide which demonstrates using a Stop Loss and Profit Target order with OnExecutionUpdate()/OnOrderUpdate().

    <span class="name">Brandon H.</span><span class="title">NinjaTrader Customer Service</span><iframe name="sig" id="sigFrame" src="/support/forum/core/clientscript/Signature/signature.php" frameborder="0" border="0" cellspacing="0" style="border-style: none;width: 100%; height: 120px;"></iframe>

    Comment


      #3



      people with nt,


      thanks.


      i had forgotten that nt's sample does include one stop loss and one profit target order.




      i have been going over the strategies i have been working on and i have realized that most everything is well defined. i'm thinking that it must be this part below inside the onexecution section that i must have errors on:




      // Reset our stop order and target orders' Order objects after our position is closed. (1st Entry)
      if ((stopOrder != null && stopOrder == execution.Order) || (targetOrder != null && targetOrder == execution.Order))
      {
      if (execution.Order.OrderState == OrderState.Filled || execution.Order.OrderState == OrderState.PartFilled)
      {
      stopOrder = null;
      targetOrder = null;
      }
      }​


      nt's sample strategy consists of one single entry with only two possible exit orders: a stop loss order or a profit target order.


      i request that nt make available a sample strategy, as simple as you like, with two identical, parallel, short entry orders, the first of which can only have two possible exit orders: a stop loss order and an exitshort order. the second short entry order should have three possible exit commands: a stop loss order,a profit target order and an exitshort order.


      with such a sample fragment i should be able to correct the strategies i'm working on as necessary.



      very well, thanks, regards.

      Comment


        #4
        Hello rtwave,

        Thanks for your notes.

        We do not have a reference sample available that specifically places the orders you mentioned.

        If you are wanting to submit two entry orders then you would need to track each of those Order objects in your script, such as private Order entryOrder1 and private Order entryOrder2.

        You would also need to track each stop and target order as individual Order objects in the script and come up with the custom logic for handling each of those orders.

        I suggest studying the SampleOnOrderUpdate reference sample to gain a full understanding of how the script functions. Once you have a good understanding of how everything in the script works, you could add one element to your script at a time and test to ensure it is working as you are expecting it to before adding another element to the script.

        If the strategy is not behaving as you expect it to, debugging prints would have to be added to the strategy to understand how your logic is behaving when running the script. Also, keep an eye on the Log tab of the Control Center for any error messages that might appear.

        Below is a link to a forum post that demonstrates how to use prints to understand behavior.
        https://ninjatrader.com/support/foru...121#post791121
        <span class="name">Brandon H.</span><span class="title">NinjaTrader Customer Service</span><iframe name="sig" id="sigFrame" src="/support/forum/core/clientscript/Signature/signature.php" frameborder="0" border="0" cellspacing="0" style="border-style: none;width: 100%; height: 120px;"></iframe>

        Comment


          #5




          people with nt,



          the resources that nt makes available to clients are so incomplete that it is hilarious. well, it would be hilarious if there was anything funny about such a situation where a company with a brutally difficult to use, proprietary product gives clients no resources to work with.



          in the case of a strategy where there are only two exit commands this fragment below will work fine:


          // Reset our stop order and target orders' Order objects after our position is closed. (1st Entry)
          if ((stopOrder != null && stopOrder == execution.Order) || (targetOrder != null && targetOrder == execution.Order))
          {
          if (execution.Order.OrderState == OrderState.Filled || execution.Order.OrderState == OrderState.PartFilled)
          {
          stopOrder = null;
          targetOrder = null;
          }
          }​​

          an entry will only be exited by either a stop loss order or a profit target order, and once either of those situations arises, all order objects will be appropriately reset.




          in other cases, like the ones i mentioned, where other commands can also exit an entry, żhow can code be modified so that the strategy will not only reset the stop loss and profit target order objects in the case any of those orders has been activated but also in case an exitshort order for that same entry has been activated?


          i have been looking at several strategies and as i see exit orders do not require an order object and do not have to ever be reset.


          nt has to provide a working sample of a strategy that uses the onorder and onexecution functionalities and where entries are exited with exitshort - exitlong commands. this is basic, elementary code that users cannot be expected to figure out how to utilize by themselves.

          Comment


            #6
            Hello rtwave,

            Thanks for your notes.

            If you want to use an Exit method, such as ExitLong() or ExitShort() to exit the entry order when a certain condition becomes true, you could set up your condition in the OnBarUpdate() section of code and call the ExitLong() or ExitShort() method within that condition to exit the entry order.

            I have modified the SampleOnOrderUpdate reference sample to place an exit order with ExitLong() if at least three bars have passed since the entry order was placed if the stop/target was not reached. The way the script works is the strategy places an entry order. When the entry order is filled, a stop loss and profit target are placed. If at least three bars pass since the entry order was placed, the strategy calls ExitLong() to exit the entry order, and the stop loss and profit target are canceled.

            See the attached sample script demonstrating the use of a stop loss, profit target, and exit market order (ExitLong()).
            Attached Files
            <span class="name">Brandon H.</span><span class="title">NinjaTrader Customer Service</span><iframe name="sig" id="sigFrame" src="/support/forum/core/clientscript/Signature/signature.php" frameborder="0" border="0" cellspacing="0" style="border-style: none;width: 100%; height: 120px;"></iframe>

            Comment


              #7



              NinjaTrader_BrandonH,



              thanks.


              i will indeed take a look at the script you have been so kind to share.



              this below is nt's sample strategy, nt should have at least 3 very basic strategies that it featured in every single section of their user guide. a price - sma crossover, an alternating short entries on odd bar numbers - long entries on even bar numbers and a strategy that placed entry and exit orders at different times of the day. if these basic strategies were featured everywhere: from the most basic, simplest versions, to versions using onorder and onexecution functionalities, to versions with and without stop loss - profit target orders, and versions using multiple data indices functionalities and everything in between, then it would actually be possible to figure out how to develop slightly more complex scripts on nt. at the moment, the guides are very incomplete and it is impossible to piece together any coherent basis from which to work on.





              namespace NinjaTrader.NinjaScript.Strategies
              {
              public class SampleMACrossOver : Strategy
              {
              private SMA smaFast;
              private SMA smaSlow;

              protected override void OnStateChange()
              {
              if (State == State.SetDefaults)
              {
              Description = NinjaTrader.Custom.Resource.NinjaScriptStrategyDes criptionSampleMACrossOver;
              Name = NinjaTrader.Custom.Resource.NinjaScriptStrategyNam eSampleMACrossOver;
              Fast = 10;
              Slow = 25;
              // This strategy has been designed to take advantage of performance gains in Strategy Analyzer optimizations
              // See the Help Guide for additional information
              IsInstantiatedOnEachOptimizationIteration = false;
              }
              else if (State == State.DataLoaded)
              {
              smaFast = SMA(Fast);
              smaSlow = SMA(Slow);
              }
              }

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

              if (CrossAbove(smaFast, smaSlow, 1))
              ExitShort();
              else if (CrossBelow(smaFast, smaSlow, 1))
              EnterShort();
              }​

              Comment


                #8
                Hello rtwave,

                Thanks for your notes.

                The Language Reference section of the help guide details all of the different methods and properties that are available to use in custom NinjaScripts. Each method and property contains simple sample code to demonstrate how it could be used. The Educational Resources section help guide contains information about multi-threading consideration, working with multi-timeframe/multi-instrument NinjaScripts, Tips, Reference Sample scripts, and more. There is also a section in the help guide detailing the use of SharpDX for custom rendering objects on charts.

                These concepts should be studied to understand their functionalities and how they could be combined with other NinjaScript concepts.

                That said, I have submitted a feature request to the Development team for including the reference samples you mentioned in the help guide. This request is being tracked under the number SFT-6047.

                As with all feature requests, interest is tracked before implementation is considered, so we cannot offer an ETA or promise of fulfillment. If implemented, it will be noted on the Release Notes page of the Help Guide.

                Release Notes — https://ninjatrader.com/support/help...ease_notes.htm
                <span class="name">Brandon H.</span><span class="title">NinjaTrader Customer Service</span><iframe name="sig" id="sigFrame" src="/support/forum/core/clientscript/Signature/signature.php" frameborder="0" border="0" cellspacing="0" style="border-style: none;width: 100%; height: 120px;"></iframe>

                Comment


                  #9


                  i have already gone over the script that was made available.


                  it is not working as intended. i modified my code so that it would have the same structure as the sample but still for an entry with an exit order - a stop loss order - a profit target order only the exit order will activate. something is missing for the stop loss and profit target orders and those will never activate.


                  please provide a working sample for nt's sample strategy but a version which uses the onorder and onexecution capabilities:


                  namespace NinjaTrader.NinjaScript.Strategies
                  {
                  public class SampleMACrossOver : Strategy
                  {
                  private SMA smaFast;
                  private SMA smaSlow;

                  protected override void OnStateChange()
                  {
                  if (State == State.SetDefaults)
                  {
                  Description = NinjaTrader.Custom.Resource.NinjaScriptStrategyDes criptionSampleMACrossOver;
                  Name = NinjaTrader.Custom.Resource.NinjaScriptStrategyNam eSampleMACrossOver;
                  Fast = 10;
                  Slow = 25;
                  // This strategy has been designed to take advantage of performance gains in Strategy Analyzer optimizations
                  // See the Help Guide for additional information
                  IsInstantiatedOnEachOptimizationIteration = false;
                  }
                  else if (State == State.DataLoaded)
                  {
                  smaFast = SMA(Fast);
                  smaSlow = SMA(Slow);
                  }
                  }

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

                  if (CrossAbove(smaFast, smaSlow, 1))
                  ExitShort();
                  else if (CrossBelow(smaFast, smaSlow, 1))
                  EnterShort();
                  }​​


                  once i understand how entry and exit orders should be utilized with onorder and onexecution capabilities i should be able to refine my code as necessary.



                  i strongly suspect that it must be necessary for the platform to also monitor for exit orders in this section:


                  // Reset our stop order and target orders' Order objects after our position is closed. (1st Entry)
                  if ((stopOrder != null && stopOrder == execution.Order) || (targetOrder != null && targetOrder == execution.Order))
                  {
                  if (execution.Order.OrderState == OrderState.Filled || execution.Order.OrderState == OrderState.PartFilled)
                  {
                  stopOrder = null;
                  targetOrder = null;
                  }
                  }​​​


                  that is missing from the sample and it seems to me like that would complete the code and cover all possibilities.

                  Comment


                    #10
                    Hello rtwave,

                    Thanks for your notes.

                    "it is not working as intended."

                    Are you referring to the script that you are trying to create? Or, are you referring to the sample script I shared on post # 6?

                    Here is a demonstration video showing that the SampleOnOrderUpdateMod script does work: https://brandonh-ninjatrader.tinytak...Nl8yMTkyMDkxMw

                    I have also attached a modified version of SampleOnOrderUpdate that uses SMA Crossover conditions for you to view.​
                    Attached Files
                    <span class="name">Brandon H.</span><span class="title">NinjaTrader Customer Service</span><iframe name="sig" id="sigFrame" src="/support/forum/core/clientscript/Signature/signature.php" frameborder="0" border="0" cellspacing="0" style="border-style: none;width: 100%; height: 120px;"></iframe>

                    Comment


                      #11


                      people with nt,


                      i have continued to work on these strategies i am currently developing.


                      i disactivated the entire onorder and onexecution sections and created a simple version of a strategy using what nt calls set orders.



                      SetStopLoss(@"shortentrya", CalculationMode.Ticks, , false);
                      SetStopLoss(@"shortentryb", CalculationMode.Ticks, , false);
                      SetStopLoss(@"shortentryc", CalculationMode.Ticks, , false);
                      SetProfitTarget(@"shortentryb", CalculationMode.Ticks, );
                      SetProfitTarget(@"shortentryc", CalculationMode.Ticks, );



                      these orders work to perfection. stops, profit orders and exit orders will all activate exactly as they are intended to.


                      the issues have been when i have tried to create a more advanced version that will utilize onorder and onexecution functionalities.




                      Comment


                        #12
                        Originally posted by NinjaTrader_BrandonH View Post
                        Hello rtwave,

                        Thanks for your notes.

                        If you want to use an Exit method, such as ExitLong() or ExitShort() to exit the entry order when a certain condition becomes true, you could set up your condition in the OnBarUpdate() section of code and call the ExitLong() or ExitShort() method within that condition to exit the entry order.

                        I have modified the SampleOnOrderUpdate reference sample to place an exit order with ExitLong() if at least three bars have passed since the entry order was placed if the stop/target was not reached. The way the script works is the strategy places an entry order. When the entry order is filled, a stop loss and profit target are placed. If at least three bars pass since the entry order was placed, the strategy calls ExitLong() to exit the entry order, and the stop loss and profit target are canceled.

                        See the attached sample script demonstrating the use of a stop loss, profit target, and exit market order (ExitLong()).


                        additionally, i also ran some tests on this sample strategy that nt made available on this post and there are some issues with it.


                        i created a 1 minute chart with 7 days of data, disabled the breakeven command by setting it to 60 ticks in favor and used the settings below. both on the es and the rty contract the strategy will begin placing entries in a rtrded fashion and all of a sudden it will just stop placing any more entries when it should not. nt should be able to corroborate this malfunction.



                        // Submit exit orders for partial fills
                        if (execution.Order.OrderState == OrderState.PartFilled)
                        {
                        stopOrder = ExitLongStopMarket(0, true, execution.Order.Filled, execution.Order.AverageFillPrice - 3 * TickSize, "MyStop", "MyEntry");
                        targetOrder = ExitLongLimit(0, true, execution.Order.Filled, execution.Order.AverageFillPrice + 17 * TickSize, "MyTarget", "MyEntry");
                        }
                        // Update our exit order quantities once orderstate turns to filled and we have seen execution quantities match order quantities
                        else if (execution.Order.OrderState == OrderState.Filled && sumFilled == execution.Order.Filled)
                        {
                        // Stop-Loss order for OrderState.Filled
                        stopOrder = ExitLongStopMarket(0, true, execution.Order.Filled, execution.Order.AverageFillPrice - 3 * TickSize, "MyStop", "MyEntry");
                        targetOrder = ExitLongLimit(0, true, execution.Order.Filled, execution.Order.AverageFillPrice + 17 * TickSize, "MyTarget", "MyEntry");
                        }

                        // Resets the entryOrder object and the sumFilled counter to null / 0 after the order has been filled
                        if (execution.Order.OrderState != OrderState.PartFilled && sumFilled == execution.Order.Filled)
                        {
                        entryOrder = null;
                        sumFilled = 0;
                        }​


                        this screengrab below illustrates what i'm talking about:



                        Click image for larger version

Name:	20230816 nt malfunction 0001.jpg
Views:	1320
Size:	155.0 KB
ID:	1265051



                        i will now try to evaluate the latest sample that nt has made available.

                        Comment


                          #13
                          Hello rtwave,

                          Thanks for your notes.

                          The SampleOnOrderUpdateMod sample linked on post # 6 is working as expected when I am testing it on my end. The strategy places trades trades when the condition to place the trades becomes true.

                          A demonstration video of the script working as expected could be seen on post # 10.

                          You should add debugging prints to the script if you have modified the script to see exactly how your logic in the strategy is behaving and placing orders.

                          Below is a link to a forum post that demonstrates how to use prints to understand behavior.
                          https://ninjatrader.com/support/foru...121#post791121
                          <span class="name">Brandon H.</span><span class="title">NinjaTrader Customer Service</span><iframe name="sig" id="sigFrame" src="/support/forum/core/clientscript/Signature/signature.php" frameborder="0" border="0" cellspacing="0" style="border-style: none;width: 100%; height: 120px;"></iframe>

                          Comment


                            #14

                            Originally posted by NinjaTrader_BrandonH View Post
                            Hello rtwave,

                            Thanks for your notes.

                            "it is not working as intended."

                            Are you referring to the script that you are trying to create? Or, are you referring to the sample script I shared on post # 6?

                            Here is a demonstration video showing that the SampleOnOrderUpdateMod script does work: https://brandonh-ninjatrader.tinytak...Nl8yMTkyMDkxMw

                            I have also attached a modified version of SampleOnOrderUpdate that uses SMA Crossover conditions for you to view.​


                            people with nt,


                            i have been evaluating the sample strategy that nt made available in post #10.


                            incredibly, this works to perfection. exit orders, stop loss orders, profit target orders will all work without problem and liquidate entries when they are supposed to.


                            Click image for larger version

Name:	20230818 performance 0001.jpg
Views:	1273
Size:	34.7 KB
ID:	1265275



                            and this ends up being really strange and frustrating because i'm using the exact same structure this sample strategy uses.

                            Comment


                              #15
                              Hello rtwave,

                              Thanks for your notes.

                              If your custom NinjaScript strategy is not behaving as expected, you should use debugging prints to determine exactly how the script is behaving and placing orders.

                              Below is a link to a forum post that demonstrates how to use prints to understand behavior.
                              https://ninjatrader.com/support/foru...121#post791121

                              You could also carefully compare each line of code in your custom script to the sample script linked on post # 10 to see where differences might be between scripts.
                              <span class="name">Brandon H.</span><span class="title">NinjaTrader Customer Service</span><iframe name="sig" id="sigFrame" src="/support/forum/core/clientscript/Signature/signature.php" frameborder="0" border="0" cellspacing="0" style="border-style: none;width: 100%; height: 120px;"></iframe>

                              Comment

                              Latest Posts

                              Collapse

                              Topics Statistics Last Post
                              Started by argusthome, 03-08-2026, 10:06 AM
                              0 responses
                              116 views
                              0 likes
                              Last Post argusthome  
                              Started by NabilKhattabi, 03-06-2026, 11:18 AM
                              0 responses
                              61 views
                              0 likes
                              Last Post NabilKhattabi  
                              Started by Deep42, 03-06-2026, 12:28 AM
                              0 responses
                              40 views
                              0 likes
                              Last Post Deep42
                              by Deep42
                               
                              Started by TheRealMorford, 03-05-2026, 06:15 PM
                              0 responses
                              43 views
                              0 likes
                              Last Post TheRealMorford  
                              Started by Mindset, 02-28-2026, 06:16 AM
                              0 responses
                              82 views
                              0 likes
                              Last Post Mindset
                              by Mindset
                               
                              Working...
                              X