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

exit on bar close

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

    exit on bar close

    trying to create a strategy to backtest on historical data that buys on a certain 1 hour candle open and sell on the close of the same candle
    i came up with this code but it dosent seem to work

    the logic:
    buy on the first 1 minute bar
    then check if 59 bars have passed (BarsSinceEntry) if yes then exit on the 59th 1 minute bar. thus we have entered at open of the 1 hour bar (not exactly at the open but close ) and exited at close as 59 minutes is a hour.

    theoreticaly when i run this code on the 1 hour candle it should show a buy close to Open and exit close to Close

    but its not working
    how do i fix it

    here is the code
    Code:
     protected override void Initialize()
            {
                CalculateOnBarClose = true;
                // primary bar is 60 minute 
    	    Add(PeriodType.Minute,1 );
            }
    
            /// <summary>
            /// Called on each bar update event (incoming tick)
            /// </summary>
            protected override void OnBarUpdate()
            {
    			
    			
    		if ( BarsInProgress == 1 && Position.MarketPosition == MarketPosition.Flat )
    			{
    				EnterLong(1,100,"buy");
    			}
    			if (BarsSinceEntry(1,"buy",0)== 59)
    			{
    				ExitLong();
    			}
    			
    			
            }
    thanks in advance

    #2
    Hello maaz1598,

    Thanks for your post.

    In the case of BarsSinceEntry() in a multi time frame strategy it appears that it will use the BarsInProgress of 0. If you apply your strategy to 60 minute bars and set the exitonclose to false, you will see that it will exit exactly after 59 60 minute bars.

    Here is some code that will allow you to accomplish your goal:

    Code:
            #region Variables
    			private int saveBar;
            #endregion
    
            protected override void Initialize()
            {
                CalculateOnBarClose = true;
    			 Add(PeriodType.Minute,1 );
            }
            protected override void OnBarUpdate()
            {
    			if ( BarsInProgress == 1 && Position.MarketPosition == MarketPosition.Flat )
    			{
    				EnterLong(1,100,"buy");
    				saveBar = CurrentBar;
    			}
    					
    			if (BarsInProgress == 1 && Position.MarketPosition != MarketPosition.Flat)  // if long or short
    			{
    				if (CurrentBar - saveBar == 59)
    				{
    					ExitLong();
    				}
    			}
            }
    Paul H.NinjaTrader Customer Service

    Comment


      #3
      getting really really close

      thanks paul for the code
      still its not working properly but we are getting really really close
      if you take a look at the attachment "exit on close 1" you will see that on the first day it works perfectly but when it goes to the next day it stuffs up, this is expected as trading starts 9:30 (there is a extra 30min which continues the next day) this not the main issue but i would be really thank full if you have a solution to that (haven't got around to that issue yet )

      the real issue is inconsistency

      if you look at attachment "exit on close 2" you will see that the first candle makes a perfect trade but then from there of it goes bad the second candle executes at the correct price levels but it sells on the next candle, and for there on it becomes randomly, this appears in many other chart
      example "exit on close 3" i cant find a reason for this inconsistency (its not the last candle of the day)
      how do i fix it ?

      note ;
      i am aware that one inconsistency disrupts all the rest of the trades from there on due to the way code is written, so the issue to fix would only be the the first inconsistent candle which will fix the rest
      Attached Files

      Comment


        #4
        Hello maaz1598,

        Thanks for your post.

        What instrument(s) are you applying this strategy to?

        What session template is being used?

        Is your entry logic different than what has already been posted?
        Paul H.NinjaTrader Customer Service

        Comment


          #5
          troubleshoot

          1)i dont remember exactly which instrument those snap shot was taken of but this phenomena occurs on nearly every stock see attachment for the stock AGI@NYSE

          2)US RTH is being used

          3)the entry logic is exactly the same except that i added "CurrentBar > saveBar" inside the first "if " statement so that the strategy dosent buy twice on the same candle

          Code:
          if ( BarsInProgress == 1 && Position.MarketPosition == MarketPosition.Flat && [U][I][B]CurrentBar > saveBar[/B][/I][/U])
          			{
          				EnterLong(1,100,"buy");
          				saveBar = CurrentBar;
          			}
          Attached Files

          Comment


            #6
            Hello maaz1598,

            Thanks for your reply.

            You are on the right track with your entry logic except that the check needs to be not of the 1 minute bar but of the 60 minute bar so CurrentBar in this case would be CurrentBars[0] to refer to the primary series which is the 60 minute bars. This also means that the saveBar then must also refer to the 60 minute bars as the issue is to not have two orders in the same 60 minute bar. So we really need a saveBar for the 60 minute but we still also need one for the 1 minute bars so we can count the bars.

            I changed the code to this:
            Code:
            			if ( BarsInProgress == 1 && Position.MarketPosition == MarketPosition.Flat && CurrentBars[0] > saveBar)
            			{
            				EnterLong(1,100,"buy");
            				saveBar = CurrentBars[0];
            				saveBar1 = CurrentBar;
            			}
            									
            			if (BarsInProgress == 1 && Position.MarketPosition != MarketPosition.Flat)  // if long or short
            			{
            				if (CurrentBar - saveBar1 == 58)
            				{
            					ExitLong();
            				}
            			}
            Note that I also change the number of bars check to 58 as we are using COBC data so we need close one bar sooner to fit within the 60 minute bar execution. So this code produced the backtest result of maaz-2 attached. In review of this picture you can see that the entry and exit is exactly on the same bar, however the first bar in each session is not used.

            To resolve the final issue of the first bar, I added further code that detects the first bar of the session for the 1 minute bars and then if flat enters the order. This section of code would then only execute on first bar of session detection, there after the second section will place the remaining orders:

            Code:
                    protected override void OnBarUpdate()
                    {
            			if (BarsInProgress == 1 && BarsArray[1].FirstBarOfSession && Position.MarketPosition == MarketPosition.Flat)
            			{
            				EnterLong(1,100,"buy");
            				saveBar = CurrentBars[0];
            				saveBar1 = CurrentBar;
            			}
            			
            			if ( BarsInProgress == 1 && Position.MarketPosition == MarketPosition.Flat && CurrentBars[0] > saveBar)
            			{
            				EnterLong(1,100,"buy");
            				saveBar = CurrentBars[0];
            				saveBar1 = CurrentBar;
            			}
            									
            			if (BarsInProgress == 1 && Position.MarketPosition != MarketPosition.Flat)  // if long or short
            			{
            				if (CurrentBar - saveBar1 == 58)
            				{
            					ExitLong();
            				}
            			}
                    }
            Please see the attached picture maaz-3 which shows one order on every bar.
            Attached Files
            Paul H.NinjaTrader Customer Service

            Comment

            Latest Posts

            Collapse

            Topics Statistics Last Post
            Started by elderan, Today, 08:03 PM
            0 responses
            2 views
            0 likes
            Last Post elderan
            by elderan
             
            Started by algospoke, Today, 06:40 PM
            0 responses
            10 views
            0 likes
            Last Post algospoke  
            Started by maybeimnotrader, Today, 05:46 PM
            0 responses
            8 views
            0 likes
            Last Post maybeimnotrader  
            Started by quantismo, Today, 05:13 PM
            0 responses
            7 views
            0 likes
            Last Post quantismo  
            Started by AttiM, 02-14-2024, 05:20 PM
            8 responses
            169 views
            0 likes
            Last Post jeronymite  
            Working...
            X