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

recent bar bigger then last x amount of bars and exit on crossing SMA

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

    recent bar bigger then last x amount of bars and exit on crossing SMA

    hello,

    I am currently in the process of gaining experience with the wizard and the script.
    Unfortunately, I'm not getting any further with a few points concerning the wizard.

    I would like to build the following strategy.

    there are 3 time frames i would like to use:
    15 min with SMA 24
    5 min with SMA 24 and SMA 8
    2 min with SMA 6

    my rules should be the following:
    enter long when the most recent candle is closed above all sma.
    enter short when the most recent candle closes below all sma.
    additionally i would like to exit when the latest candle crosses the 2 min sma 6.
    enter long or exit should only go from 2 min.


    further rules:
    i would like to calculate the size of open to close of the last 30 bars. i only want to go long or short if the most recent bar is 2x bigger than 20-3 bars and 4x bigger than the last 2 bars.
    in addition, the close of the most recent bar should be 90% or more of the high (wick)

    i have used last recent bars but that doesn't seem to work. not with the last 30 and not for every single bar. also an offset of 150% etc doesn't work the way i want it to.

    how can i build this strategy and is it even possible to this extent?


    public class strategie : Strategy
    {

    private SMA SMA1;
    private SMA SMA2;
    private SMA SMA3;
    private SMA SMA4;

    protected override void OnStateChange()
    {
    if (State == State.SetDefaults)
    {
    Description = @"Geben Sie hier die Beschreibung für die neue benutzerdefinierte Strategie.";
    Name = "strategie";
    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.Gtc;
    TraceOrders = true;
    RealtimeErrorHandling = RealtimeErrorHandling.StopCancelClose;
    StopTargetHandling = StopTargetHandling.PerEntryExecution;
    BarsRequiredToTrade = 20;
    // Disable this property for performance gains in Strategy Analyzer optimizations
    // See the Help Guide for additional information
    IsInstantiatedOnEachOptimizationIteration = true;
    Purple = 24;
    Blue = 8;
    Dotted = 6;
    Green = 24;
    }
    else if (State == State.Configure)
    {
    AddDataSeries(Data.BarsPeriodType.Minute, 2);
    AddDataSeries(Data.BarsPeriodType.Minute, 5);
    AddDataSeries(Data.BarsPeriodType.Minute, 15);
    }
    else if (State == State.DataLoaded)
    {
    SMA1 = SMA(Closes[3], Convert.ToInt32(Green));
    SMA2 = SMA(Closes[2], Convert.ToInt32(Purple));
    SMA3 = SMA(Closes[2], Convert.ToInt32(Blue));
    SMA4 = SMA(Closes[1], Convert.ToInt32(Dotted));
    }
    }

    protected override void OnBarUpdate()
    {
    if (BarsInProgress != 0)
    return;

    if (CurrentBars[0] < 30
    || CurrentBars[1] < 1
    || CurrentBars[2] < 0
    || CurrentBars[3] < 0)
    return;

    // set 1
    if ((Closes[1][0] > SMA1[0])
    && (Closes[1][0] > SMA2[0])
    && (Closes[1][0] > SMA3[0]))
    {
    }

    // set 2
    if ((Closes[1][0] < SMA1[0])
    && (Closes[1][0] < SMA2[0])
    && (Closes[1][0] < SMA3[0])
    && (Close[0] > (Close[30] * 1.5) ))
    {
    }

    // set 3
    if ((CrossAbove(Close, SMA4, 1))
    || (CrossBelow(Close, SMA4, 1)))
    {
    ExitLong(Convert.ToInt32(DefaultQuantity), "", "");
    ExitShort(Convert.ToInt32(DefaultQuantity), "", "");
    }

    }​

    #2
    Hello Paste1903,

    Thank you for your post.

    Please see the attached for your first two conditions.

    additionally i would like to exit when the latest candle crosses the 2 min sma 6.
    Can you specify if this is for a cross above or cross below?

    Unfortunately, some of your conditions would not be possible in the Strategy Builder.

    enter long or exit should only go from 2 min.
    You cannot specify BarsInProgress indexes for order entry methods in the Strategy Builder.

    Your conditions for "further rules" also would not be possible to create in the Strategy Builder, as calculating this comparison between bar sizes would require more complicated math than the Offset function in the Builder is capable of doing. You would need to unlock your script in order to specify a BarsInProgress index and also to do the calculations for your "further rules".

    Please let me know if you have any further questions.
    Attached Files
    Gaby V.NinjaTrader Customer Service

    Comment


      #3
      hi gaby,

      thank you for your help.

      Can you specify if this is for a cross above or cross below?
      if i go long, i want to adjust my stop to the SMA 6 and carry it with the SMA. as soon as a bar crosses this SMA, my stop should take effect. the same for going short.

      You would need to unlock your script in order to specify a BarsInProgress index and also to do the calculations for your "further rules".
      ok thats fine for me. what would the calculations look like?


      thanks a lot.

      best,

      Comment


        #4
        Thank you for your response.

        Take a look at this sample script which demonstrates modifying the price of stop and target orders:



        i would like to calculate the size of open to close of the last 30 bars. i only want to go long or short if the most recent bar is 2x bigger than 20-3 bars and 4x bigger than the last 2 bars.
        How would like to calculate the size of the last 30 bars to compare to the most recent bar? Are you looking to take the average size of the last 30 bars and the last 2 bars, and compare that to the most recent bar?

        I look forward to assisting further.
        Gaby V.NinjaTrader Customer Service

        Comment


          #5
          Take a look at this sample script​
          i had already looked at this. unfortunately, it only explains the basics. can i calculate exits using only percentages, ticks, etc.? i couldn't find anything there about the possibility of triggering an exit when an SMA is crossed.


          How would like to calculate the size of the last 30 bars to compare to the most recent bar? Are you looking to take the average size of the last 30 bars and the last 2 bars, and compare that to the most recent bar?
          no not the average size. rather the size of open to close. i want to compare this unit/size with the current bar size from open to close. so i only want to go long with the current bar if it is 2x or 4x larger than the previous bars without a larger bar in between. if i were to take the average, there could also be bars or volatility that are too large for me.

          i hope i was able to explain what i mean reasonably well. if not, please let me know

          Comment


            #6
            Hello Paste,

            SetStopLoss() allows you to specify the Calculation mode to be percentage or ticks.



            You can also trigger an exit based on a CrossAbove or CrossBelow.







            I would like to provide you with a sample script, but just to be clear, this is what you are looking for:
            • Compare the size of the last 30 bars with the current bar. If the size of the current bar is between 2-4x larger than these bars, you would like to go long.
            If not, please describe with detail what the logic would be.

            ​I look forward to assisting further.
            Gaby V.NinjaTrader Customer Service

            Comment


              #7
              hi gaby,

              You can also trigger an exit based on a CrossAbove or CrossBelow.
              perfect thank you very much. i'll take a look.


              please describe with detail what the logic would be.
              I'll try to describe it as best I can. one important property of your sentence only needs to be changed. it is important that it must be at least 2x (for previous 30 bars) and 4x (for previous 2 bars). not in between.


              if the size of the current bar (open to close) is 2x larger than the previous 30 bars (open to close) and 4x larger than the previous 2 bars (open to close), then go long.
              same with going short.

              and can you send me an example for "only go long when current bar OPEN to CLOSE is at least 90% or greater compared to OPEN to HIGH?

              thank you for your help.

              best,
              Last edited by Paste1903; 03-08-2024, 02:43 AM.

              Comment


                #8
                Hello Paste1903,

                Do you want to compare the previous 2 bars (check if those are 4x bigger), then the next 30 bars after that (check if those are 2x) bigger? Or is the previous 2 bars included within those last 30 bars, so in essence you are checking if the 28 bars after that are 2x bigger?


                can you send me an example for "only go long when current bar OPEN to CLOSE is at least 90% or greater compared to OPEN to HIGH?
                For this you could do something like,

                Code:
                            double OpenClose = Math.Abs(Open[0] - Close[0]);
                            double OpenHigh = Math.Abs(Open[0] - High[0]);
                            
                            if (OpenClose >= (OpenHigh + (OpenHigh * 0.9)))
                            {
                                EnterLong();
                            }
                ​
                Gaby V.NinjaTrader Customer Service

                Comment


                  #9
                  hello gaby,

                  Do you want to compare the previous 2 bars (check if those are 4x bigger), then the next 30 bars after that (check if those are 2x) bigger?
                  yes, exactly as you explained in the first sentence. the 2 bars before my entry bar should be the 4x. all others before these 2 (i.e. then 3rd bar to 30th bar) should be the 2x


                  For this you could do something like
                  perfect thank you i will test that.

                  best,

                  Comment


                    #10
                    Hello,

                    See the attached sample script.

                    Please let me know if this doesn't guide you in the right direction.

                    Attached Files
                    Gaby V.NinjaTrader Customer Service

                    Comment


                      #11
                      perfect thank you for your help and sorry if i couldn't express myself very well. i'll have a look over at the weekend and if i have any more questions, i'll get back to you here.

                      have a nice weekend.

                      Comment


                        #12
                        hey gaby,

                        i have been working with the code over the weekend. it doesn't seem to work quite right. please find attached a screenshot. the entry bar is larger than the previous 2 bars from open to close, but clearly too small for the 30 others. should i send you my code again? or is there an error somewhere in the example calculation?

                        best,
                        Last edited by Paste1903; 03-11-2024, 04:11 AM.

                        Comment


                          #13

                          Comment


                            #14
                            Hello Paste1903,

                            Thank you for your response.

                            To understand why the script is behaving as it is, such as placing orders or not placing orders or drawing objects when expected, it is necessary to add prints to the script that print the values used for the logic of the script to understand how the script is evaluating.

                            In the strategy add prints (outside of any conditions) that print the date time of the bar and all values compared in every condition that places an order. You could print out the index of the bar, the size of the bar being compared, and the size of the current bar as well.

                            The prints should include the time of the bar and should print all values from all variables and all hard coded values in all conditions that must evaluate as true for this action to be triggered. It is very important to include a text label for each value and for each comparison operator in the print to understand what is being compared in the condition sets.

                            Prints will appear in the NinjaScript Output window (New > NinjaScript Output window).

                            Further, enable TraceOrders which will let us know if any orders are being ignored and not being submitted when the condition to place the orders is evaluating as true.

                            I am happy to assist you with analyzing the output from the output window.

                            Run or backtest the script and when the output from the output window appears save this by right-clicking the output window and selecting Save As... -> give the output file a name and save -> then attach the output text file to your reply.

                            Below is a link to a forum post that demonstrates using informative prints to understand behavior and includes a link to a video recorded using the Strategy Builder to add prints.


                            Please let me know if I may further assist with analyzing the output or if you need any assistance creating a print or enabling TraceOrders.​
                            Gaby V.NinjaTrader Customer Service

                            Comment


                              #15
                              ive checked the code again and cant find any problems there. maybe ive done something wrong here?
                              the following code is placed after your example:

                              if (BarsInProgress != 0)
                              return;

                              if (CurrentBars[0] < 1
                              || CurrentBars[2] < 0
                              || CurrentBars[3] < 0)
                              return;

                              // set 1
                              if ((Close[0] > SMA1[0])
                              && (Close[0] > SMA2[0])
                              && (Close[0] > SMA3[0])
                              && (isLarger == true))
                              {
                              EnterLong(Convert.ToInt32(DefaultQuantity), "");
                              }

                              // set 2
                              if ((Close[0] < SMA1[0])
                              && (Close[0] < SMA3[0])
                              && (Close[0] < SMA2[0])
                              && (isLarger == true))
                              {
                              EnterShort(Convert.ToInt32(DefaultQuantity), "");
                              }​

                              Comment

                              Latest Posts

                              Collapse

                              Topics Statistics Last Post
                              Started by DJ888, Today, 10:57 PM
                              0 responses
                              6 views
                              0 likes
                              Last Post DJ888
                              by DJ888
                               
                              Started by MacDad, 02-25-2024, 11:48 PM
                              7 responses
                              158 views
                              0 likes
                              Last Post loganjarosz123  
                              Started by Belfortbucks, Today, 09:29 PM
                              0 responses
                              7 views
                              0 likes
                              Last Post Belfortbucks  
                              Started by zstheorist, Today, 07:52 PM
                              0 responses
                              7 views
                              0 likes
                              Last Post zstheorist  
                              Started by pmachiraju, 11-01-2023, 04:46 AM
                              8 responses
                              151 views
                              0 likes
                              Last Post rehmans
                              by rehmans
                               
                              Working...
                              X