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.
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", ""); } } } } }
Comment