Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

green to red strategy: assistance - collaboration.

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

    green to red strategy: assistance - collaboration.




    people with nt, fellow nt users,



    i want to develop a green to red strategy i have had in mind for a while and i will appreciate both the assistance of nt's staff and also any assistance from other nt users.




    the general structure would be very simple, if price is made to open at a higher level than that of the close of the previous session then declare a green condition to be true, if price is being sold lower, open a short position and set stop loss and profit target orders. and that would be it.




    the difficulty for me results from knowing which kind of inputs - variables to use in nt - c# and how to best make them work from one trading session to the other as necessary. i have a list of very specific questions, so it will be impossible for nt support to resort to their usual position of - we won't code for you -. if any other users have any advice, that will be quite welcome.



    - first question, for the "close" value, i want to use something like the value for the highest high between 15:30 and 16:00 for the previous trading session. also, there must be some way to avoid the problems caused by shortened sessions, sessions closed due to holidays or weekends for which this highest high value does not exist. so, ¿what would be the best way to store - hold the value for the highest high between 15:30 and 16:00 for the nearest previous session for which this value exists and have it available for the next occasion in which it could be used?


    - second question, for the "open" value, i am considering the highest high between 09:30 and 10:00 for the current session. same as before, ¿which would be the best format and type of variable to have this value available when applicable?


    if "open" is at least .5% higher than "close", then i would declare the green condition to be true. i think a boolean variable should work perfectly for this purpose.


    - then, if green is true and a bar is made to close below the arithmetic halfway point between "open" and "close" then i would declare the to red condition to be true, green to now be reset to false and open a short position with a stop above the high of the day and a profit target below the value for "close". ¿which would be the best formats and types of variable to have these values available to be used to open a position and set a stop loss - profit target bracket?


    - it seems to me that most of these variables could need to be reset after the end of each trading session. ¿how could this be accomplished?


    - and lastly for the moment, if i wanted to evaluate whether a green to red pattern has any lasting effects, ¿how could i create a variable that would be true for the next three following trading sessions only if the pattern is observed and price is sold lower than the value for "close" at some point? there must be very elegant ways to create and process a variable to serve such a purpose.





    this is it for the moment, hopefully this should be an easy strategy to develop and should generate interesting results.


    very well, thanks, regards.

    #2
    Hello rtwave,

    For your first question you would have to make time conditions and then accumulate a high or low during that time. To avoid short trading sessions like holidays you would have to add additional logic to handle those situations and replace the accumulated high/low with whatever value you wanted to use instead. NinjaScript uses double numbers for prices so storing a price would require a double type variable.

    For your second question that would essentially be the same answer, a double variable could be used for that.

    Checking price conditions results in a bool result so checking if the open is greater than 5% higher than the close would result in a true/false condition. If you needed to store that as a variable you could use a bool variable.

    To reset variables you can use the first bar of session variable: https://ninjatrader.com/support/help...htsub=firstbar

    Variables are only reset when you choose to reset them, if you wanted it to persist for multiple sessions you would just not reset it until you need to.





    Comment


      #3





      this strategy i have in mind is really simple but it is going to be brutally, brutally difficult for me to develop.



      i have been looking at nt indicators or samples that could be of use for this strategy i have in mind, and indeed i have found several exemplars that could be of help.



      this one below is quite similar to what i have in mind, same with the previous and current day ohlc lines and other pieces of code.







      however, this initial research has also led me to find out that the structure for the strategy will not be like i had in mind and will actually be quite complicated. if it is not possible for the nt platform to calculate a higher high - lower low other than with a bars ago logic then i will have to adapt the entire strategy to this format.




      i will eventually ask for assistance on the stckvrflow fora but it is not easy at all to get help there either. jaja. we will have to see how everything progresses.

      Comment


        #4



        people with nt,


        this below is what i have been able to piece together so far from the strategy i have been discussing here.



        Code:
        namespace NinjaTrader.NinjaScript.Strategies
        {
        public class greentoreddevelopment1 : Strategy
        {
        private double Valueclose;
        private double Valueopen;
        private double Valueforentry;
        private double Valueforstlo;
        private double Valueforprta;
        private bool Greenco;
        private bool Toredco;
        
        
        protected override void OnStateChange()
        {
        if (State == State.SetDefaults)
        {
        Description = @"greentoreddevelopment1.";
        Name = "greentoreddevelopment1";
        Calculate = Calculate.OnBarClose;
        EntriesPerDirection = 1;
        EntryHandling = EntryHandling.UniqueEntries;
        IsExitOnSessionCloseStrategy = false;
        ExitOnSessionCloseSeconds = 10;
        IsFillLimitOnTouch = false;
        MaximumBarsLookBack = MaximumBarsLookBack.TwoHundredFiftySix;
        OrderFillResolution = OrderFillResolution.Standard;
        Slippage = 1;
        StartBehavior = StartBehavior.ImmediatelySubmitSynchronizeAccount;
        TimeInForce = TimeInForce.Gtc;
        TraceOrders = true;
        RealtimeErrorHandling = RealtimeErrorHandling.StopCancelCloseIgnoreRejects ;
        StopTargetHandling = StopTargetHandling.PerEntryExecution;
        BarsRequiredToTrade = 10;
        // Disable this property for performance gains in Strategy Analyzer optimizations
        // See the Help Guide for additional information
        IsInstantiatedOnEachOptimizationIteration = true;
        Valuedefineentry = 0.9;
        Valuedefineprta = 0.98;
        Valuedefinestlo = 1.002;
        Valuedefinegreen = 1.005;
        Nuofbafoca = 6;
        Valueclose = 0;
        Valueopen = 0;
        Valueforentry = 0;
        Valueforstlo = 0;
        Valueforprta = 0;
        Greenco = false;
        Toredco = false;
        }
        else if (State == State.Configure)
        {
        SetProfitTarget(@"greentoredentry.", CalculationMode.Price, Valueforprta);
        SetStopLoss(@"greentoredentry.", CalculationMode.Price, Valueforstlo, false);
        }
        }
        
        protected override void OnBarUpdate()
        {
        if (BarsInProgress != 0)
        return;
        
        if (CurrentBars[0] < 10)
        return;
        
        // Set 1
        if (High[0] > High[2])
        {
        Greenco = true;
        }
        
        // Set 2
        if ((Greenco == true)
        && (Close[0] <= Valueforentry))
        {
        EnterShort(Convert.ToInt32(DefaultQuantity), @"greentoredentry.");
        Greenco = false;
        Toredco = true;
        }
        
        // Set 3
        if (High[1] > High[3])
        {
        Greenco = true;
        Toredco = false;
        }
        
        }
        
        [HASHTAG="t3322"]region[/HASHTAG] Properties
        
        [NinjaScriptProperty]
        [Range(1, double.MaxValue)]
        [Display(Name="Valuedefineentry", Description="valuedefineentry.", Order=1, GroupName="Parameters")]
        public double Valuedefineentry
        { get; set; }
        
        [NinjaScriptProperty]
        [Range(1, double.MaxValue)]
        [Display(Name="Valuedefineprta", Description="valuedefineprta.", Order=2, GroupName="Parameters")]
        public double Valuedefineprta
        { get; set; }
        
        [NinjaScriptProperty]
        [Range(1, double.MaxValue)]
        [Display(Name="Valuedefinestlo", Description="valuedefinestlo.", Order=3, GroupName="Parameters")]
        public double Valuedefinestlo
        { get; set; }
        
        [NinjaScriptProperty]
        [Range(1, double.MaxValue)]
        [Display(Name="Valuedefinegreen", Description="valuedefinegreen.", Order=4, GroupName="Parameters")]
        public double Valuedefinegreen
        { get; set; }
        
        [NinjaScriptProperty]
        [Range(1, int.MaxValue)]
        [Display(Name="Nuofbafoca", Description="Nuofbafoca.", Order=5, GroupName="Parameters")]
        public int Nuofbafoca
        { get; set; }
        
        #endregion​
        Last edited by rtwave; 08-30-2023, 12:54 AM.

        Comment


          #5


          it is evident that i have not been able to make any progress on the highest high parts.

          i am thinking of using a structure similar to this sample i linked previously:






          - ¿is it possible to create a mechanism like the one below that would only calculate every day at exactly 16:00? and then it should hold that value until it was calculated again.


          - i'm thinking of defining the value of number of bars to calculate on as an input. for example, on a 5 minute bar chart the number of bars to go back to cover the 15:30 to 16:00 interval would be 6. for other bar sizes this input would also be trivial to determine.


          Code:
          
          if (EndHour < StartHour)
                          return;
          
          
                      //Do not calculate the high or low value when the ending time of the desired range is less than the current time of the bar being processed
                      if (ToTime(EndHour,EndMinute,0) > ToTime(Time[0]))
                          return;  
          
          
          
                      // If the stored date time date is not the same date as the bar time date, create a new DateTime object
                      if (startDateTime.Date != Time[0].Date)
                      {
                          startDateTime = new DateTime(Time[0].Year, Time[0].Month, Time[0].Day, StartHour, StartMinute, 0);
                          endDateTime = new DateTime(Time[0].Year, Time[0].Month, Time[0].Day, EndHour, EndMinute, 0);    
                      }
          
                      // Calculate the number of bars ago for the start and end bars of the specified time range
                      int startBarsAgo = Bars.GetBar(startDateTime);
                      int endBarsAgo = Bars.GetBar(endDateTime);
          
                      /* Now that we have the start and end bars ago values for the specified time range we can calculate the highest high for this range
          
                      Note: We add 1 to the period range for MAX and MIN to compensate for the difference between "period" logic and "bars ago" logic.
                      "Period" logic means exactly how many bars you want to check including the current bar.
                      "Bars ago" logic means how many bars we are going to go backwards. The current bar is not counted because on that bar we aren't going back any bars so it would be "bars ago = 0" */
                      double highestHigh = MAX(High, endBarsAgo - startBarsAgo  + 1)[CurrentBar - endBarsAgo];
          
                                   // Set the plot values
                      HighestHigh[0] = highestHigh;​

          the logic for the 09:30 to 10:00 will seemingly be much more difficult to develop.
          Last edited by rtwave; 08-30-2023, 12:57 AM.

          Comment


            #6
            Hello rtwave,

            If you want to do an action at a specific time each day you can create a time condition to do that. There are examples of making time conditions in the following link. A single time condition can be used to check for 1 specific time, a 2 part condition can be used to check if the time falls within a range of times.

            Comment


              #7




              people with nt,


              i have been able to make some interesting progress.


              i have been able to create this version below of the sample indicator i have linked previously. this code is able to have the highest high between 15:30 and 16:00 available every day, right at 16:00 hours.


              however, now i need to work on the other interval i need for the calculations: the highest high between 9:30 and 10:00.


              if i use this same code and just change the parameters, there will be two problems i can identify right away.


              _ first of all, it seems to me that right between 09:30 and 10:00, the strategy would resort to using the values of the previous day. this would defeat the entire exercise. ¿how can i make sure that the 09:30 to 10:00 interval will always correspond to the current date and the 15:30 to 16:00 interval will always correspond to the previous date? ¿is there any way to check for the date of each or to "index" these variables?


              _ and, additionally, the green to red opportunities that this strategy will try to profit from can easily start selling lower to lower prices between 09:30 and 10:00 hours. i need the strategy to work with the highest high up to that moment and last - closing prices before 10:00 if it is still not 10:00 hours, and then only use the values for the 09:30 to 10:00 interval after 10:00 hours. if the information for the previous day is available and time is greater than 09:30 then use real time data for today right away and then use the definitive data after 10:00 hours.


              Code:
              
              
              namespace NinjaTrader.NinjaScript.Indicators
              {
                  public class delolohihive0001 : Indicator
                  {
                      protected override void OnStateChange()
                      {
              
                          if (State == State.SetDefaults)
                          {
                              Description                    = @"Determines the highest high and lowest low in a specified time range";
                              Name                        = "delimited lolo hihi";
                              Calculate                    = Calculate.OnBarClose;
                              IsOverlay                    = true;
                              DisplayInDataBox            = true;
                              DrawOnPricePanel            = true;
                              DrawHorizontalGridLines        = true;
                              DrawVerticalGridLines        = true;
                              PaintPriceMarkers            = true;
                              ScaleJustification             = NinjaTrader.Gui.Chart.ScaleJustification.Right;
                              StartHour                    = 9;
                              StartMinute                    = 30;
                              EndHour                        = 10;
                              EndMinute                    = 00;
                              Calculatevalueclose            = DateTime.Parse("16:00", System.Globalization.CultureInfo.InvariantCulture);
                              Nuofbafoca                    = 1;
                              AddPlot(Brushes.Green, "HighestHigh");
                              AddPlot(Brushes.Red, "LowestLow");
                              AddPlot(new Stroke(Brushes.DarkBlue, DashStyleHelper.Solid, 3), PlotStyle.Line, "Trialseries");
              
                          }
                      if (State == State.Configure)
                      {
                      AddDataSeries(BarsPeriodType.Minute, 30);
                      }
                      }
              
                      private DateTime startDateTime;
                      private DateTime endDateTime;
                      private double trialseries;
                      protected override void OnBarUpdate()
                      {
              
                          if (CurrentBars[0] < 2) return;
              
              
              
                          if ( (Times[1][0].TimeOfDay >= Calculatevalueclose.AddMinutes(-1).TimeOfDay)
                              && (Times[1][0].TimeOfDay <= Calculatevalueclose.AddMinutes(1).TimeOfDay) )
                          {
                          trialseries = MAX(Highs[1], Nuofbafoca)[0];
                          }
              
                          // Set the plot values
              //            HighestHigh[0] = highestHigh;
              //            LowestLow[0] = lowestLow;
                          Trialseries[0] = trialseries;
              
                      }
              
              ​


              ¿how could these refinements i have explained be implemented?



              very well, regards.

              Comment


                #8
                Hello rtwave,

                It looks like the script provided is omitting variables or other logic so I would not be sure how this code would work. If you want to know if the values between 9;30 and 10 are correct you can use prints in your actual logic to confirm if that theory is right or not.

                For the second item you mentioned you would have to make logic that accomplishes that task. I wouldn't be able to walk through all of the steps required to do each of those items but you would need to use a variable for your calculation and more time conditions to delegate how your logic works. I would suggest to become familiar with prints because that lets you output runtime variables and also see how your logic is actually executing so you have a good idea on how to implement your ideas.


                Comment


                  #9



                  people with nt,



                  i have continued to work on this strategy. in the time since i created this thread there have been two notable green to red patterns that would have been beautifully profitable.




                  this code below works to open green to red positions on another crappy platform. however, it is impossible to add bracket orders with stop loss and profit target orders as i have in mind and then backtest the strategy, so i just persevere.








                  if (time > 930 and time[1] < 930)
                  or (time > 930 and date <> date[1]) then
                  begin
                  todaysopen = high;
                  end else if time > 930 and time <= 1000 then
                  begin
                  if high > todaysopen then
                  todaysopen = high;
                  end;


                  if (time > 1530 and time[1] < 1530)
                  or (time > 1530 and date <> date[1]) then
                  begin
                  yesterdaysclose = high;
                  end
                  else if time > 1530 and time <= 1600 then
                  begin
                  if high > yesterdaysclose then
                  yesterdaysclose = high;
                  end;


                  if date <> date[1] and ( todaysopen > ( valuedefinegreen ) * ( yesterdaysclose ) ) then
                  begin
                  greencondition = true;
                  end;

                  if greencondition = true and ( close[0] <= ( todaysopen + ( ( valuedefineentry ) * ( todaysopen - yesterdaysclose ) ) ) ) then
                  begin
                  greencondition = false;
                  toredcondition = true;
                  if abstainfromtrade = false then
                  sell short ("green to red entry a") posi shares next bar at market;
                  end;

                  if toredcondition = true and ( high[0] >= ( valuedefinestlo ) * ( todaysopen ) ) then
                  begin
                  greencondition = true;
                  toredcondition = false;
                  end;

                  if time >= cutofftime then
                  begin
                  abstainfromtrade = true;
                  buy to cover all shares next bar at market;
                  end else begin
                  abstainfromtrade = false;
                  end;





                  in nt i already have most of the general structure in place, specially the stop loss and profit target orders. it is this fragment of code below that i have been unable to code in nt. this formulation seemingly works great and avoids all the issues with shortened or not worked sessions. ¿can the staff at nt tell how should this formulation be coded in nt?




                  if (time > 930 and time[1] < 930)
                  or (time > 930 and date <> date[1]) then
                  begin
                  todaysopen = high;
                  end else if time > 930 and time <= 1000 then
                  begin
                  if high > todaysopen then
                  todaysopen = high;
                  end;


                  if (time > 1530 and time[1] < 1530)
                  or (time > 1530 and date <> date[1]) then
                  begin
                  yesterdaysclose = high;
                  end
                  else if time > 1530 and time <= 1600 then
                  begin
                  if high > yesterdaysclose then
                  yesterdaysclose = high;
                  end;​



                  very well, regards.

                  Comment


                    #10
                    Hello rtwave,

                    To make braket orders you have to use the unmanaged approach, you can see a sample of that here: https://ninjatrader.com/support/foru...926#post486926

                    The code you have asked about has a few time conditions and is using a few double variables. You would need to make time conditions and also a private double variables.

                    We have samples of how to make time conditions here: https://ninjatrader.com/support/help...ightsub=totime
                    You can additional find how to make date conditions here: https://ninjatrader.com/support/help...lightsub=today

                    after making double variables you could assign the value using the High series

                    todaysopen = High[0];


                    Comment

                    Latest Posts

                    Collapse

                    Topics Statistics Last Post
                    Started by NullPointStrategies, Today, 05:17 AM
                    0 responses
                    53 views
                    0 likes
                    Last Post NullPointStrategies  
                    Started by argusthome, 03-08-2026, 10:06 AM
                    0 responses
                    130 views
                    0 likes
                    Last Post argusthome  
                    Started by NabilKhattabi, 03-06-2026, 11:18 AM
                    0 responses
                    70 views
                    0 likes
                    Last Post NabilKhattabi  
                    Started by Deep42, 03-06-2026, 12:28 AM
                    0 responses
                    44 views
                    0 likes
                    Last Post Deep42
                    by Deep42
                     
                    Started by TheRealMorford, 03-05-2026, 06:15 PM
                    0 responses
                    49 views
                    0 likes
                    Last Post TheRealMorford  
                    Working...
                    X