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

Simple EMA crossover strategy is executing double orders on crossover

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

    Simple EMA crossover strategy is executing double orders on crossover

    I have been working on a strategy in NT 8 which is fairly simple. When I enable it on a chart and run it it's executing double orders in 2 out of 4 conditions and I would like to know what I am missing. I am using the wizard to create the strategy

    Here is my environment -
    3 min chart
    trading hours are set to regular stock/options trading hours i.e. 6:30am to 1pm PST

    The premise is pretty straight forward -
    When a market opens, on the very first bar of the day I want to go long/short if 34ema is above/below 63ema. I am using isFirstBarOfTheSession as 'true' with emas.
    As the crossover happens I exit my long/short and open the opposite position. E.g. At open if ema 34 > ema 63 I go long and when the 34 crosses below 63 I use "exit long" and "enter short"

    In theory it should work but when executing a strategy above I am seeing a situation where my position goes from 1 contract when the market opens and then switches to 2 contracts at the first crossover. How do I fix that? Any help would be appreciated.


    here is the code for my strategy generated by the wizard

    ================================================== ===========
    public class Test : Strategy
    {
    private EMA EMA1;
    private EMA EMA2;

    protected override void OnStateChange()
    {
    if (State == State.SetDefaults)
    {
    Description = @"34 EMA 63 EMA crossover";
    Name = "Test";
    Calculate = Calculate.OnBarClose;
    EntriesPerDirection = 1;
    EntryHandling = EntryHandling.AllEntries;
    IsExitOnSessionCloseStrategy = true;
    ExitOnSessionCloseSeconds = 30;
    IsFillLimitOnTouch = false;
    MaximumBarsLookBack = MaximumBarsLookBack.TwoHundredFiftySix;
    OrderFillResolution = OrderFillResolution.Standard;
    Slippage = 0;
    StartBehavior = StartBehavior.WaitUntilFlat;
    TimeInForce = TimeInForce.Gtc;
    TraceOrders = false;
    RealtimeErrorHandling = RealtimeErrorHandling.StopCancelClose;
    StopTargetHandling = StopTargetHandling.PerEntryExecution;
    BarsRequiredToTrade = 20;
    // Disable this property for performance gains in Strategy Analyzer optimizations
    // See the Help Guide for additional information
    IsInstantiatedOnEachOptimizationIteration = true;
    Ema34 = 34;
    Ema63 = 63;
    }
    else if (State == State.Configure)
    {
    AddDataSeries("ES 06-21", Data.BarsPeriodType.Minute, 3, Data.MarketDataType.Last);
    }
    else if (State == State.DataLoaded)
    {
    EMA1 = EMA(Close, Convert.ToInt32(Ema34));
    EMA2 = EMA(Close, Convert.ToInt32(Ema63));
    }
    }

    protected override void OnBarUpdate()
    {
    if (BarsInProgress != 0)
    return;

    if (CurrentBars[0] < 1)
    return;

    // Set 1
    if (CrossAbove(EMA1, EMA2, 1))
    {
    EnterLong(Convert.ToInt32(DefaultQuantity), "");
    ExitShort(Convert.ToInt32(DefaultQuantity), "", "");
    }

    // Set 2
    if (CrossBelow(EMA1, EMA2, 1))
    {
    EnterShort(Convert.ToInt32(DefaultQuantity), "");
    ExitLong(Convert.ToInt32(DefaultQuantity), "", "");
    }

    // Set 3
    if ((EMA1[0] < EMA2[0])
    && (Bars.IsFirstBarOfSession == true))
    {
    EnterShort(Convert.ToInt32(DefaultQuantity), "");
    }

    // Set 4
    if ((EMA1[0] > EMA2[0])
    && (Bars.IsFirstBarOfSession == true))
    {
    EnterLong(Convert.ToInt32(DefaultQuantity), "");
    }

    }

    ================================================== ===========
    Last edited by vpatanka; 04-27-2021, 11:43 AM.

    #2
    Hello vpatanka,

    Thank you for your post.

    I see you are calling an exit order method and entry order method on the same bar. The most common reason the behavior you are reporting occurs is because an exit method and entry method are both submitted on the same bar.

    Calling an exit order and an entry order on the same pass of OnBarUpdate will result in either the strategy position entering the opposite position with double the quantity or will result in an Overfill.

    If you want to reverse the position, call an entry order in the opposite direction of the position without calling an exit method first. For example, if the position is long then call EnterShort(). NinjaTrader will automatically send a Close position order and then send another order as the entry order to enter the opposite direction.

    An example of this could be seen by viewing the code for the Sample MA Crossover strategy that comes with NinjaTrader. To view the strategy's code, open a New > NinjaScript Editor window, open the Strategies folder, and select the SampleMACrossOver strategy.

    See this forum thread for more information - https://ninjatrader.com/support/foru...op#post1036616

    Let us know if we may assist further.
    Brandon H.NinjaTrader Customer Service

    Comment


      #3
      Originally posted by NinjaTrader_BrandonH View Post
      Hello vpatanka,

      Thank you for your post.

      I see you are calling an exit order method and entry order method on the same bar. The most common reason the behavior you are reporting occurs is because an exit method and entry method are both submitted on the same bar.

      Calling an exit order and an entry order on the same pass of OnBarUpdate will result in either the strategy position entering the opposite position with double the quantity or will result in an Overfill.

      If you want to reverse the position, call an entry order in the opposite direction of the position without calling an exit method first. For example, if the position is long then call EnterShort(). NinjaTrader will automatically send a Close position order and then send another order as the entry order to enter the opposite direction.

      An example of this could be seen by viewing the code for the Sample MA Crossover strategy that comes with NinjaTrader. To view the strategy's code, open a New > NinjaScript Editor window, open the Strategies folder, and select the SampleMACrossOver strategy.

      See this forum thread for more information - https://ninjatrader.com/support/foru...op#post1036616

      Let us know if we may assist further.

      Oh i see. Let me try that out and will let you know if I run into any issues. Thanks a lot !

      Comment


        #4
        Originally posted by vpatanka View Post


        Oh i see. Let me try that out and will let you know if I run into any issues. Thanks a lot !
        Hello There,

        I updated my strategy code to remove 'Exit Long' and 'Exit Short' as suggested and that seemed to work well. However, this evening I noticed that the strategy executed a trade after hours which it shouldn't have. I have my data series for 3 min chart with trading hours set as 6:30am - 1pm PST. There was a closing trade 30 seconds before market close at 12:59:31 per strategy which was correct. This evening I noticed that my position went long again (/ES) at 7:56:11PM which it shouldn't have executed. I am not sure why that would be as the candles on my chart stopped at 1pm. Any idea why this would happen.

        btw - I was just looking into it and the trade that happened at 7:56:11pm today is showing up as 'Synchronize'. My strategy is set with "Immediately Submit, Synchronize account'. Having said that the synchronization should be only within the trading hours defined for the chart correct or am I missing something?
        Last edited by vpatanka; 04-28-2021, 11:56 PM.

        Comment


          #5
          Hello vpatanka,

          Thank you for your note.

          If you are using Immediately Submit, Synchronize Account and enable the strategy outside of market hours this behavior could occur.

          Immediately Submit automatically submits working orders from when the strategy processed historical data, and assumes the strategy position and account position are where you want it when you enable the strategy. This is typically used to have a strategy resume a position after disabling/enabling. If the strategy already had live orders running, the orders will resume with the new enablement of the strategy if they match the historically calculated orders. If the orders calculated from historical data do not match the live working orders, the live working orders will be canceled and replaced by those calculated from historical data. The name of the order placed by the strategy to synchronize the strategy position and account position will be 'Synchronize'.

          I suggest either waiting until the session opens to enable your strategy or use Immediate Submit without Synchronize Account to prevent a synchronize order from being placed outside of market hours.

          We currently have an internal feature request for allowing synchronization orders to only be placed during market hours. I have added your vote to the feature request.

          The internal tracking number for your feature request is SFT-4389. Please reference this internal tracking number when contacting Platform Support if you ever have questions regarding this feature request.

          When a feature request is implemented, you'll find a description of the new feature in the release notes:Let us know if we may assist further.

          Brandon H.NinjaTrader Customer Service

          Comment


            #6
            Originally posted by NinjaTrader_BrandonH View Post
            Hello vpatanka,

            Thank you for your note.

            If you are using Immediately Submit, Synchronize Account and enable the strategy outside of market hours this behavior could occur.

            Immediately Submit automatically submits working orders from when the strategy processed historical data, and assumes the strategy position and account position are where you want it when you enable the strategy. This is typically used to have a strategy resume a position after disabling/enabling. If the strategy already had live orders running, the orders will resume with the new enablement of the strategy if they match the historically calculated orders. If the orders calculated from historical data do not match the live working orders, the live working orders will be canceled and replaced by those calculated from historical data. The name of the order placed by the strategy to synchronize the strategy position and account position will be 'Synchronize'.

            I suggest either waiting until the session opens to enable your strategy or use Immediate Submit without Synchronize Account to prevent a synchronize order from being placed outside of market hours.

            We currently have an internal feature request for allowing synchronization orders to only be placed during market hours. I have added your vote to the feature request.

            The internal tracking number for your feature request is SFT-4389. Please reference this internal tracking number when contacting Platform Support if you ever have questions regarding this feature request.

            When a feature request is implemented, you'll find a description of the new feature in the release notes:Let us know if we may assist further.
            Got it. That makes sense. I will make sure to use enable/disable only during my trading hours set for the chart. Thanks for the info regarding the feature request.

            Comment

            Latest Posts

            Collapse

            Topics Statistics Last Post
            Started by techgetgame, Yesterday, 11:42 PM
            0 responses
            8 views
            0 likes
            Last Post techgetgame  
            Started by sephichapdson, Yesterday, 11:36 PM
            0 responses
            2 views
            0 likes
            Last Post sephichapdson  
            Started by bortz, 11-06-2023, 08:04 AM
            47 responses
            1,613 views
            0 likes
            Last Post aligator  
            Started by jaybedreamin, Yesterday, 05:56 PM
            0 responses
            10 views
            0 likes
            Last Post jaybedreamin  
            Started by DJ888, 04-16-2024, 06:09 PM
            6 responses
            20 views
            0 likes
            Last Post DJ888
            by DJ888
             
            Working...
            X