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

Coloring Bars at certain Times

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

    Coloring Bars at certain Times

    I know this must be incredibly simple but having searched the forum, downloaded several sample files (for example from : http://www.ninjatrader-support2.com/...ad.php?t=19176 ) I have got nowhere.

    All I want to do is plot on a 15 min chart certain bars at specified times, preferably having those times in the indicator menu so that I can change them around after the indicator is loaded. But I can't even get to step 1 which is being able to code in plotting a barcolor on a specific bar.

    So if someone could show me how to write out in Ninja script:

    if (Time[0] == 094500) {BarColor = Color.Red;} (which of course doesn't work)

    I would be very grateful.

    I also tried making a different version of the default Range indicator with the idea being to color the bars at certain times but again was unable to figure out how to code it for the same reason as in the snippet above which doesn't work. It doesn't like ints or strings.

    That's Step One.

    What I would really like to have is an indicator that would show the average Range, bar by bar, over the period which the chart is loaded so that with a 30 minute chart, for example, the indicator would plot on each bar the average range at that time. Perhaps it is not possible to have it automatically adjust to the entire loaded chart, in which case the last x occurrences, like 30 or whatever. That way the indicator will instantly show the times of day with the highest and lowest ranges and/or whether or not there are any discernible periods or if there is an even distribution throughout all times of day.

    This is sort of like a daily seasonal indicator and I suspect it will need savvy loop coding which I am useless at even when not working in Ninja which I am totally useless at. But such an indicator would be a handy analytical tool for quickly picking out instruments that exhibit clear patterns of having certain times of day that are regularly more volatile than others.
    Last edited by cclsys; 09-06-2009, 06:49 PM.

    #2
    cclsys,

    Since you are using a bars type indicator, that makes things easier.

    Here's a way to change bar colors.

    Just create two outputs then switch back and forth based on time.

    make parts of your code look something like this...

    --------------------------------------------------------------------
    variables area:
    private bool RedBars = false;


    initial area:
    Add(new Plot(new Pen(Color.Red , 4) , PlotStyle.Bar, "PlotRedBars"));
    Add(new Plot(new Pen(Color.Gray , 4) , PlotStyle.Bar, "PlotGrayBars"));


    update area:
    if (Time[0] == 094500) RedBars == true;

    if (Time[0] == 154500) RedBars == false;

    if (RedBars)Values[0].Set(Volume[0]);

    if (!RedBars)Values[1].Set(Volume[0]);

    --------------------------------------------------------------------

    Try building a new indicator with this stuff.

    Good luck,

    RJay
    RJay
    NinjaTrader Ecosystem Vendor - Innovative Trading Solutions

    Comment


      #3
      cclsys,

      Try this,

      if (ToTime(Time[0]) == 094500) BarColor = Color.Red;

      That will color the actual price bar that ends at 9:45 red, which is what I think you want to do. If you want to have that time be adjusted when applied to a chart set it as an "int" input parameter and call it like this.

      if (ToTime(Time[0]) == RedBar) BarColor = Color.Red;

      Hope this helps.
      VT

      Comment


        #4
        Originally posted by rt6176 View Post
        cclsys,

        Since you are using a bars type indicator, that makes things easier.

        Here's a way to change bar colors.

        Just create two outputs then switch back and forth based on time.

        make parts of your code look something like this...

        --------------------------------------------------------------------
        variables area:
        private bool RedBars = false;


        initial area:
        Add(new Plot(new Pen(Color.Red , 4) , PlotStyle.Bar, "PlotRedBars"));
        Add(new Plot(new Pen(Color.Gray , 4) , PlotStyle.Bar, "PlotGrayBars"));


        update area:
        if (Time[0] == 094500) RedBars == true;

        if (Time[0] == 154500) RedBars == false;

        if (RedBars)Values[0].Set(Volume[0]);

        if (!RedBars)Values[1].Set(Volume[0]);

        --------------------------------------------------------------------

        Try building a new indicator with this stuff.

        Good luck,

        RJay
        +++++++++++

        Thanks RJ. I built a new one with 2 plots as per your recommendation and tried to do exactly what you have above to start with (i.e. plot Volume with different color).

        Thus:

        if (Time[0] == 094500) {RedBars == true;}
        if (Time[0] > 094500) RedBars == false;

        if (RedBars)Values[0].Set(Volume[0]);

        if (!RedBars)Values[1].Set(Volume[0]);

        But I am getting the same error. Time[0] cannot be linked to 094500.

        Error is: CS0019, ' Operator == cannot be applied to operands of type System Date Time and int. ( I sort of understand this, but cannot find any clue in the Help Menu examples or on the forum as to how to fix it. Hence this thread.)
        Also Error CS0201: Only assignment, call, increment, decrement and new object expressions can be used as a statement. (a msg which is beyond my pay grade to make head or tail of).


        That is what was happening before when I was working with the Default Range Indicator and simply trying to color the bars at certain times.

        Comment


          #5
          cclsys,
          See my post above, you need to use,

          if (ToTime(Time[0]) == 094500) BarColor = Color.Red;

          VT
          Last edited by VTtrader; 09-07-2009, 10:27 AM.

          Comment


            #6
            Here is the help menu on Time:

            A collection of historical bar time stamp values.


            Property Value
            A TimeSeries type object.


            Syntax
            Time
            Time[int barsAgo] (returns a DateTime structure)


            Property Of
            Custom Indicator, Custom Strategy


            Examples
            // Prints the current bar time stamp
            Print(Time[0].ToString());
            // Checks if current time is greater than the bar time stamp
            if (DateTime.Now.Ticks > Time[0].Ticks)
            Print("Do something");



            I suspect that this error has to do with the 'DateTime' structure, for which there is no information unless that is the section on the DateTime Series class. The link in the Help Menu does not work.

            I tried adding in a DateTimeSeries "dts" following the DateTimeSeries Help Menu and changed the code to

            dts.Set(DateTime.Now);
            if (dts[0] == 094500) {RedBars = true;}
            if (dts[0] > 094500) {RedBars = false;}

            but this gives the same error messages. I suspect that 094500 is incorrectly formatted as an int. I have also tried making it a string but it doesn't like that either. I have tried writing it 09:45:00 AM (which is what is printed out for Time[0]) but it doesn't like that either, either as string or int.

            One improvement though: only error CS0019, with CS0201 having been addressed by using a data series instead of Time[0];

            The Print for Time[0] or dts[0] is the same:

            07/09/2009 12:24:53 PM


            So it includes a Date. I don't want a date so I should be using a date time series. All I want is hour and minute. Maybe that is the problem? There is nothing for 'hour' or 'minute' in the help menu but I suspect there is coding for that somewhere.
            Last edited by cclsys; 09-07-2009, 10:26 AM.

            Comment


              #7
              #region Variables
              // Wizard generated variables
              private int startHour = 9; // Default setting for StartHour
              private int startMinute = 30; // Default setting for StartMinute
              private int endHour = 10; // Default setting for EndHour
              private int endMinute = 15; // Default setting for EndMinute
              // User defined variables (add any user defined variables below)
              #endregion

              /// <summary>
              /// This method is used to configure the indicator and is called once before any bar data is loaded.
              /// </summary>
              protected override void Initialize()
              {
              Add(new Plot(Color.FromKnownColor(KnownColor.Green), PlotStyle.Line, "HighestHigh"));
              Add(new Plot(Color.FromKnownColor(KnownColor.Red), PlotStyle.Line, "LowestLow"));
              CalculateOnBarClose = true;
              Overlay = true;
              PriceTypeSupported = false;
              }

              private DateTime startDateTime;
              private DateTime endDateTime;

              /// <summary>
              /// Called on each bar update event (incoming tick)
              /// </summary>
              protected override void OnBarUpdate()
              {
              // Check to make sure the end time is not earlier than the start time
              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 = GetBar(startDateTime);
              int endBarsAgo = GetBar(endDateTime);

              // Now that we have the start end end bars ago values for the specified time range we can calculate the highest high for this range
              double highestHigh = MAX(High, startBarsAgo - endBarsAgo)[endBarsAgo];

              // Now that we have the start end end bars ago values for the specified time range we can calculate the lowest low for this range
              double lowestLow = MIN(Low, startBarsAgo - endBarsAgo)[endBarsAgo];

              // Set the plot values
              HighestHigh.Set(highestHigh);
              LowestLow.Set(lowestLow);
              }

              ++++++++

              That is code from the SampleGetHighLowbyTimeRange and I suspect using the ToTime function is the way to go, but I really don't understand all the lines in this and what they are doing, especially since one of their main concerns is to identify new and old day periods. I don't want that. I just want to change the color of a bar which closes at, for example 945 am on a 15 minute bar chart.

              Comment


                #8
                OK one last try.
                clcsys, are my posts not coming through?
                scroll up (or down).

                You need to use

                if (ToTime(Time[0]) == 094500) BarColor = Color.Red;

                very simple, your first attempt was just missing the ToTime() function

                Comment


                  #9
                  Originally posted by VTtrader View Post
                  OK one last try.
                  clcsys, are my posts not coming through?
                  scroll up (or down).

                  You need to use

                  if (ToTime(Time[0]) == 094500) BarColor = Color.Red;

                  very simple, your first attempt was just missing the ToTime() function

                  Thanks RT. I missed your last one posting a couple in the row and didn't see a new one had come in. It IS very simple. I did try it earlier but must have had some other element wrong from trying so many different things with Time[0] and could not interpret the error msgs properly.

                  So now I have:

                  if (ToTime(Time[0]) == 094500 || ToTime(Time[0]) == 120000 || ToTime(Time[0]) == 150000)
                  {RedBars = true;} else RedBars = false;


                  if (RedBars) Values[0].Set (Range()[0]);
                  if (!RedBars) Values[1].Set (Range()[0]);

                  And it works fine. Thank you very much.

                  Comment


                    #10
                    Now that that simple business is out of the way (!), anyone interested in working on making an indicator like the above but which shows the average of last x occurrences for each time period on a minute bar chart? So instead of plotting the current Range of the current bar, it plots the average range at this time, i.e. the average range of all the 9.45 bars on the chart or if that is too difficult the average range of all the 945 bars the past 21 occurrences (for example).

                    This would create an instant intraday barchart 'seasonal' of sorts and might prove quite revealing.

                    I suspect you/we would have to
                    a) create a loop command that labels each bar in the day according to the time at the close (not the bar number of the day because of holidays etc. although maybe the first would work because they nearly always start at the same time, just don't always end at the same time which is fine).
                    b) then apply the range to particular bars (900,915,930,945 etc.)
                    c) then take an average of either last x occurrences (simpler) for each bar time or
                    d) same as above but have a loop command structure that adjusts how many occurrences based on the number of days/bars loaded on the chart versus picking an arbitrary Period value like 21, 50 etc.

                    Comment


                      #11
                      clcsys,
                      lol, I had a feeling that the posts were crossing, glad you got it working.

                      BTW, you don't have to go to the trouble of having different plots to just color a bar. The original way you did it (except using it with the ToTime() function), will work fine and probably more efficient since you don't have to store 2 DataSeries to accomplish it.

                      VT

                      Comment


                        #12
                        By the way, I started to work on this from reading the following article at:



                        "f you ever needed to see a formalized definition of what momos are and why they believe chasing momentum is actually a credible strategy instead of a self-perpetuating bubble that sucks many of their kind in, until the musical chairs game stops and then you have a mad dash for the fire exits, read the below press release by AQR, issued when Cliff Asness' fund decided to go pedal to the metal in momoism. And keep in mind Cliff is not alone - these are the same "strategies" that gun up the market every day at 9:45 am, noon and 3:30 pm, simply because "it has worked in the past." Then again, the question, just like in the RenTec case, is who is on the other side of the trade that recurs like clockwork each and every day and where just 60 minutes of trading accounts for over 70% of the entire intraday stock market movement over the past 6 months. Another key question to consider as more and more momos pile into the momentum trade is what happens when it fails and all the previously natural buyers become very unnatural sellers. Will be a sight to behold when the momentum flips. But for now, someone is very happy to keep feeding the momos, who, with Pavlovian regularity, keep coming back, until one day the Skinner box fails."

                        It's a smart little blog with many interesting market-related tidbits.

                        Now that I can run the indicator - and having only looked quickly at the TF - the 945 call seems pretty accurate (though of course that is just after the opening so hardly surprising) but the 1200 and 1530 one doesn't seem so accurate albeit there are many examples of the range spiking up just at or after those times. But more generally, it gave me the idea to try to make an indicator that would automatically reveal such times - if they exist regularly - when plotted rather than manually inputting certain times to highlight as the above starter model does.

                        Comment


                          #13
                          Originally posted by VTtrader View Post
                          clcsys,
                          lol, I had a feeling that the posts were crossing, glad you got it working.

                          BTW, you don't have to go to the trouble of having different plots to just color a bar. The original way you did it (except using it with the ToTime() function), will work fine and probably more efficient since you don't have to store 2 DataSeries to accomplish it.

                          VT
                          VT: yes, I figured that out. But since I want to combine it with the Range Indicator and/or another at some point (hopefully), that was a better structure.

                          It's so easy when you know how, but when you don't....

                          Attached is the code if anyone wants it or wants to take it further...
                          Attached Files

                          Comment

                          Latest Posts

                          Collapse

                          Topics Statistics Last Post
                          Started by JoMoon2024, Today, 06:56 AM
                          0 responses
                          6 views
                          0 likes
                          Last Post JoMoon2024  
                          Started by Haiasi, 04-25-2024, 06:53 PM
                          2 responses
                          19 views
                          0 likes
                          Last Post Massinisa  
                          Started by Creamers, Today, 05:32 AM
                          0 responses
                          6 views
                          0 likes
                          Last Post Creamers  
                          Started by Segwin, 05-07-2018, 02:15 PM
                          12 responses
                          1,786 views
                          0 likes
                          Last Post Leafcutter  
                          Started by poplagelu, Today, 05:00 AM
                          0 responses
                          3 views
                          0 likes
                          Last Post poplagelu  
                          Working...
                          X