Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

Trying to get look back of bars and an exit strategy worked out.

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

    Trying to get look back of bars and an exit strategy worked out.

    Looking at this in terms of a SHORT for this question.

    I'm working on a strategy that I'm trying to get setup. So basically what I have is when price crosses a certain threshold (whether it be an EMA, etc) I want it to look back at the last X amount of bars and if where the current price is IS NOT less than the lowest price of the last X amount of bars don't trigger.

    Current I'm using something such as this as I found it in the the docs but it seems like its not quite right all the time.

    if(Close[0] < Low[LRO(() => Close[0] > Open[0], 1, X)]) { Enter Short here}

    I'm honestly not quite understanding the `Close[0] > Open[0]` part of it but truly not quite sure if its actually looking back at the last X amount of bars because in the strategy analyzer the first time it hits its seems to work but I think its because of the time I'm actually using for a small sample test but when I see it run again it definitely is not working because it shouldn't have entered into a short if the price was not lower than the last X amount of bars I'm using.

    Then I'm also looking at my exit strategy where once its in a short I want it to look at the current price (bar) and if at X amount of bars back (not looking at all the bars behind it but at a specific bar behind the current bar if the price is higher than that bars HIGH I want it to exit.

    For that I was using something like:

    if(Close[0] > High[X]) { Exit short here }

    For some reason this isn't working correctly either b/c its exiting sooner than the X value of the High parameter for that bar at that index.





    #2
    Hello vegas3416,

    Thanks for your post.

    LRO is the "Least Recent Occurrence" and it will start at the beginning of the lookback period and walk forward looking for the condition you have specified and it will return the Bars ago that this occurred. your condition Close[0] < Low[LRO(() => Close[0] > Open[0], 1, X)] is quite dangerous because if the condition to test for (Close[0] > Open[0]) is not found, it will return a -1 value and in this set up you are directly entering the bars ago for the Low[] to find and a -1 would cause an error because that would try to pull a future bar. Chances are pretty good that it will find a Close > Open but just to clarify there is some functionality risk in what has been constructed. It would be better to run the LRO and have its results go to an int variable that you can test if it is -1 or > 0 and then put that int variable into your Close[0] < Low[in variable here].
    Reference: https://ninjatrader.com/support/help...urence_lro.htm

    You may want to look at using the MIN() method: https://ninjatrader.com/support/help...inimum_min.htm
    Example:

    if (Close[0] < MIN(Low, X)[1]) // Is the close less than the lowest low of the last x bars, note that I used [1] to start the lookback at the previous bar, not the current bar.

    Here is a link for the complimentary method MAX(): https://ninjatrader.com/support/help...aximum_max.htm

    Paul H.NinjaTrader Customer Service

    Comment


      #3
      OK so I think I have this working but one question I have. I have multiple setups for vary for what kind of entry it is. So for instance lets say my short entry is this:

      EnterShort(Convert.ToInt32(DefaultQuantity), "@PinkShort");


      Then I have a check that Exits the short if a certain signal is hit but I also want to exit this particular short if the Profit target for it is hit. I have set something as such:

      SetProfitTarget(@"PinkShort", CalculationMode.Ticks, 60);


      in the State == State.DataLoaded section and again also have something as such:

      if(ninZaStepMAPro1.Signal_State[0] == 2)
      {
      ExitShort(Convert.ToInt32(DefaultQuantity), "", "@PinkShort");
      }


      The issue is it only will trigger if the ninZaStepMAPro1 signal is triggered and will not trigger if the profit target is reached. Can you aid in what I'm missing here?

      Comment


        #4
        Hello vegas3416 ,

        Thanks for your reply.

        State.DataLoaded is only called once after all bars are loaded so it would not be an appropriate place for your exit condition.
        Reference: https://ninjatrader.com/support/help...tatechange.htm

        "The issue is it only will trigger if the ninZaStepMAPro1 signal is triggered and will not trigger if the profit target is reached" I am not sure on what "it" is that will only trigger if. If by "it" you mean the exitshort order then correct it will not trigger if the profit target is hit because the entry order is now closed.
        Paul H.NinjaTrader Customer Service

        Comment


          #5
          I figured out what it was. It was a type on my part. I was using my entry signal to be @"PinkShort" but in the profit target putting "@PinkShort" Not sure if you can see the issue but the @ symbol was outside of the quotes. Not sure if this was a copy and paste error from strategy builder or fat fingers. Wow, I hate small typos like this.

          Comment


            #6
            Ok, another question. Tried this MIN function but its not working as I'm seeing.

            I'm doing somethign as such:

            if((Close[0] < EMA(100)[0]) && (Low[2] > Low[1]) && (Close[0] < MIN(Low, 16)[1]))
            {

            }


            Issue I'm seeing here is that its still entering even though I've checked that the `Close[0]` is not lower than the lowest low of one of the last 16 bars.

            Maybe you can explain what I could be missing here.

            Comment


              #7
              Hello vegas3416,

              Thanks for your reply.

              I would add a print statement to print out all of the values you are evaluating to best understand what the logic code is actually working with.

              For example, before your entry condition:

              Print (Time[0] + "Close: "+Close[0].ToString()+" EMA100: "+EMA(100)[0].ToString()+" Low2: "+Low[2].ToString()+" Low1: "+Low[1].ToString()+"Min: "+ MIN(Low, 16)[1].ToString());

              Open the New>Ninjascript output window to see these results when you apply your script. the Time[0] will show you the values at the time of the bar close.

              Here is a link to further debugging tips: https://ninjatrader.com/support/help...script_cod.htm

              Paul H.NinjaTrader Customer Service

              Comment


                #8
                Ok, I figured out the issue but it brought up another issue that I'm not quite sure how to deal with. I feel its an easy one but lets see.

                So I have a trigger that exits a strategy if a certain indicator is crossed OR if a SetProfitTarget has been reached on that particular entry signal.

                When I do this or when I enter that trade I set a boolean value to 'True' - its basically a value that tells the code that we are in a trade and to skip calculating the other setups so it doesn't color the bars of those potential setups b/c we are in a trade and don't want it to mess up or have the system thinking those other scenarios should trigger or set certain parameters.

                The issue with this is if the indicator doesn't trigger but instead the `SetProfitTarget` is triggered I'm not quite sure where I would call the parameter to set the `inTrade` variable back to false.

                I thought maybe there was something in the docs to do this like if MarketPosition.Flat or something but that doesn't do it. Is there a place where this could be called to do this?

                Possibly in the Update() method? Just want to see if I can't get preferred places on where this should be called for best performance and for best practice.

                Comment


                  #9
                  Hello vegas3416,

                  Thanks for your reply.

                  Checking that the market position is flat would be the way to reset your bool variable.

                  Another alternative would be to check that the profit target filled in the OnExecutionUpdate() method.
                  Paul H.NinjaTrader Customer Service

                  Comment


                    #10
                    I think I got it with that but another question on this:

                    Say I have a bar and I got its entry price but its kind of a sketchy location for an entry on the algo I'm working on so what I want to do is check the close of the next bar and make sure that close is less that the price of the prior bar. If the close of the bar after the entry price bar is lower then keep going with the algo but if the close of the price of the bar after the entry bar is not lower I want it to exit the trade.

                    Can you provide a format that would work for that. Looking through the docs and not quite seeing something that would work for this scenario.

                    Comment


                      #11
                      Also is there a way to call something so that after a specific type of trade it doesn't enter a trade even if it meets the expectations until after 4 bars have completed?


                      So trade enters short -> trade closes -> tag saved -> waits 4 bars while tag is a specific type. After 4 bars tag is cleared and strategy goes back to reevaluating the setups to determine if it should re-enter again.
                      Last edited by vegas3416; 02-24-2021, 04:40 PM.

                      Comment


                        #12
                        Think I found it. Sorry - if anything hopefully this helps others.

                        For the Bars Since Exit: https://ninjatrader.com/support/help...texecution.htm

                        // Only enter if at least 10 bars has passed since our last exit or if we have never traded yet
                        if ((BarsSinceExitExecution() > 10 || BarsSinceE xitExecution() == -1) && CrossAbove(SMA(10), SMA(20), 1))
                        EnterLong();
                        Last edited by NinjaTrader_PaulH; 02-25-2021, 07:43 AM. Reason: Corrected the help guide link to the intended BarsSinceExitExecution()

                        Comment


                          #13
                          Trying to get this to work correctly but not able to get that BarsSinceExitExecution to work properly.

                          Essentially this is what I have:

                          if(BarsInProgress == 0)
                          {

                          //Check for ExitShort
                          if((waitFourBars) && (Position.MarketPosition == MarketPosition.Short) && ((Close[0] > High[1]) || ninZaTStop1.Signal_Trend[0] == 1))
                          {
                          Print("I should be closing");
                          ExitShort("Twenty");
                          waitFourBars = false;
                          }



                          if statement for a specific scenario1

                          else if statement for a specific scenario2

                          else if statement for a specific scenario3
                          {
                          EnterShort("scenario3");
                          waitFourBars = true;

                          }


                          }


                          Trying to figure out where I would put that BarsSinceExitExecution. Should I wrap the BarsInProgress with with I'm just not really sure where to add it.

                          Goal is when I enter a short on a specific scenario it triggers the short and sets a boolean.

                          Then with that boolean its looking to see if a specific scenario is met and if its not keep skipping over until it is. Once it is Exit the Short and then I want it to wait 4 bars before it start processing bars again to determine if it should start entering trades again.

                          I've played around with it a few different ways but I'm just not quite understanding where I need to put that.

                          Also because I keep getting this error:

                          Strategy 'ShortTrendInitial': Error on calling 'OnBarUpdate' method on bar 1: Strategy 'ShortTrendInitial/-1': You must use the overload that has a 'BarsInProgress' parameter when calling the BarsSinceExitExecution() method in the context of a multi-time frame and instrument strategy.

                          I'm not quite sure what that means in terms of this.

                          Comment


                            #14
                            Hello vegas3416,

                            Thanks for your reply.

                            There are two ways to implement BarsSinceExitExecution(). If you are using a single data series (the Chart bars only) then you can use BarsSinceExitExecution() == 4.

                            If your strategy has added data series then you must use it with the other method signature of: BarsSinceExitExecution(0,"",0) == 4. NOTE: Make sure you review the help guide to understand what the parameters 0, "", 0 are and set them according to your needs: https://ninjatrader.com/support/help...texecution.htm

                            Paul H.NinjaTrader Customer Service

                            Comment


                              #15
                              I wish this were the case but this does not work. When I try to do what you put above I get this error:

                              "Strategy 'ShortTrendInitial': Error on calling 'OnBarUpdate' method on bar 50: Strategy 'ShortTrendInitial/-1': You must use the overload that has a 'BarsInProgress' parameter when calling the BarsSinceExitExecution() method in the context of a multi-time frame and instrument strategy"

                              Then if I try to put it in between a

                              if(BarsInProgress == 0) {

                              if( waitFourBars && BarsSinceExitExecution() == 4)
                              {
                              Print("Is more than four bars: " );
                              }

                              }

                              I get the same error. If I try putting BarsSinceExitExecution(0,"Twenty", 4) > 4 or just doing it without the " > 4 " to see its value in a print statement I get " -1 "

                              Comment

                              Latest Posts

                              Collapse

                              Topics Statistics Last Post
                              Started by PWillard, Today, 12:56 AM
                              0 responses
                              1 view
                              0 likes
                              Last Post PWillard  
                              Started by WidenThur, Today, 12:48 AM
                              0 responses
                              1 view
                              0 likes
                              Last Post WidenThur  
                              Started by devidbelly, Today, 12:39 AM
                              0 responses
                              2 views
                              0 likes
                              Last Post devidbelly  
                              Started by anderson, Yesterday, 11:06 PM
                              0 responses
                              1 view
                              0 likes
                              Last Post anderson  
                              Started by eseorafva, Yesterday, 10:43 PM
                              0 responses
                              0 views
                              0 likes
                              Last Post eseorafva  
                              Working...
                              X