Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

Help Condition Problems (Limiting time since last trade and if price goes below)

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

    Help Condition Problems (Limiting time since last trade and if price goes below)

    I have my code working, but it is still not executing two conditions.

    1. I want it to not place an order if there has been a sell within the last 1.5 hours
    2. I want to sell long position if it crosses below the indicator that I required for its purchase within 25 minutes of its order

    I thought the code looked correct to execute these two conditions but when I looked back through the charts there are order executions within 1.5 hours of each other and sometimes the price crosses back below the SMA(400) within 25 minutes of purchasing it and it doesn't sell!

    Basically my strategy is trying to buy long positions if the prices crosses the SMA(400) when the SMA(400)>SMA(100) [works] and sell when it crosses the SMA(50) [works]. But if I can get the two conditions listed above to work, my strategy will get me out of losing positions faster and prevent series of buy/sell orders when the SMA(400) and SMA(100) are very close


    /// <summary>
    /// This method is used to configure the strategy and is called once before any strategy method is called.
    /// </summary>
    protected override void Initialize()
    {
    Add(SMA(400));
    Add(SMA(100));

    CalculateOnBarClose = false;
    }

    /// <summary>
    /// Called on each bar update event (incoming tick)
    /// </summary>
    protected override void OnBarUpdate()
    {
    // Condition set 1
    if ((BarsSinceExit() > 90 || BarsSinceExit() == -1)
    && Close[0] > SMA(400)[0]
    && SMA(400)[0] > SMA(100)[0])
    {
    EnterLong(DefaultQuantity, "");
    }

    // Condition set 2
    if (Close[0] < SMA(100)[0])
    {
    ExitLong("", "");
    }

    // Condition set 3
    if (Close[0] < SMA(400)[0]
    && BarsSinceEntry() < 25)
    {
    ExitLong("", "");
    }
    }

    #region Properties
    #endregion
    }
    }


    Thank you!

    #2
    Originally posted by volhog View Post
    I have my code working, but it is still not executing two conditions.

    1. I want it to not place an order if there has been a sell within the last 1.5 hours
    2. I want to sell long position if it crosses below the indicator that I required for its purchase within 25 minutes of its order

    I thought the code looked correct to execute these two conditions but when I looked back through the charts there are order executions within 1.5 hours of each other and sometimes the price crosses back below the SMA(400) within 25 minutes of purchasing it and it doesn't sell!

    Basically my strategy is trying to buy long positions if the prices crosses the SMA(400) when the SMA(400)>SMA(100) [works] and sell when it crosses the SMA(50) [works]. But if I can get the two conditions listed above to work, my strategy will get me out of losing positions faster and prevent series of buy/sell orders when the SMA(400) and SMA(100) are very close


    /// <summary>
    /// This method is used to configure the strategy and is called once before any strategy method is called.
    /// </summary>
    protected override void Initialize()
    {
    Add(SMA(400));
    Add(SMA(100));

    CalculateOnBarClose = false;
    }

    /// <summary>
    /// Called on each bar update event (incoming tick)
    /// </summary>
    protected override void OnBarUpdate()
    {
    // Condition set 1
    if ((BarsSinceExit() > 90 || BarsSinceExit() == -1)
    && Close[0] > SMA(400)[0]
    && SMA(400)[0] > SMA(100)[0])
    {
    EnterLong(DefaultQuantity, "");
    }

    // Condition set 2
    if (Close[0] < SMA(100)[0])
    {
    ExitLong("", "");
    }

    // Condition set 3
    if (Close[0] < SMA(400)[0]
    && BarsSinceEntry() < 25)
    {
    ExitLong("", "");
    }
    }

    #region Properties
    #endregion
    }
    }


    Thank you!
    Care to show some pictures of where on a chart your expectations are not being met?

    Comment


      #3
      Trades that executed w/in 90 min or didn't sell after crossing back SMA(400)


      Executed another trade within 90 minutes and did not sell the first after crossing back below SMA(400) within 25 minutes




      Did not sell after crossing back below SMA(400) within 25 min of purchase


      Execute within 90min


      Did not sell after crossing back below SMA(400) within 25 min of purchase

      Comment


        #4
        Hello volhog,

        For your Exit orders its is hard to tell which SMA is which because it is looking like they are executing on the crossing of Close which should be correct.

        You may want to change the plot colors like in our SampleMACrossOver strategy so it is easier to tell which one is which for example:

        Code:
        protected override void Initialize()
        {
        	SMA(400).Plots[0].Pen.Color = Color.Orange;
        	SMA(100).Plots[0].Pen.Color = Color.Green;
                Add(SMA(400));
                Add(SMA(100));
        }
        As for entering within 90 minutes, the code seems to be correct. What dates are you looking at on the Strategy Analyzer that are getting these results and what From and To date do you have it set to?
        JCNinjaTrader Customer Service

        Comment


          #5
          The dates on this backtest are on AAPL from 12/9/2013 to 12/20/2013.

          SMA(400) now in green
          SMA(100) now in red


          As you can see here the price went below the SMA(400) within 25 minutes of purchase and it did not sell



          Here a sell was executed at 11:55 am and then a purchase was execute at 12:55pm, which is less than 90 minutes. I want it to prevent orders from occuring within 90 minutes of the last exit. This will keep the strategy from buying/selling like crazy when the SMA(400) and SMA(100) are close.


          Another Buy/Sell within 90 minutes of each other


          Another sell that should have occurred earlier when the price crossed back under the SMA(400)\


          I know what I want to happen, but I just may be using the wrong code. Thanks for the help!

          Comment


            #6
            Hello volhog,

            Thanks for the screenshots.

            I have a few questions for you.

            Regarding the exits that should happen when the price closes below the SMA's are you asking why these are not happening no the same bar as the cross and instead are showing on the next bar?
            I ask because I am seeing exits after these crosses.

            If this is your question, this would be due to CalculateOnBarClose being set to true. While this is set to true, the cross trigger is not evaluated until the bar closes and thus shows on the next bar. If you set this to false, either in the code or in the strategy parameters, then this will be evaluated on the next received piece of data, intra-bar and would show on the same bar.

            Below is a link to the help guide on a description of Multi-Time Frame & Instruments and CalculateOnBarClose.
            Multi-Time Frame & Instruments (please read the How Bar Data is Referenced
            section) - http://www.ninjatrader.com/support/h...nstruments.htm
            CalculateOnBarClose - http://www.ninjatrader.com/support/h...onbarclose.htm

            You mention that you do not want orders to be made within 90 minutes of each other. May I confirm that this is only for entry orders and exit orders are allowed within 90 minutes of each other?

            Regarding just the entries happening within 90 bars of each other, I was not able to reproduce this on my end using your code. All entries I have on my chart are not within 90 minutes of each other. Have you updated the code and not removed/re-added this to the chart?

            What date is your chart showing? What time zone are you in?

            This is so I can try and match up my chart.
            Last edited by NinjaTrader_ChelseaB; 12-23-2013, 01:41 PM.
            Chelsea B.NinjaTrader Customer Service

            Comment


              #7
              It certainly appears that this block is not being entered:
              Code:
              // Condition set 3
                          if (Close[0] < SMA(400)[0]
                              && BarsSinceEntry() < 25)
                          {
                              ExitLong("", "");
                          }
              You may want to Print() the variables to the Output Window to see why.

              Comment


                #8
                Originally posted by NinjaTrader_ChelseaB View Post
                Hello volhog,

                Thanks for the screenshots.

                I have a few questions for you.

                Regarding the exits that should happen when the price closes below the SMA's are you asking why these are not happening no the same bar as the cross and instead are showing on the next bar?
                I ask because I am seeing exits after these crosses.

                If this is your question, this would be due to CalculateOnBarClose being set to true. While this is set to true, the cross trigger is not evaluated until the bar closes and thus shows on the next bar. If you set this to false, either in the code or in the strategy parameters, then this will be evaluated on the next received piece of data, intra-bar and would show on the same bar.

                Below is a link to the help guide on a description of Multi-Time Frame & Instruments and CalculateOnBarClose.
                Multi-Time Frame & Instruments (please read the How Bar Data is Referenced
                section) - http://www.ninjatrader.com/support/h...nstruments.htm
                CalculateOnBarClose - http://www.ninjatrader.com/support/h...onbarclose.htm

                You mention that you do not want orders to be made within 90 minutes of each other. May I confirm that this is only for entry orders and exit orders are allowed within 90 minutes of each other?

                Regarding just the entries happening within 90 bars of each other, I was not able to reproduce this on my end using your code. All entries I have on my chart are not within 90 minutes of each other. Have you updated the code and not removed/re-added this to the chart?

                What date is your chart showing? What time zone are you in?

                This is so I can try and match up my chart.
                To answer the first question, it is not an issue of it exiting on the next bar, it is an issue of it exiting on the wrong SMA. If price < SMA(400) within 25 minutes of entry, then exit. All trades are waiting to exit until price < SMA(100), which is another exit indicator. But it needs to work on both.

                On the clarification, yes you are correct. Exits can be allowed within seconds, but entry's of new long positions should not happen within 90 minutes of the last exit. The screen shots are of days between 12/9/2013 and 12/20/2013. I am United States eastern time zone. When I run my code there are trades that execute with 90 minutes of the last exit.

                Comment


                  #9
                  koganam,

                  I am very new to ninja trader, so I don't know exactly know how to get the variables to print. I tried putting the print() command at the end of my code but it didn't open a output window when I ran it.

                  Comment


                    #10
                    Hello Volhog,

                    Attached is an export of the code I am testing.

                    Is this code not working correctly for you as well? Currently, I am not able to reproduce this behavior.

                    May I have an export of your code to test?

                    To export your script do the following:
                    1. Click File -> Utilities -> Export NinjaScript
                    2. Enter a unique name for the file in the value for 'File name:'
                    3. Select the strategy from the objects list on the left -> click the right facing arrow ">" to add the strategy to the export
                    4. Click the 'Export' button -> click 'yes' to add any referenced indicators to the export -> click OK to clear the export location message


                    By default your exported file will be in the following location:
                    • (My) Documents/NinjaTrader 7/bin/Custom/ExportNinjaScript/<export_file_name.zip>


                    Below is a link to the help guide on Exporting NinjaScripts.
                    http://www.ninjatrader.com/support/h...nt7/export.htm
                    Attached Files
                    Chelsea B.NinjaTrader Customer Service

                    Comment


                      #11
                      Hello Volhog,

                      To print use the Print() command.
                      For example:
                      Code:
                      Print(Close[0] + " - " + SMA(400)[0] + " - " + BarsSinceEntry());
                      Prints will go to the output window which you will need to open yourself.
                      • Click Tools -> Output Window...
                      Chelsea B.NinjaTrader Customer Service

                      Comment


                        #12
                        Originally posted by volhog View Post
                        koganam,

                        I am very new to ninja trader, so I don't know exactly know how to get the variables to print. I tried putting the print() command at the end of my code but it didn't open a output window when I ran it.
                        Code:
                        // Condition set 3
                        Print(null);
                        Print("CurrentBar: " + CurrentBar);
                                     if (Close[0] < SMA(400)[0] && BarsSinceEntry() < 25)
                                     {
                        Print("Entered SMA(400) exit block");
                                         ExitLong("", "");
                        Print("Exit SMA(400) exit block");
                                     }
                        You can modify your code that way. I assume you understand what you would then expect to see in the Output Window.

                        The Output Window is a separate window in NT, that you must open yourself: the Strategy is not going to open one for you. Look under the "Tools" menu.

                        Comment


                          #13
                          Chelsea,

                          My code is attached. Sorry for the delay. The holiday season got me in a rush!
                          Attached Files

                          Comment


                            #14
                            Chelsea,

                            You are a genius...I plugged in your code and it did everything that mine wasn't doing! It must have been a few of the minor differences in the beginning. Now on the first purchase of AAPL that occurred on 12/20 I have a question. The strategy didn't purchase it right when it crossed SMA(400) at 9:40ish (because it was counting 90 bars since the last sell including the bars from the prior days trading session. A sell occurred on 12/19 around 3pm). Is there a way to reset bar count every new trading session? Thanks!

                            Rob

                            Comment


                              #15
                              Hi Rob,

                              If you are using CurrentBar as the bar counter it will not be possible to reset this.

                              Instead, you can have your own variable that you use to count bars. Then you can reset this upon every new session.

                              For example:
                              Code:
                              private int barCount = 1;
                              protected override void OnBarUpdate()
                              {
                              if (Bars.FirstBarOfSession == true)
                              {
                              barCount = 1;
                              }
                              else
                              {
                              barCount++;
                              }
                              }
                              This code will reset the barCount variable to 1 on the first bar of a session. Then it will increment until a new session is reached.
                              Chelsea B.NinjaTrader Customer Service

                              Comment

                              Latest Posts

                              Collapse

                              Topics Statistics Last Post
                              Started by kujista, Today, 06:23 AM
                              4 responses
                              13 views
                              0 likes
                              Last Post NinjaTrader_ChelseaB  
                              Started by traderqz, Yesterday, 09:06 AM
                              2 responses
                              15 views
                              0 likes
                              Last Post traderqz  
                              Started by traderqz, Today, 12:06 AM
                              3 responses
                              6 views
                              0 likes
                              Last Post NinjaTrader_Gaby  
                              Started by RideMe, 04-07-2024, 04:54 PM
                              5 responses
                              28 views
                              0 likes
                              Last Post NinjaTrader_BrandonH  
                              Started by f.saeidi, Today, 08:13 AM
                              1 response
                              8 views
                              0 likes
                              Last Post NinjaTrader_ChelseaB  
                              Working...
                              X