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

Enter the next day on the opening and exit on the close

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

    Enter the next day on the opening and exit on the close

    Hello NinjaTrader Support Team,

    I am trying to test a simple strategy where the rules are:
    1. If the average 2 day close is less than the average 5 day close, then buy the next day on the opening.
    2. If the average 2 day close is greater than the average 5 day close, then sell short the next day on the opening.
    3. Exit all positions on the close on the same day as the trade entry.

    Having read the multi-time frame & instruments section of the help manual and I made an attempt at scripting the above strategy for testing. Please see below for the ninja 7 script of the above strategy in BOLD but it did not produce the desired output. Specifically, the issues are:

    1. Not all trades were exited on the same day as the entry date
    2. Most entries were between 9:30 am and 9:35 am EST (as per my script) but I noticed some trade entries were executed after 9:35 AM EST, not sure why.

    protected override void Initialize()
    {
    Add(PeriodType.Tick, 1);

    CalculateOnBarClose = false;
    EntriesPerDirection = 1;
    EntryHandling = EntryHandling.AllEntries;

    }

    /// <summary>
    /// Called on each bar update event (incoming tick)
    /// </summary>
    protected override void OnBarUpdate()
    {
    // Checks to ensure all Bars objects contain enough bars before beginning
    if ((CurrentBars[0] <= BarsRequired) || (CurrentBars[1] <= BarsRequired))
    return;

    var sma1 = SMA(this.sma1Val); // fast SMA
    var sma2 = SMA(this.sma2Val); // slow SMA


    if (BarsInProgress == 0)
    {
    if (sma1[1] < sma2[1])
    {
    if (ToTime(Times[1][0]) >= 93000 && ToTime(Times[1][0]) < 93500 && Positions[1].MarketPosition == MarketPosition.Flat)
    {
    //EnterLongLimit(1, Open[0]);
    //EnterLong();
    EnterLong(1, 1, "Long: 1min");
    Print("Long Entry: " + Times[1][0]);
    }
    }

    if (sma1[1] > sma2[1])
    {
    if (ToTime(Times[1][0]) >= 93000 && ToTime(Times[1][0]) < 93500 && Positions[1].MarketPosition == MarketPosition.Flat)
    {
    //EnterShortLimit(1, Open[0]);
    //EnterShort();
    EnterShort(1, 1, "Short: 1min");
    Print("Short Entry: " + Times[1][0]);
    }
    }

    }


    // Exit positions
    if (BarsInProgress == 1)
    {
    if (ToTime(Times[1][0]) >= 161000 && ToTime(Times[1][0]) < 161500 && Positions[1].MarketPosition == MarketPosition.Long)
    {
    ExitLong();
    Print("Long Exit: " + Times[1][0]);
    }

    if (ToTime(Times[1][0]) >= 161000 && ToTime(Times[1][0]) < 161500 && Positions[1].MarketPosition == MarketPosition.Short)
    {
    ExitShort();
    Print("Short Exit: " + Times[1][0]);
    }
    }


    In testing the strategy, I selected the Strategy Analyzer from the File menu in Control Center. Then I right clicked on ES 09-18 and selected Backtest. Please see the values I specified for some of the parameters below:

    Data Series
    - Price based on: last
    - Type: Minute
    - Value: 1

    Order Handling
    - Entries per direction: 1
    - Entry handling: All entries
    - Exit on Close: False

    Can you tell me why my script is not producing the desired output?

    #2
    Hello JackATrader,

    Thanks for your post and welcome to the NinjaTrader forums!

    I don't see where you are adding daily bars and then using the SMA's based on the daily bars. (I also don't see the definitions for sma1Val and sma2Val. As is it would seem to be using tick bars for the SMAs and then minute bars for the SMAs when the BarsInProgress switches (you are setting the SMAs outside of any BarsInProgress control so that means on every tick the SMAs would use tick bars and once a minute that would be minute bars). You might add print statements to help evaluate what is being used.

    As your script is reliant on tick data, make sure that you have the historical tick data for the instrument you are using over the entire backtest period. You can check the historical data by the historical data manager via Tools>Historical data manager > edit, then looking in the instrument and drilling down into the tick folder for each day. Reference: https://ninjatrader.com/support/help...ta_manager.htm
    Paul H.NinjaTrader Customer Service

    Comment


      #3
      Hi Paul,

      Thanks for your fast response.

      I am using the NinjaTrader Continuum (Demo) account and I followed your advice and checked the historical data of ES 09-18 using the Historical Data Manager and there is only minute by minute data.
      Am I able to test my strategy with this demo account data or do I need to subscribe to a data service?

      Comment


        #4
        Hi Jack!
        First of all - when you open Tools->Historical Data you can see two tabs in bottom left "Edit" and "Load". So you can select Load, select your Instrument, set all three checkboxes "Tick" "Minute" "Day", select time range and download your data via Demo continuum account.
        Second one you can select "Exit on session close" checkbox in strategy creation or set
        Code:
        IsExitOnSessionCloseStrategy = true;
        Then add time serie for minute:
        Code:
        AddDataSeries(BarsPeriodType.Minute, 5);
        Select in strategy analyzer Days, so your strategy will operate with day bars and added data serie for minute will close position every day on session close.
        Also you can try this code:
        Code:
            public class TwoFiveDaysClose : Strategy
            {
                private SMA SMA1;
                private SMA SMA2;
                SessionIterator sessionIterator;
                Order sessionOrder;
        
                protected override void OnStateChange()
                {
                    if (State == State.SetDefaults)
                    {
                        Description = @"Enter the description for your new custom Strategy here.";
                        Name = "TwoFiveDaysClose";
                        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;
                        SlowSMA = 5;
                        FastSMA = 2;
                        Quantity = 2000;
                    }
                    else if (State == State.Configure)
                    {
                        //Adding data serie of same instrument to manage closing daily deals
                        AddDataSeries(BarsPeriodType.Minute, 5);
                    }
                    else if (State == State.DataLoaded)
                    {
                        SMA1 = SMA(Close, FastSMA);
                        SMA2 = SMA(Close, SlowSMA);
                        SMA1.Plots[0].Brush = Brushes.Goldenrod;
                        AddChartIndicator(SMA1);
                        sessionIterator = new SessionIterator(Bars);
                    }
                }
        
                protected override void OnBarUpdate()
                {
                    if (CurrentBars[0] < Math.Max(FastSMA, SlowSMA))
                        return;
        
                    if (BarsInProgress == 0) //Daily bars, check on open previous value
                    {
                        if (SMA1[0] < SMA2[0])
                        {
                            sessionOrder = EnterLong(Convert.ToInt32(DefaultQuantity), "");
                        }
                        if (SMA1[0] > SMA2[0])
                        {
                            sessionOrder = EnterShort(Convert.ToInt32(DefaultQuantity), "");
                        }
                    }
                    if (BarsInProgress == 1) //Minute bars, check for close
                    {
        
                        if (Bars.IsFirstBarOfSession)
                        {
                            // use the current bar time to calculate the next session
                            sessionIterator.GetNextSession(Time[0], true);
                        }
                        else
                        //Checks if 15 minutes left for session close
                        if (Time[0].AddMinutes(25) >= sessionIterator.ActualSessionEnd)
                        {
                            if ((sessionOrder != null) && (sessionOrder.OrderState == OrderState.Filled))
                            {
                                if (sessionOrder.OrderAction == OrderAction.Buy) ExitLong("eXit", sessionOrder.Name);
                                if ((sessionOrder.OrderAction == OrderAction.Sell) ||
                                (sessionOrder.OrderAction == OrderAction.SellShort)) ExitShort("eXit", sessionOrder.Name);
                            }
                            else
                            if (sessionOrder != null)
                                CancelOrder(sessionOrder);
                        }
                    }
                }

        Comment


          #5
          Hello JackATrader,

          Thanks for your reply.

          Yes, you can backtest using the live data demo datafeed. To get tick data into your platform, while connected to the live data please create a chart of the ES 09-18 and create the chart using a non time based bar type (found by clicking in the "type" row of the data series when you create the chart) such as volume, renko, renge or tick. Perhaps a 5000 tick bar for example. Then set the days to load for whatever backtest duration you need. Please note that you will likely only be able to get tick data for less than 1 year and it will take longer to load the chart the farther back you go. As such you may want to limit your initial testing to say 30 days of tick data. By creating a chart such as this, the tick data will be downloaded and available when you run your strategy.
          Paul H.NinjaTrader Customer Service

          Comment


            #6
            Hello schattencheg,

            Thanks for your post.

            Please note that JackATrader has posted in the NinjaTrader7 strategy development forums and his code appears to be using NinjaTrader7 type coding. While your contribution is appreciated, as you are posting NT8 coding this would only serve to confuse anyone reading this thread. Please feel free to readjust for NT7, thank-you.
            Paul H.NinjaTrader Customer Service

            Comment


              #7
              Hi schattencheg,

              Thanks for taking to write the code. Though the code in my previous posting was written in NinjaTrader 7, I decided to download NinjaTrader 8 and ran your code in Strategy Analyzer against ES 09-18. Prior to that I also downloaded tick and minute data in Historical Data dating back to 1997. In the Strategy Analyzer, I tested the strategy using Day bars from 01/01/2017 to 20/08/2018. Trading hours was set to CME US Index Futures ETH. The test produced output I didn't quite understand. Almost all of the Long trades were executed at 12:00:00 AM and were exited at around 4:00:00 PM. And the Short Sell trades were exited one or two days prior to the entry date and it does not really make any sense to me. As I am new to NinjaTrader programming and you obviously have a lot of experience with this, your guidance on this is much appreciated.

              Comment


                #8
                Hello JackATrader,

                Thanks for your post.

                I recommend that you either create a new post in the NT8 strategy thread or communicate directly with member schattencheg directly through private messaging to continue. We would like to keep the forum organized by the platform to displace any confusing information. Thanks for your understanding.
                Paul H.NinjaTrader Customer Service

                Comment


                  #9
                  Hi Paul

                  Thanks for your help. It worked!!

                  I followed your approach.... set the Type in the data series under the Strategy Analyzer to Tick and Value was set to 5000 ticks. Time frame from 1/1/2017 to 8/20/2018. After checking the output, all trades were executed around the opening time at 9:30 AM to 9:35 AM and trades closed on the same day around 4:11 PM. Just wanted to clarify, is the timezone of the trade execution the same timezone as the CME exchange time?

                  Just to ensure I fully understand how the coding works... by setting the Chart Type to Tick in the Strategy Analyzer, what time frame would the primary bars object be? Ticks or Days? Within the primary bars code: if (BarsInProgress == 0), when I check for the condition if (sma1[1] < sma2[1]), what time frame am I checking this condition against? Is there a way to check the timeframe?

                  Comment


                    #10
                    Hello JackATrader,

                    Thanks for your reply.

                    The time zone would be whatever you have set your PC time zone to.

                    By setting the bar Type in the strategy analyzer or chart and applying your strategy, the strategy will use whatever is set in the analyzer or chart as the primary (BarsInProgress 0). The SMA check in BarsInProgress0 would then be the 5000 Tick Bars in this case.

                    You may want to review the helpguide multi-time frame section as it clarifies how bars are referenced: https://ninjatrader.com/support/help...nstruments.htm
                    Paul H.NinjaTrader Customer Service

                    Comment

                    Latest Posts

                    Collapse

                    Topics Statistics Last Post
                    Started by ScottWalsh, 04-16-2024, 04:29 PM
                    7 responses
                    34 views
                    0 likes
                    Last Post NinjaTrader_Gaby  
                    Started by cls71, Today, 04:45 AM
                    0 responses
                    5 views
                    0 likes
                    Last Post cls71
                    by cls71
                     
                    Started by mjairg, 07-20-2023, 11:57 PM
                    3 responses
                    214 views
                    1 like
                    Last Post PaulMohn  
                    Started by TheWhiteDragon, 01-21-2019, 12:44 PM
                    4 responses
                    547 views
                    0 likes
                    Last Post PaulMohn  
                    Started by GLFX005, Today, 03:23 AM
                    0 responses
                    3 views
                    0 likes
                    Last Post GLFX005
                    by GLFX005
                     
                    Working...
                    X