Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

Alternating Buy/Sell programming help

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

    Alternating Buy/Sell programming help

    Hi guys, I've been working on a strategy and I could use some pro programming help!

    For example:
    If the strategy enters a buy signal and closes it out once completed, I don't want it to re-enter another long position, I want it to ignore the buy signals and wait until a sell signal is given.

    If the previous trade was a buy, the next trade can only be a sell.
    If the previous trade was a sell, the next trade can only be a buy.

    #2
    You're in luck!

    That is exactly how NinjaTrader's managed approached works.

    Have you read these pages?




    Have you studied "@SampleMACrossOver.cs" in your "bin/Custom/Strategy" folder?

    Assuming "EntriesPerDirection=1" then the following is true:

    1. When you're already long (because of a prior call to EnterLong()) any new calls to EnterLong() will be ignored.

    2. If this long trade is not exited via stop/limit set by SetStopLoss()/SetTrailStop()/SetProfitTarget(), then your long position will be automatically exited when you call EnterShort().

    That's it! Easy peasy.

    Yes, NinjaTrader is that smart -- sequences of alternating calls to EnterLong() and EnterShort() will work exactly as what you are asking for -- each "Enter" function first exits the opposite position if there is one. And, if you're trying to go long "twice" by calling EnterLong() twice, well, NinjaTrader saves you. That 2nd "Enter" call will be ignored.

    The managed approach is really a quite convenient (and clever) design pattern for writing NinjaScript strategies.

    So, study that again: opposite positions will be exited automatically, under the hood, like magic, nothing for you to do, it's automatic, done for you, you know you love that, it's beautiful, enlightenment ensues -- yes, auto magically, NinjaTrader will NOT let you have long and short position open at same time -- so it exits the opposing position (if there is one) A-U-T-O-matically for you.

    Such is the power of the "managed approach" and "EntriesPerDirection=1".

    Comment


      #3
      Oh, hey, I may have misread your request.

      One solution might be this:

      Add 2 bools to your code,

      Code:
      private bool IsLongOk = true;
      private bool IsShortOk = true;
      When you call EnterLong() make sure you check if you have permission,

      Code:
      If (IsLongOk)
        {
           EnterLong();
           IsLongOk = false;
           IsShortOk = true;
        }
      also put your call to EnterShort() into a similar "permission" wrapper,

      Code:
      if (IsShortOk)
        {
          EnterShort();
          IsShortOk = false;
          IsLongOk = true;
        }
      Is that what you're asking for?

      Comment


        #4
        Yes this is it but can you make it so I can just paste the entire thing into the code, when I try to add it I keep getting errors and I am not sure how to code.
        Last edited by brucelevy; 02-07-2015, 12:15 AM.

        Comment


          #5
          Post an attachment with the code you have so far.

          Comment


            #6
            #region Using declarations
            using System;
            using System.ComponentModel;
            using System.Diagnostics;
            using System.Drawing;
            using System.Drawing.Drawing2D;
            using System.Xml.Serialization;
            using NinjaTrader.Cbi;
            using NinjaTrader.Data;
            using NinjaTrader.Indicator;
            using NinjaTrader.Gui.Chart;
            using NinjaTrader.Strategy;
            #endregion

            // This namespace holds all strategies and is required. Do not change it.
            namespace NinjaTrader.Strategy
            {
            /// <summary>
            /// Enter the description of your strategy here
            /// </summary>
            [Description("Enter the description of your strategy here")]
            public class AlternateMA : Strategy
            {
            #region Variables
            // Wizard generated variables
            // User defined variables (add any user defined variables below)
            #endregion

            /// <summary>
            /// This method is used to configure the strategy and is called once before any strategy method is called.
            /// </summary>
            protected override void Initialize()
            {
            SetStopLoss("a", CalculationMode.Ticks, 5, false);
            SetStopLoss("b", CalculationMode.Ticks, 5, false);

            CalculateOnBarClose = true;
            }

            /// <summary>
            /// Called on each bar update event (incoming tick)
            /// </summary>
            protected override void OnBarUpdate()
            {
            // Condition set 1
            if (SMA(5)[0] > SMA(20)[0])
            {
            EnterLong(DefaultQuantity, "a");
            }

            // Condition set 2
            if (SMA(5)[0] < SMA(20)[0])
            {
            EnterShort(DefaultQuantity, "b");
            }
            }

            #region Properties
            #endregion
            }
            }

            #region Wizard settings, neither change nor remove

            Comment


              #7
              Hello brucelevy,

              Thank you for your response.

              The code provided by bltdavid would be added as follows:
              Code:
              public class AlternateMA : Strategy
              {
              #region Variables
              private bool IsLongOk = true;
              private bool IsShortOk = true;
              #endregion
              
              /// <summary>
              /// This method is used to configure the strategy and is called once before any strategy method is called.
              /// </summary>
              protected override void Initialize()
              {
              SetStopLoss("a", CalculationMode.Ticks, 5, false);
              SetStopLoss("b", CalculationMode.Ticks, 5, false);
              
              CalculateOnBarClose = true;
              }
              
              /// <summary>
              /// Called on each bar update event (incoming tick)
              /// </summary>
              protected override void OnBarUpdate()
              {
              // Condition set 1
              if (SMA(5)[0] > SMA(20)[0] && IsLongOk)
              {
              EnterLong(DefaultQuantity, "a");
              IsLongOk = false;
              IsShortOk = true;
              }
              
              // Condition set 2
              if (SMA(5)[0] < SMA(20)[0] && IsShortOk)
              {
              EnterShort(DefaultQuantity, "b");
              IsShortOk = false;
              IsLongOk = true;
              }
              }
              
              #region Properties
              #endregion
              }
              }

              Comment


                #8
                What would cause this to take a position on every candle?

                Comment


                  #9
                  brucelevy, the code would check for the one MA being greater than the other to take a trade, it would not check for a crossover here, meaning the bar before the condition triggered the MA was smaller than the other one. If this is changed you should not see a trade on each candle the condition is true, since it could only true for the crossover bar.

                  Comment


                    #10
                    I had added a second condition using a cross above/below. The ema is used to make sure the trend is up or down first - but it started opening and closing a new position on every bar

                    Comment


                      #11
                      Hello brucelevy,

                      Can you provide your amended code that is producing this behavior?

                      Comment

                      Latest Posts

                      Collapse

                      Topics Statistics Last Post
                      Started by Geovanny Suaza, 02-11-2026, 06:32 PM
                      0 responses
                      637 views
                      0 likes
                      Last Post Geovanny Suaza  
                      Started by Geovanny Suaza, 02-11-2026, 05:51 PM
                      0 responses
                      366 views
                      1 like
                      Last Post Geovanny Suaza  
                      Started by Mindset, 02-09-2026, 11:44 AM
                      0 responses
                      107 views
                      0 likes
                      Last Post Mindset
                      by Mindset
                       
                      Started by Geovanny Suaza, 02-02-2026, 12:30 PM
                      0 responses
                      569 views
                      1 like
                      Last Post Geovanny Suaza  
                      Started by RFrosty, 01-28-2026, 06:49 PM
                      0 responses
                      571 views
                      1 like
                      Last Post RFrosty
                      by RFrosty
                       
                      Working...
                      X