Announcement

Collapse

Looking for a User App or Add-On built by the NinjaTrader community?

Visit NinjaTrader EcoSystem and our free User App Share!

Have a question for the NinjaScript developer community? Open a new thread in our NinjaScript File Sharing Discussion Forum!
See more
See less

Partner 728x90

Collapse

My strategy only places stop and profit target orders 1 bar later. Why?

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

    My strategy only places stop and profit target orders 1 bar later. Why?

    Hello,

    I am using some software to automatically generate trading strategies. I am using NT7 connected to Interactive Brokers. Below is a sample of my generated trading code and it runs intraday. I want the strategy to enter long with a market order, then immediately place the calculated stop loss and target profit orders.

    Unfortunately this does not happen. It enters long, then it only adds the stop and profit target orders after 1 more bar of time has passed. The behaviour is the same whether I run such strategies on 60 min bars or 1 minute bars. 60 minutes is scary long time to wait without a stop!

    Why is this happening? And how can I make it so the stop and target orders are placed immediately after the entry market order is placed (and ideally filled)?

    In the code, the order gets placed then it does pos1 = 1; which should allow it to enter the if (pos1 == 1) section but this only seems to happen 1 bar later.

    I would be very grateful for any insight you may have.

    Code:
    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;
    
    namespace NinjaTrader.Strategy
    {
        public class BAnewport : Strategy
        {
            private DataSeries myDataSeries;
            protected override void Initialize()
            {
                myDataSeries = new DataSeries(this,MaximumBarsLookBack.Infinite);
                CalculateOnBarClose = true;
            }
    
            int length = 20;
    
            private int long_on_1 = 1;
            private int Profx1 = 0;
            private int Profx1_s = 0;
            private int Profcloses1 = 4;
            private int Maxtime1 = 5;
            private int HH1 = 1;
            private int LL1 = 0;
            private int PT_ON1 = 1;
            private int SL_ON1 = 1;
            private double PT1 = 0;
            private double SL1 = 0;
            private int mp1 = 0;
            private int pos1 = 0;
    
    
            protected override void OnBarUpdate()
            {
    
                if (Position.MarketPosition == MarketPosition.Flat && BarsInProgress == 0)
                {
                    pos1 = 0; Profx1 = 0; Profx1_s = 0;
                }
    
                if (BarsInProgress == 0 && Position.MarketPosition == MarketPosition.Flat  && ADX(20)[0] <= 35 && High[4] <= High[9] && StochasticsFast(3,14).K[0] >= 20)
                {
                    EnterLong(20000,"EntryBAnewport");
                    pos1 = 1;
                    PT1 = (Close[0]+ATR(20)[0]*1.25);
                    SL1 = (Close[0]-ATR(20)[0]*1.25);
                    Profx1 = 0;
                }
    
                if (pos1 == 1) 
                {
                    if (BarsSinceEntry(BarsInProgress,"EntryBAnewport",0) >= Maxtime1-1) { ExitLong("Timex1",""); }
                    if (BarsSinceEntry(BarsInProgress,"EntryBAnewport",0) > 0 && Close[0] >= Position.AvgPrice) { Profx1 += 1; }
                    if (Profx1 >= Profcloses1) { ExitLong("Profx1",""); }
                    if (HH1 == 1) { ExitLongLimit((MAX(High,5)[1]),"HHx1",""); }
                    if (LL1 == 1) { ExitLongStop((MIN(Low,5)[1]),"LLx1",""); }
                    if (PT_ON1 == 1) { ExitLongLimit(PT1,"PT1",""); }
                    if (SL_ON1 == 1) { ExitLongStop(SL1,"SL1",""); }
                    // if (ToTime(Time[0]) >= 000000) { ExitLong("EndOfDay", ""); }
                }
    
            }
        }
    }

    #2
    Hello tradingtrader,
    Thanks for your post.

    You could make your strategy submit your profit target and stop loss orders immediately after your entry by placing them inside the same condition as your entry. Something like the following snippet would submit all three on the same bar with a 10 tick stop loss and 10 tick profit target.
    Code:
    		protected override void OnBarUpdate()
    		{
    			if ([COLOR="Green"]//your entry conditions//[/COLOR])
    				EnterLong("entryOrder");
    				SetProfitTarget("entryOrder", CalculationMode.Ticks,10);
    				SetStopLoss("entryOrder",CalculationMode.Ticks, 10, false);
    		}
    That being said, I highly suggest adding some Print() statements to your code and seeing where your conditions are becoming true. You mentioned that the "if (pos1 == 1)" condition becoming true should allow your other orders to be placed, but there are other conditions inside that statement that would need to become true as well for anything to happen.

    The following forum post discusses how to utilize Print() statements to debug your code.
    Debugging your NinjaScript Code
    https://ninjatrader.com/support/foru...49&postcount=2

    Please let me know if you have any further questions.
    Josh G.NinjaTrader Customer Service

    Comment


      #3
      Hi JoshG,

      Thank you for your quick response, and thank you for the suggestion that I can use Print statements in Ninjatrader! I did not realize that and it's extremely useful for debugging.

      So I tried out your suggestion and here is what I found. (I have removed the indicator entry logic for simplicity's sake).

      When I use this code, everything works exactly as it should. My order is placed, and the stop and target is placed immediately.

      Code:
                  if (BarsInProgress == 0 && Position.MarketPosition == MarketPosition.Flat )
                  {
                      EnterLong(10000,"EntryBAnewport");
                      Print("Just went long " + DateTime.Now + "\n");
                      pos1 = 1;
                      PT1 = (Close[0]+ATR(20)[0]*1.25);
                      SL1 = (Close[0]-ATR(20)[0]*1.25);
                      Profx1 = 0;
                      SetProfitTarget("EntryBAnewport", CalculationMode.Ticks,10);
                      Print("Target set " + DateTime.Now + "\n");
                      SetStopLoss("EntryBAnewport",CalculationMode.Ticks, 10, false);
                      Print("Stop set " + DateTime.Now + "\n");
                  }
      My strategy requires that I use specific prices for the stop and target (see the PT1 and SL1 calculations) so I modified the code to use the previous ExitLongLimit and ExitLongStop functions. Shown here:

      Code:
                  if (BarsInProgress == 0 && Position.MarketPosition == MarketPosition.Flat )
                  {
                      EnterLong(10000,"EntryBAnewport");
                      Print("Just went long " + DateTime.Now + "\n");
                      pos1 = 1;
                      PT1 = (Close[0]+ATR(20)[0]*1.25);
                      SL1 = (Close[0]-ATR(20)[0]*1.25);
                      Profx1 = 0;
                      ExitLongLimit(PT1,"PT1","EntryBAnewport");
                      Print("Target set " + DateTime.Now + "\n");
                      ExitLongStop(SL1,"SL1","EntryBAnewport");
                      Print("Stop set " + DateTime.Now + "\n");
                  }
      However, when I do this, the initial order is placed, but now the stop and target orders literally do not get placed at all! They don't get created 1 bar later, they literally never show up in IB. The debug output from the Print statements suggests that the orders were set, but they in fact never were.

      I am wondering now if this is a problem with ExitLongStop and ExitLongLimit and Interactive Brokers? Or am I using those functions incorrectly?

      This is my debug output:
      Just went long 2/15/2018 3:06:02 PM
      Target set 2/15/2018 3:06:02 PM
      Stop set 2/15/2018 3:06:02 PM

      And here is the output from my Ninjatrader log file. (I have censored my account number.)

      Code:
      2/15/2018 3:05:01 PM|1|128|Enabling NinjaScript strategy 'BAnewport/f40d60f3964342d9bf6febcc399136aa' : On starting a real-time strategy - StrategySync=WaitUntilFlat SyncAccountPosition=False EntryHandling=AllEntries EntriesPerDirection=1 StopTargetHandling=PerEntryExecution ErrorHandling=StopStrategyCancelOrdersClosePositions ExitOnClose=True/ triggering 30 before close Set order quantity by=Strategy ConnectionLossHandling=Recalculate DisconnectDelaySeconds=10 CancelEntryOrdersOnDisable=False CancelExitOrdersOnDisable=False CalculateOnBarClose=True MaxRestarts=4 in 5 minutes
      2/15/2018 3:06:02 PM|1|32|Order='93771357344e44638077c0c4a7d88014/U15xxxxx' Name='EntryBAnewport' New state=PendingSubmit Instrument='$AUDUSD' Action=Buy Limit price=0 Stop price=0 Quantity=0.01M Type=Market Filled=0 Fill price=0 Error=NoError Native error=''
      2/15/2018 3:06:02 PM|2|4|Order Event Warning:Attribute 'Outside Regular Trading Hours' is ignored based on the order type and destination. PlaceOrder is now being processed. 2109
      2/15/2018 3:06:02 PM|2|32|Order Message: BUY 10K AUD.USD Forex Warning: Your order size is below the AUD 25000 IdealPro minimum and will be routed as an odd lot order.
      2/15/2018 3:06:02 PM|1|32|Order='157953365/U15xxxxx' Name='EntryBAnewport' New state=Accepted Instrument='$AUDUSD' Action=Buy Limit price=0 Stop price=0 Quantity=0.01M Type=Market Filled=0 Fill price=0 Error=NoError Native error=''
      2/15/2018 3:06:02 PM|1|32|Order='157953365/U15xxxxx' Name='EntryBAnewport' New state=Working Instrument='$AUDUSD' Action=Buy Limit price=0 Stop price=0 Quantity=0.01M Type=Market Filled=0 Fill price=0 Error=NoError Native error=''
      2/15/2018 3:06:02 PM|1|32|Order='157953365/U15xxxxx' Name='EntryBAnewport' New state=Filled Instrument='$AUDUSD' Action=Buy Limit price=0 Stop price=0 Quantity=0.01M Type=Market Filled=10000 Fill price=0.79389 Error=NoError Native error=''
      2/15/2018 3:06:02 PM|1|16|Execution='$AUDUSD/00012258.5a80c538.01.01' Instrument='$AUDUSD' Account='U15xxxxx' Exchange=IBIdealPro Price=0.79389 Quantity=0.01M Market position=Long Operation=Insert Order='157953365' Time='2/15/2018 3:06:02 PM' Multiplier=1E-05
      2/15/2018 3:06:03 PM|1|64|Instrument='$AUDUSD' Account='U15xxxxx' Avg price=0.79409 Quantity=0.01M Market position=Long Operation=Insert Currency=UsDollar
      Thanks!

      Comment


        #4
        Hello tradingtrader,
        Thanks for your note.

        Those orders are being ignored when the entry order happens because you are not in a long position yet. Once your entry order is placed you are having to wait for your conditions to become true again before your exit orders are being placed.

        ExitLongStop()
        https://ninjatrader.com/support/help...itlongstop.htm

        ExitLongLimit()
        https://ninjatrader.com/support/help...tlonglimit.htm

        You said your reasoning for switching back to ExitLongLimit and ExitStop orders was because you needed specific price values. Why do you not just put those price values inside StopLoss and ProfitTarget? It sounds to me like what you want to do will require switching back to the StopLoss and ProfitTarget order methods similar to the snippet below.

        Code:
        		protected override void OnBarUpdate()
        		{
        			if ([COLOR="Green"]//your entry conditions//[/COLOR])
        				EnterLong("entryOrder");
        				SetProfitTarget("entryOrder", CalculationMode.Price,PT1);
        				SetStopLoss("entryOrder",CalculationMode.Price, SL1, false);
        		}
        I am including some relevant help guide documentation below that I believe you will find helpful.

        Order Methods
        https://ninjatrader.com/support/help...er_methods.htm

        Understanding the Managed Approach
        https://ninjatrader.com/support/help...d_approach.htm

        Please let me know if you have any further questions.
        Josh G.NinjaTrader Customer Service

        Comment


          #5
          Aha! I did not realize that ExitLongLimit and ExitLongStop require the initial long order to be fully filled before the subsequent orders can be placed. It all makes sense now. SetProfitTarget and SetStopLoss should indeed solve my problem.

          Thank you Josh. I am very impressed with Ninjatrader's support.

          Comment

          Latest Posts

          Collapse

          Topics Statistics Last Post
          Started by CortexZenUSA, Today, 12:53 AM
          0 responses
          1 view
          0 likes
          Last Post CortexZenUSA  
          Started by CortexZenUSA, Today, 12:46 AM
          0 responses
          1 view
          0 likes
          Last Post CortexZenUSA  
          Started by usazencortex, Today, 12:43 AM
          0 responses
          5 views
          0 likes
          Last Post usazencortex  
          Started by sidlercom80, 10-28-2023, 08:49 AM
          168 responses
          2,265 views
          0 likes
          Last Post sidlercom80  
          Started by Barry Milan, Yesterday, 10:35 PM
          3 responses
          12 views
          0 likes
          Last Post NinjaTrader_Manfred  
          Working...
          X