• If this is your first visit, you will have to register before you can post. To view messages, please scroll below and select the forum that you would like to visits. Questions? Be sure to check out the Forum FAQ.


No announcement yet.

Partner 728x90


Highest / Lowest Price within a certain Range; MIN(), MAX() Issue

  • Filter
  • Time
  • Show
Clear All
new posts

    Highest / Lowest Price within a certain Range; MIN(), MAX() Issue

    I'm trying to get the highest / lowest price for a certain range - so far so good, here's my code (an excerpt of it):

    namespace NinjaTrader.NinjaScript.Indicators
    // [TypeConverter("NinjaTrader.NinjaScript.Indicators. PivotsTypeConverter")]
    public class HighLowRange: Indicator
    private double sum, lowestPrice, highestPrice, fractal;
    protected override void OnStateChange()
    if (State == State.SetDefaults)
    Description = @"Plot High / Low of a certain range";
    Name = "HighLowRange";
    Calculate = Calculate.OnBarClose;
    DisplayInDataBox = false;
    DrawOnPricePanel = false;
    IsAutoScale = false;
    IsOverlay = true;
    PaintPriceMarkers = true;
    ScaleJustification = ScaleJustification.Right;

    iLookBackPeriodBars = 64;
    AddPlot(Brushes.Red, "H88");
    AddPlot(Brushes.Green, "L08");

    protected override void OnBarUpdate()
    lowestPrice = MIN(Low, li_LookBack)[0];
    highestPrice = MAX(High, li_LookBack)[0];

    This gives completely false values.

    I also tried it with determining of the index
    lowestPrice = Low[LowestBar(Low, li_LookBack)];
    highestPrice = High[HighestBar(High, li_LookBack)];

    However this also is not retrieving the correct values

    Only if I determine the values when processing just the last Bar and putting in the condition

    if(Count - CurrentBar > 2)

    before the calculation does it retrieve the correct value, however this messes up the plots and everything else that comes afterwards.

    Please advice. Thank you

    Thanks for your post abctrader,

    MIN will return the lowest price from a Series looking back a certain number of bars. MAX will return the highest price in a Series looking back a certain number of bars.

    Demo - https://drive.google.com/file/d/1FVm...w?usp=drivesdk

    When you test the same on your end, are you seeing something different? What values are you getting when you test the same and what are you expecting to get?

    I look forward to being of any further assistance.
    JimNinjaTrader Customer Service


      Thanks for your response Jim

      I've attached the complete file - If you attach it e.g to the current GC contract, you'll see that the output is not correct since it's calculating the wrong low and high values for the given period. You can see in the Ninjascript Output what values are calculated.

      Then look for the following line:

      // if((Count - CurrentBar) > 2) return;

      un-comment it and you'll see now that the values are calculated correctly, however the plots are not processed any longer.

      Thanks for your help - really no idea what I'm doing wrong
      Last edited by abctrader; 11-08-2018, 04:48 PM.


        Hello abctrader,

        I've created another demonstration showing how MAX could be analyzed by looking at the debug output.

        Demo - https://drive.google.com/file/d/1vIu...w?usp=drivesdk

        Print: Print(string.Format("highestPrice: {0} index: {1} range: {2}", highestPrice, CurrentBar, li_LookBack));

        As for your condition: if((Count - CurrentBar) > 2) return;

        This will compare the number of bars available in the script to the number of bars it has processed and if it is greater than 2. This is essentially checking if you are processing historical data since Count will not increase until Realtime data is processed and new bars are built. I typically would not recommend this type of check involving Count and would suggest to use Bars.Count or BarsArray[0].Count so the reference is valid with Multi Time Frame NinjaScripts. Checking if (State == State.Historical) return; would be a close parallel to this condition.

        Please let me know if we can be of further assistance.
        JimNinjaTrader Customer Service


          Unfortunately there's no sound on your last video and I couldn't figure out what you were trying to communicate - Sorry


            Hello abctrader,

            In the video I am printing the CurrentBar when MAX is called, and then I am looking for that Bar Index on the Chart when I have the Data Box open.

            From there, I check the highest value of that bar and I go check 3 more bars back since I am testing with a period of 4. The High of that bar (Bar Index 4131) was 1228 and the high of the 3 bars prior were 1227.9. Since, I was testing with a period of 4 for MAX, and 1228 is greater than the 1227.9 value from the previous bars, 1228 was the MAX.

            Please let me know if you have any questions.
            JimNinjaTrader Customer Service


              Ok - Thx much; seem to have the MIN() MAX() solved; If I could get the Price to now also print with the full decimal places I'd be happy ...

              E.g. in Euro the price marker for the lines printed shows as 1.14, when in fact I'd like to see it as 1.13720 ... not sure what I need to do there. Any clue? Thx again


                Hello abctrader,

                You could use FormatPriceMarker to reformat the appearance of values in the Price Marker.

                FormatPriceMarker - https://ninjatrader.com/support/help...ricemarker.htm

                More information on formatting strings in C# can be found here - https://docs.microsoft.com/en-us/dot...format-strings

                Let us know if there is anything else we can do to help.
                JimNinjaTrader Customer Service


                  Ok thx 4 everything - looks like I've got it all figured out - Have a great weekend


                    Hello abctrader

                    I am interested in your code as well, if it is possible to share it.



                      One more issue I'm facing is the chart not displaying the lines like they are calculated by the script.

                      I've attached 2 pictures: the 6B chart with the (incorrect) lines and the DataBox which has the correct values for the lines.

                      I've tried to refresh the chart, reload the NinjaScript (F5), however the lines aren't updating to the correct values, even though the values on the right-hand axis are correct!!!

                      Thanks for your help


                        Hello abctrader,

                        This script is using SharpDX for custom rendering, correct? The plots in the data box and the chart should be correct for the plot values, but the drawing of the lines does not look the same.

                        We have some example SharpDX code that loops through all plots that are added and customizing the rendering similar to what you are trying to accomplish. I would recommend testing with that code and if you need to debug it, you could look into printing what plotValue is being used in the loop for each plot that you want to look into.

                        For example:

                        protected override void OnRender(ChartControl chartControl, ChartScale chartScale)
                          // get the starting and ending bars from what is rendered on the chart
                          float startX = chartControl.GetXByBarIndex(ChartBars, ChartBars.FromIndex);
                          float endX = chartControl.GetXByBarIndex(ChartBars, ChartBars.ToIndex);
                          // Loop through each Plot Values on the chart
                          for (int seriesCount = 0; seriesCount < Values.Length; seriesCount++)
                            // get the value at the last bar on the chart (if it has been set)
                            if (Values[seriesCount].IsValidDataPointAt(ChartBars.ToIndex))
                                double plotValue = Values[seriesCount].GetValueAt(ChartBars.ToIndex);
                               if(seriesCount == 1)Print(plotValue);
                        The sample code that you can try can be found at the following link under "Using multiple SharpDX objects to override the default plot appearance" - https://ninjatrader.com/support/helpGuides/nt8/en-us/onrender.htm

                        Please let us know if there is anything else we can do to help.
                        Last edited by NinjaTrader_Jim; 11-15-2018, 09:05 AM.
                        JimNinjaTrader Customer Service


                          Hi Jim

                          Thanx for your time and help. I figured the issue must be within the OnRender logic ...

                          I'm now using the exact same code like the one used within the standard Pivot indicator, since I basically want it to behave the same way. HOWEVER, it is still displaying incorrect values and not adjusting them properly once the calculated values change. It's still displaying the wrong lines, even though the data in the DataBox is different. Any help would be appreciated. Thanks


                            Hello abctrader,

                            The levels where the lines are drawn are going to be based entirely off of what is sent to the RenderTarget.DrawLine() methods. The coordinates should be back traced to where they are assigned using ChartControl.GetXByBarIndex and ChartScale.GetYByValue.

                            The sample code linked in my previous message (I did not include the full link and updated my post. Link here) demonstrates setting your own plot values and drawing your own lines in OnRender(). I would recommend setting up this test code in a new script and then modify the plots so you can verify that you are able to create your own custom plots and draw them appropriately.

                            Once you can confirm that you are getting the results you expect, I would then recommend testing the same with your indicator. After you are able to draw custom plots appropriately in these two steps, it should not be difficult to correct the existing lines so they behave the same.

                            Let us know if there is anything else we can do to help.
                            JimNinjaTrader Customer Service


                              Releasing drawn lines prior to writing new ones. Is there a recommended method to release drawn lines for Min Max when using Draw Horizontal Line before drawing new ones so they do not build up in the history?


                              Latest Posts


                              Topics Statistics Last Post
                              Started by sisenberg, Today, 07:40 AM
                              1 response
                              Last Post NinjaTrader_SergeyS  
                              Started by revdozza, Today, 06:54 AM
                              2 responses
                              Last Post revdozza  
                              Started by ztrader, Today, 07:07 AM
                              1 response
                              Last Post NinjaTrader_DrewO  
                              Started by ballboy11, Yesterday, 04:33 PM
                              3 responses
                              Last Post NinjaTrader_Jesse  
                              Started by zhiga, Yesterday, 12:54 AM
                              4 responses
                              Last Post NinjaTrader_ChristopherD