Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

Help with Breakout Stop Entry code.

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

    Help with Breakout Stop Entry code.

    I've coded thousands of lines of ninjascript code but it has all been Indicator code. So I'm breaking my Strategy cherry here with a very simple breakout strategy.

    All I want to do is: at 10am define the highest high of the last 8 bars and place a buy stop to enter at that price and define the lowest low of the last 8 bars and place a sell stop to enter at that low. I would like the orders to persist till 3pm then cancel.

    Using the following code, either the Long Entry Stop works or the Short Entry Stop works but not both. Whichever EnterStop statement is second in the code, does not work. I've tried giving then unique string names but that has no effect.

    What fundamental concept am I missing? Some hand holding would be appreciated .

    thanks,
    shawnj

    Code:
    public class BO : Strategy
    {
       private double _rangeHigh = Double.MaxValue;
       private double _rangeLow = 0;
    
       protected override void Initialize()
       {
           CalculateOnBarClose = true;
       }
    
        protected override void OnBarUpdate()
        {
    	if( CurrentBar < 10 ) return;
    		
    	//===Define breakout high and low prices.===
    	if( Time[0].TimeOfDay == DateTime.Parse("10:00").TimeOfDay )
    	{
    		_rangeHigh = High[ HighestBar(High, 8) ];
    		_rangeLow = Low[ LowestBar(Low, 8) ];
    	}
    		
    	//===Place breakout orders each bar.===
    	if( (Time[0].TimeOfDay >= DateTime.Parse("10:00").TimeOfDay) && (Time[0].TimeOfDay <= DateTime.Parse("15:00").TimeOfDay) )
    	{
    		EnterLongStop(_rangeHigh + 1*TickSize);
    		EnterShortStop(_rangeLow - 1*TickSize);  //Here the Short Entry Stop never fills.
    			
    		//EnterShortStop(_rangeLow - 1*TickSize); 
    		//EnterLongStop(_rangeHigh + 1*TickSize);  //Here the Long Entry Stop never fills.
    	}
        }
    }

    #2
    shawnj, most likely you run into the 'Internal Order Handling Rules' with this - http://www.ninjatrader-support.com/H...verview36.html (bottom part of the link)

    To debug your strategy order behavior, please work with TradeOrders = true in the Initialize() - http://www.ninjatrader-support2.com/...ead.php?t=3627

    Comment


      #3
      I've carefully read the two links provided. After adding TradeOrders=true and further testing, it does look like 'Internal Order Handling Rules' is the "problem". Here is the output:

      <<Begin TradeOrders output:>>

      6/17/2009 10:00:00 AM Ignored PlaceOrder() method at 6/17/2009 10:00:00 AM: Action=SellShort OrderType=Stop Quantity=1 LimitPrice=0 StopPrice=1.6244 SignalName=Sell short' FromEntrySignal='' Reason='An Enter() method to submit an entry order has been ignore. Please search on the term 'Internal Order Handling Rules' in the Help Guide for detailed explanation.'

      <<End TradeOrders output.>>

      Since I am a rookie at writing NT Strategies (though I've written lots of Tradestation strategy code) I'm trying to resist the urge to complain here since there may be something that I still don't understand.

      But the trading strategy of bracketing a range of prices with a buy stop above the highs and a sell stop below the lows is so common, I don't understand why ninjatrader feels the need to internally restrict this. So what if the market trades above the highs and stops us in long then turns around and takes out the lows and stops us in short. Why do we need protection against that or why is it restricted?

      I have to confess I have not thoroughly search the forms but surely this is common problem. Is there a palatable workaround for this problem? The only thing I can think of is to write two separate Strategies: a long entry strategy and a short entry strategy. I find this very unsatisfactory.

      Would another possible workaround be to move the orders out of OnBarUpdate?

      shawnj

      Comment


        #4
        shawnj,

        Consider the way NinjaTrader handles reversals. If you were already long, all you do is call EnterShort and it automatically closes the long and gets you short. When you do Enter() simultaneously in opposite directions the orders do not know what to do with reversals and can leave you in the system in a limbo state. This is why it is not allowed.

        If you have a need for a long/short like that, just submit one of them at a time. If the price moves closer to the opposite direction, then cancel the first, submit the second. If it moves yet back to the original, do the same, and keep doing this till one gets filled.
        Josh P.NinjaTrader Customer Service

        Comment


          #5
          Josh, I've carefully read your reply. Thanks for offering a workaround. Of course one of the problems with that workaround is when we cancel the stop entry and then reapply it, we loose our place in the order queue. Also as the market swings back and forth in the middle of the range then suddenly breaks out, we may be late getting the order in. That's why we have stop entry orders already at the exchange waiting.

          But can we talk about the reversal issue. I'm assuming this is the reason for this restriction.

          I can see restricting EnterLong() and EnterShort() this way since these are market orders, but it doesn't make sense to restrict EnterLongStop() and EnterShortStop() this way. This is a completely different scenario.

          In the code as I have written it, assuming no restrictions, if we stop in long, then the market turns around and trades through the low, we just reverse there and go short because the SellStop order is not activated till we tick at the low entry price. Behind the scene, as soon as we go long, NT would modify the EntrySellStop order and double the quantity (to make it a reversing order). I don't see what the ambiguity is.

          The only real ambiguity I can think of, and this is the result of writing and testing and trading with lots of Tradestation strategy code, is if when backtesting with bar data and a single bar hits the buy stop and the sell stop - which happened first? Trading realtime there is no ambiguity. BTW, the way Tradestation deals with that ambiguity is it looks at the OHLC relationship then makes an assumption which happened first - the High or the Low.

          shawnj
          Last edited by shawnj; 09-10-2009, 04:21 PM.

          Comment


            #6
            The restriction does not care if it is market or limit order. The problem is you will be stuck in a limbo state.

            NT7 will provide an unmanaged approach where you can program however you want at your own risk. For 6.5, these limitations are in place and will remain there.
            Josh P.NinjaTrader Customer Service

            Comment


              #7
              Originally posted by NinjaTrader_Josh View Post
              The restriction does not care if it is market or limit order. The problem is you will be stuck in a limbo state.
              Ok, I understand the reality that the restriction applies to market or limit orders (though what I'm describing is a stop order - I assume it also applies) but what I'm saying is doesn't make sense. Though I guess you are not going to explain why we will be stuck in a limbo state, I still don't understand why.

              Originally posted by NinjaTrader_Josh View Post
              NT7 will provide an unmanaged approach where you can program however you want at your own risk.
              I've learned a long time ago to not use "The next version will fix this" as a solution to my software problems. This applies to all software. NT7 is approaching now a year late based on the first estimate I heard way back when. I'm assuming NT7 will be released some time between tomorrow and never. I'm not waiting for NT7.

              What flabbergasts me is, the very first trading strategy that I picked to hone my NT strategy coding skills with, a strategy that I picked because I thought it was the simplest possible strategy, NT can't handle it - Amazing!

              shawnj

              Comment


                #8
                shawnj,

                The restrictions are there for good reason. They are required and nothing will change for NT6.5 in this regard. NT7 does not look to "fix" this as we do not see this as something that needs fixing. What we have done in 7 is relax the requirements for people that want more control, just like how 6.5 allowed more control for people over 6.

                I am now closing this case. Thank you for understanding.
                Josh P.NinjaTrader Customer Service

                Comment


                  #9
                  I think I am having a similar problem.

                  I want to do something like this on OnBarUpdate():
                  Code:
                  if (Position.MarketPosition == MarketPosition.Long)
                  {
                  	ExitLongStop (0, false, 1, Low [0], "LongExit", "Long");
                  	EnterShortStop (0, false, 1, Low [0], "Short");
                  }
                  I am getting the 'Ignored PlaceOrder()' message, but I do not know why.

                  I do not want to have to call ExitLong() in OnBarUpdate() because I want to use a stop order - I only want the long to be exited (and the short to be entered) if, and as soon as, the price falls below the previous bar's Low.

                  is there some way of doing this (preferrably one that's compatible with backtesting)?

                  Comment


                    #10
                    piersh, you also run into the 'Internal Order Handling Rules' with this code - http://www.ninjatrader-support.com/H...verview36.html (bottom part of this link).

                    You would need to monitor the needed price for a reversal and then send the needed order to work around.

                    Comment


                      #11
                      To piersh and others who have sent me private messages:

                      I'm kind of amazed a bigger deal has not been made of this issue before now.

                      After documenting the cause ('Internal Order Handling Rules') I was hoping an NT rep could give an explanation as to why the rule is in place (for Entry Stop orders) instead of just saying (paraphrasing) "It has to be that way, live with it."

                      If we knew the underlying logic or rational behind the restriction, it could help us (the developer community/traders) develop a viable workaround.

                      It's obvious complaining is not going to do any good if the reply is "wait till nt7".

                      shawnj

                      Comment


                        #12
                        Originally posted by NinjaTrader_Bertrand View Post
                        You would need to monitor the needed price for a reversal and then send the needed order to work around.
                        is there a way you can do that so it's compatible with backtesting?

                        Comment


                          #13
                          piersh,

                          You can only mimic it by adding more granularity into your backtest. See this reference: http://www.ninjatrader-support2.com/...ead.php?t=6652
                          Josh P.NinjaTrader Customer Service

                          Comment


                            #14
                            Originally posted by shawnj View Post
                            If we knew the underlying logic or rational behind the restriction
                            please correct me if i'm wrong, but i think it's because, in your case you have essentially two conflicting orders, both of which could get filled. at that point you'd have both long & short positions open on the same signal.

                            would it not be sufficient to allow both orders to be submitted, but only to allow one to be filled? or even to have an 'advanced' option to disable NT's reversal handling and to allow the developer to control this?

                            for example, in the breakout case, if the long fills first, then the short cannot fill and is automatically cancelled. maybe they could be linked like this using the signalName (or whatever it's called).

                            same for the stop/limit reversal (which is essentially the breakout case in reverse).


                            alternatively, maybe there's a case to be made for adding a higher-level abstraction of breakout & stopped reversal orders?

                            Comment


                              #15
                              NT7 will provide relaxed rules.
                              Josh P.NinjaTrader Customer Service

                              Comment

                              Latest Posts

                              Collapse

                              Topics Statistics Last Post
                              Started by Geovanny Suaza, 02-11-2026, 06:32 PM
                              0 responses
                              647 views
                              0 likes
                              Last Post Geovanny Suaza  
                              Started by Geovanny Suaza, 02-11-2026, 05:51 PM
                              0 responses
                              369 views
                              1 like
                              Last Post Geovanny Suaza  
                              Started by Mindset, 02-09-2026, 11:44 AM
                              0 responses
                              108 views
                              0 likes
                              Last Post Mindset
                              by Mindset
                               
                              Started by Geovanny Suaza, 02-02-2026, 12:30 PM
                              0 responses
                              572 views
                              1 like
                              Last Post Geovanny Suaza  
                              Started by RFrosty, 01-28-2026, 06:49 PM
                              0 responses
                              573 views
                              1 like
                              Last Post RFrosty
                              by RFrosty
                               
                              Working...
                              X