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

Using a time filter

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

    Using a time filter

    Apologies if I have posted this in the wrong area but I'm new to all this and finding my way around.

    On this post http://ninjatrader.com/support/forum...ead.php?t=3226 I found an explanation (and sample code) describing how to incorporate a time filter into the trading strategy.

    If I wanted to restrict trading between say 8am and 11pm, would the line of code below do the trick? (I have assumed a 24 hour clock is used but I could be wrong).

    (ToTime(Time[0]) >= 80000 && ToTime(Time[0] <= 230000)

    What time zone does the code actually check against? Does it automatically default to the local time of the machine?

    Any help/advice much appreciated.

    #2
    Hello newuser,

    Thank you for your post.

    You are correct, ToTime would use a 24 hour clock. This clock would use your time zone from your local PC clock time.

    Comment


      #3
      Hi NinjaTrader_PatrickH,

      Thank you for the prompt reply.

      If the time filter code is correct then I must have a problem somewhere else because when I ran a backtest on the AUDUSD forex pair I got trades that were outside the specified time limits. I can think of two possible issues at this point:

      The first is that the backtest properties asks for an order 'time in force' and only offers two options - GTC and Day. I tried running the test twice using either option but I couldn't understand how either good till cancelled or day would be an appropriate choice?

      The second issue might be the entry order code. I have used

      EnterLongLimit(DefaultQuantity, High[0] + 2 * TickSize, "");

      and set the tick size for the AUDUSD pair to 0.0001 as I would like orders triggered two pips above the high.

      Do you think either of these could be the issue or is it something else?

      Apologies again if I'm asking silly questions but I'm a little baffled as to where I'm going wrong.

      Comment


        #4
        Hello newuser,

        Thank you for your patience.

        The TimeInForce is likely not the cause. Using Day would mean the orders would only be active during the Session selected for the Session Template. Usign GTC would mean the orders are active until cancelled.

        So likely it is that the orders are still active outside the times you wish and thus can fill outside those hours. You would likely wish to look into CancelOrder() and IOrder objects to cancel orders when the end time of your filter is hit.

        Please let me know if you have any questions.

        Comment


          #5
          Hi PatrickH,

          I had a look at the log file and I found the following error message

          ERROR: Failed to call method 'Initialize' for strategy: 'TickSize' property can't be accessed from within 'Initialize' method in OnUnhandledThreadException

          which I attribute to the code I used to set the stop and profit target in the Initialize() section. I am assuming this is if not the cause of the problem then at least something I need to fix? If so, where should I be putting the code for the stop and take profit? Below the EnterLongLimit line?

          Comment


            #6
            Hello newuser,

            You would be unable to access the TickSize property from Initialize(), as per the help guide: https://ninjatrader.com/support/help.../?ticksize.htm

            If you wish for your stop loss and profit target to be based on ticks, you can call SetStopLoss() and SetProfitTarget() with CalculationMode set to CalculationMode.Ticks.

            https://ninjatrader.com/support/help...ofittarget.htm
            https://ninjatrader.com/support/help...etstoploss.htm
            Zachary G.NinjaTrader Customer Service

            Comment


              #7
              Hi ZacharyG,

              Thanks for the quick reply and the explanatory link.

              I probably should've explained in my previous post that I want to set the stop based on the current bar. Basically for a long order I want to set the stop a few ticks below the low.

              Is there a way to do that using CalculationMode.Ticks or would I better off using this line of code below in the OnBarUpdate()

              SetStopLoss(CalculationMode.Price, Low[0] - 2 * TickSize);

              Incidentally further to my original post about trades triggering outside of the time filter I deleted the code I had for entry, stop and take profit and simply used DrawDot when all conditions were met and everything worked just fine (so at least know I where the problem is now).

              Comment


                #8
                Hello newuser,

                Thank you for the clarification.

                In the case that you have mentioned, it would be better to use CalculationMode.Price as you have outlined in your post.

                Please, let us know if we may be of further assistance.
                Zachary G.NinjaTrader Customer Service

                Comment


                  #9
                  Unfortunately I'm still having issues with trying to get the entry, stop and profit target to work properly. As per my previous post I am trying to calculate the stop based on the current bar, so I tried using the following code in the OnBarUpdate()

                  }
                  SetStopLoss(CalculationMode.Price, (Low[0]) - (2 * TickSize));
                  EnterLongLimit(DefaultQuantity, High[0] + 2 * TickSize, "");
                  {

                  It compiles and it runs in the backtest but when I look at the results it's not performing as expected. I have the 8am to 11pm time filter for example and if I remove all the order management code and replace it with DrawDot I get exactly what I'm after, but the order stuff seems to be causing issues.

                  I also tried creating a stop based on the current bar using the wizard but it didn't seem to work either. In that instance what I did was create a user variable which was equal to the Low[0] with a 2 tick offset, and then create a stop loss with CalculationMode of Ticks and set the value as the user variable.

                  Any help would be much appreciated.

                  Comment


                    #10
                    Hello newuser,

                    Are you ensuring that the stop loss is not being modified to being the current low - 2 ticks on every call of OnBarUpdate()?

                    For example:
                    Code:
                    if (Position.MarketPosition == MarketPosition.Flat)
                    {
                    	SetStopLoss(CalculationMode.Price, Low[0] - 2 * TickSize);
                    	EnterLong();
                    }
                    In my example above, the stop loss is going to be set to the price of Low[0] - 2 * TickSize only when my strategy is still in a flat position. As soon as the strategy enters, the stop loss price is not going to be modified on the next call of OnBarUpdate() and will maintain its initial position.
                    Zachary G.NinjaTrader Customer Service

                    Comment


                      #11
                      Hi ZacharyG,

                      Ah that's filled in a piece of the puzzle. To answer your question no, I have not prevented the strategy from updating the stop loss on every call of OnBarUpdate() so that's definitely an issue.

                      In the example code you provide: what would happen if I had more than one trade open at a time? As in how would the code handle the stops on two simultaneous trades?

                      Let's say I had one trade open and second one triggers. Presumably I would need to add another few lines of code to account for where Position.MarketPosition == MarketPosition.Long?

                      Comment


                        #12
                        Hello newuser,

                        Without specifying a signal name in the SetStopLoss(), it's going to apply to all entries.

                        You'll notice that SetStopLoss() has an overload that takes in a string parameter, fromEntrySignal:

                        Code:
                        SetStopLoss(string fromEntrySignal, CalculationMode mode, double value, bool simulated)
                        You'll want to ensure that you're passing the signal name of the specific entry to the SetStopLoss() method call. You are able to have multiple SetStopLoss() calls in your strategy with different fromEntrySignal parameters.

                        I would suggest the use of booleans to prevent the strategy from calling your stop losses multiple times. For example, once the stop loss is set for your first entry, set a boolean to true/false to prevent the stop loss from being modified the next iteration of OnBarUpdate().

                        Example:
                        Code:
                        if (stopLossOneSet == false)
                        {
                             SetStopLoss(....);
                             stopLossOneSet = true;
                        }
                        On the next call of OnBarUpdate(), SetStopLoss() won't be called as the boolean is true.
                        Zachary G.NinjaTrader Customer Service

                        Comment


                          #13
                          Hi Zachary_G,

                          So given that I'm using the following code:

                          EnterLongLimit(DefaultQuantity, High[0] + 2 * TickSize, "");

                          for entry am I correct in thinking I need to insert a string in the "" at the end of the code above so I can then call that signal name for the stop loss?

                          I also have another question around your statement You are able to have multiple SetStopLoss() calls in your strategy with different fromEntrySignal parameters.

                          I am using a strategy that rides trends, and what that means is when I get a signal I will often get several consecutive signals (which may or may not trigger depending on if new highs are set in a bullish run). So it is entirely possible that I will have 2 trades open at once, based on the same condition set or in the very least I will have 1 trade open and want to set a stop for another order. How would I go about handling that, noting that (for bullish setups) I will always want to calculate the stop loss at Low[0] - 2 * TickSize?

                          The added complication is that I will want to add a breakeven strategy, but if it's simpler to sort out the multiple stop handling first based on the scenario I have described above then that's fine. For the record what I would like to do is set the stop to breakeven if after the first candle closes the current price is > entry price (to clarify when I say the first candle I do mean the very candle that the order is triggered on).

                          Many, many thanks once again for all the help and advice.

                          Comment


                            #14
                            Hello newuser,

                            You will want to specify a signal name for your entry and not pass an empty string.

                            For your additional entry, I would suggest the use of a different signal name than the first order. As long as your stop loss for that second order is not prevented from being modified on the next call of OnBarUpdate(), the stop loss will continue to be modified to your desired price.

                            I would highly suggest taking a look at this reference sample on our support forum detailing how to modify stop loss and profit target orders. The example provides a sample of how to modify the stop loss to break even as well: http://ninjatrader.com/support/forum...ead.php?t=3222
                            Zachary G.NinjaTrader Customer Service

                            Comment


                              #15
                              I was thinking about what you said re specifying a signal name for my entry and then using a different signal name for any additional entry/ies. The solution I envisage is some sort of iterative count function as it is possible that I might even find myself with more than 2 trades open at once. Given that I have no way to predict how many open trades I might have open simultaneously I figure this is the best way?

                              I've been doing some searching around the forum and the help guide and stumbled across Performance.LongTrades.Count Presumably I could use this count as a way of differentiating trades when setting the stop loss at the order stage?

                              Comment

                              Latest Posts

                              Collapse

                              Topics Statistics Last Post
                              Started by jhjhawkins, Today, 12:25 PM
                              0 responses
                              2 views
                              0 likes
                              Last Post jhjhawkins  
                              Started by rexsole, Today, 11:48 AM
                              1 response
                              13 views
                              0 likes
                              Last Post NinjaTrader_PatrickG  
                              Started by jeronymite, Yesterday, 05:05 PM
                              3 responses
                              54 views
                              0 likes
                              Last Post NinjaTrader_ChristopherJ  
                              Started by Don22Trader1, Yesterday, 05:54 PM
                              3 responses
                              47 views
                              0 likes
                              Last Post NinjaTrader_Jesse  
                              Started by Jebulay, Today, 08:36 AM
                              1 response
                              42 views
                              0 likes
                              Last Post NinjaTrader_PatrickG  
                              Working...
                              X