Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

beginner help needed for writing a daily strategy

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

    beginner help needed for writing a daily strategy

    Hi, I'm looking into writing and testing strategies in NT8 and for this I would like to backtest a simple breakout strategy based on daily bars, but I'm struggling to get it running correctly.

    At the start of each day the strategy should calculate an offset to be added to the close of the previous day's bar and use this as a long entry stop order for the day. If the order gets filled during the day, it should be closed at the end of the day otherwise the order should just get cancelled. I found a few easylanguage strategies that did something similar with a few lines of code.

    What would be the best approach for doing this in NT8? My latest try was to use daily bars as main dataserie and add minute bars as secondary to place the limit orders on (a technique explained elsewhere on this forum). However, the limit orders never get filled during backtesting, even if the daily candle traverses the limit.

    Any tips to get me started would be appreciated.

    (edit: just realized I've put this in the wrong sub-forum - it should have been in strategy development)
    Last edited by vincat; 10-23-2016, 10:12 AM.

    #2
    Hello vincat,

    For future reference, I am including a link to the NinjaTrader 8 section of the forums.


    If you are testing over a daily bar and you need intra day actions, you will need a secondary data series added to the script. Any orders must be placed using the BarsInProgressIndex of the secondary series.

    Below I am providing a link to a reference sample that demonstrates intra-bar granularity.
    You can submit orders to different Bars objects. This allows you the flexibility of submitting orders to different timeframes. Like in live trading, taking entry conditions from a 5min chart means executing your order as soon as possible instead of waiting until the next 5min bar starts building. You can achieve this by
    Chelsea B.NinjaTrader Customer Service

    Comment


      #3
      Hello Chelsea,

      Thank you for the quick reply. The technique you are referring to is the one I mentionned in my post and it is what I have tried. However, in the strategy analyser, no trades are generated. The historical data I'm using has tick granularity but for backtesting I use the daily timeframe as main dataseries.

      This is my current code, maybe I missed something?

      Code:
      namespace NinjaTrader.NinjaScript.Strategies
      {
      	public class BreakoutStrategyTest : Strategy
      	{
      		private Series<double> Offset;
      		private double stopEntry;
      
      		protected override void OnStateChange()
      		{
      			if (State == State.SetDefaults)
      			{
      				Description							= @"Breakout system test.";
      				Name								= "BreakoutStrategyTest";
      				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.Day;
      				TraceOrders							= false;
      				RealtimeErrorHandling					= RealtimeErrorHandling.StopCancelClose;
      				StopTargetHandling						= StopTargetHandling.PerEntryExecution;
      				BarsRequiredToTrade						= 3;
      				// Disable this property for performance gains in Strategy Analyzer optimizations
      				// See the Help Guide for additional information
      				IsInstantiatedOnEachOptimizationIteration	= false;
      			}
      			else if (State == State.Configure)
      			{
      				// Add minute Bars object to the strategy
      				AddDataSeries(BarsPeriodType.Minute, 1);
      				Offset = new Series<double>(this);
      			}
      		}
      
      		protected override void OnBarUpdate()
      		{
      			if (BarsInProgress == 1) return;
      			
      			var lowOffset = Math.Abs(Close[0] - Low[0]);
      			var highOffset = Math.Abs(Close[0] - High[0]);
      			Offset[0] = Math.Max(lowOffset, highOffset);
      			stopEntry = Close[0] + SMA(Offset, 3)[0];
      			Print("Day: " + Time[0].ToShortDateString() + " " + Time[0].ToShortTimeString() + " - Stop Entry: " + stopEntry.ToString());
      
      			//at least 3 daily bars needed
      			if (CurrentBar < BarsRequiredToTrade) return;
      			
      			Draw.Dot(this, CurrentBar.ToString() + "Entry", false, 0, stopEntry, Brushes.ForestGreen);
      			EnterLongStopMarket(1, true, 1, stopEntry, "BB");
      		}
      		
      	}
      }
      Last edited by vincat; 10-23-2016, 03:55 PM.

      Comment


        #4
        Hello vincat,

        I see you have draw dot added to the script. Are dots appearing on the chart?

        Add TraceOrders = true; to the Initialize() method of the script, compile, open the output window, and run again. In output window do you see messages about orders being placed or ignored?
        Chelsea B.NinjaTrader Customer Service

        Comment


          #5
          Hello Chelsea,

          Yes, I see the dots on the chart.
          But your tip about the TraceOrders-option revealed that the orders are cancelled because of end-of-session handling:

          Code:
          7/01/2015 22:00:00 Strategy 'BreakoutStrategyTest/-1': Entered internal SubmitOrderManaged() method at 7/01/2015 22:00:00: BarsInProgress=1 Action=Buy OrderType=StopMarket Quantity=5 LimitPrice=0 StopPrice=2048,23 SignalName='BB' FromEntrySignal=''
          7/01/2015 22:00:00 Strategy 'BreakoutStrategyTest/-1': Cancelled order due to end of session handling: BarsInProgress=1, orderId='NT-00000-29' account='Backtest' name='BB' orderState=Working instrument='^SP500' orderAction=Buy orderType='Stop Market' limitPrice=0 stopPrice=2048.23 quantity=5 tif=Gtc oco='' filled=0 averageFillPrice=0 onBehalfOf='' id=-1 time='2015-01-07 22:00:00' gtd='2099-12-01' statementDate='2016-10-24'
          My guess is that this happens because the order is placed at the end of the daily bar, where I would need it at the start of the next daily bar (="next bar" option in easylanguage). Is an option available in ninjascript that does this?

          Comment


            #6
            Hello vincat,

            No, instead, you would want to disable the Exit on close in the strategy parameters.
            Chelsea B.NinjaTrader Customer Service

            Comment


              #7
              Hello Chelsea,

              I need the "Exit on Close" option to be active, but was able to resolve the issue by using the minute bar series to place the trade on the first bar of the session. It is now working as expected.

              Code:
              if (BarsInProgress == 1) {
                  if (stopEntry != 0 && Bars.IsFirstBarOfSession) EnterLongStopMarket(1, true, 1, stopEntry, "BB");
                  return;
              }

              Comment


                #8
                Hello vincat,

                This would completely change the logic of the script and orders would not be submitting orders when the daily bar closes. (I'm guessing you are wanting an over night position is this correct?)

                If this is what you are looking for, then you can leave this as is.

                Having the order placed in BarsInProgress 1 would mean the order would be submitted with the secondary bar closes intra day.
                Chelsea B.NinjaTrader Customer Service

                Comment

                Latest Posts

                Collapse

                Topics Statistics Last Post
                Started by ghoul, Today, 06:02 PM
                2 responses
                12 views
                0 likes
                Last Post ghoul
                by ghoul
                 
                Started by jeronymite, 04-12-2024, 04:26 PM
                3 responses
                44 views
                0 likes
                Last Post jeronymite  
                Started by Barry Milan, Yesterday, 10:35 PM
                7 responses
                20 views
                0 likes
                Last Post NinjaTrader_Manfred  
                Started by AttiM, 02-14-2024, 05:20 PM
                10 responses
                180 views
                0 likes
                Last Post jeronymite  
                Started by DanielSanMartin, Yesterday, 02:37 PM
                2 responses
                13 views
                0 likes
                Last Post DanielSanMartin  
                Working...
                X