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

Session Calculation Programming (Long)

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

    Session Calculation Programming (Long)

    Fellas (developers),

    I've been working on some code that essentially attempts to measure the maximum trading range over the past X sessions. I know there are tools like Range(); in this case I'm using tick charts and I'm only running one data series (i.e. no multiple time frames to track days or other period types).

    I've been trying to use Pivots() as a template for getting PriorDayOHLC but I'm having problem understanding how the data is loaded asynchronously when using different timeframes.

    My code currently looks like this (the session calculation part). I use a custom list<double> This all runs in OnBarUpdate() for an unmanaged strategy.

    There HAS to be a much simpler way of calculating prior X day max ranges for a data period that is different from the input period. I was hoping you guys could help me with that:

    Code:
    // First, determine if this is the first bar of the session (because we don't know what bar we'll be given first).
    if (BarsArray[BarsInProgress].FirstBarOfSession)
    {
    	// Update session information
    	currentSessionData.Add(new CustomSession());
    	currentSessionData[sessionCount].Open = Open[0];
    	currentSessionData[sessionCount].High = High[0];
    	currentSessionData[sessionCount].Low = Low[0];
    	currentSessionData[sessionCount].SessionNum = sessionCount;
    }
    Once I've added the first session, I proceed to essentially work to determine the max range over X number of trading days:

    Code:
    if (currentSessionData.Count > 0)
    {
    	// Update the high of the current session
    	if (High[0] > currentSessionData[sessionCount].High)
    		currentSessionData[sessionCount].High = High[0];
    				
    	// Update the low of the current session
    	if (Low[0] < currentSessionData[sessionCount].Low)
    		currentSessionData[sessionCount].Low = Low[0];
    				
    	// Update current session change
    	currentSessionData[sessionCount].Change = Math.Abs((currentSessionData[sessionCount].Open - Close[0]) / currentSessionData[sessionCount].Open);
    				
    	// Record the full range of the session
    	currentSessionData[sessionCount].MaxChange = Math.Max(Math.Abs((currentSessionData[sessionCount].Open - currentSessionData[sessionCount].High) / currentSessionData[sessionCount].Open), Math.Abs((currentSessionData[sessionCount].Open - currentSessionData[sessionCount].Low) / currentSessionData[sessionCount].Open));
    					
    	// Calculate the max % change over the trailing session period
    	if (currentSessionData.Count > hiLoSessionChangeLookbackPeriod)
    		for (int i = 1; i <= hiLoSessionChangeLookbackPeriod; i ++)
    			if (currentSessionData[sessionCount].MaxChange > currentSessionData[sessionCount - i].MaxChange)
    				trailingSessionMaxRange = currentSessionData[sessionCount].MaxChange;
    }
    I then wrap up the session at the end of OnBarUpdate():

    Code:
    if (BarsArray[BarsInProgress].LastBarOfSession && currentSessionData.Count > 0)
    {
    	// Add the CLOSE to the current session data.
    	currentSessionData[sessionCount].Close = Close[0];
    
    	// Set final % change over the session
    	currentSessionData[sessionCount].Change = (currentSessionData[sessionCount].Open - currentSessionData[sessionCount].Close) / currentSessionData[sessionCount].Open;
    
    	// Increment the session count
    	sessionCount ++;
    }
    All of this works.

    As I mentioned earlier, I'd like to be able to use the Pivots() code for this; my code currently doesn't work on Day type charts or greater due to what's obviously bad code ("FirstBarOfSession" doesn't seem to happen in day/week/month type periods).

    Thoughts?

    #2
    Hello cgeorgan,

    Thanks for your post.

    One way to obtain the range of a session is to use the PriorDayOHLC() indicator.

    You can use the FirstBarOfSession as the trigger and then check the prior bar for the PriorDayOHLC of the previous session. Here is some example coding that may help:

    Code:
    if (Bars.FirstBarOfSession)
    			{	
    				Print ("Prior session Open: "+PriorDayOHLC().PriorOpen[1]);
    				Print ("Prior session High: "+PriorDayOHLC().PriorHigh[1]);
    				Print ("Prior session Low: "+PriorDayOHLC().PriorLow[1]);
    				Print ("Prior session Close: "+PriorDayOHLC().PriorClose[1]);
    			}
    Instead of print statement you could save the values and use as needed.
    Paul H.NinjaTrader Customer Service

    Comment


      #3
      Hello cgeorgan,

      This post is to provide a correction, the better code to use is:

      Code:
      if (Bars.FirstBarOfSession)
      			{	
      				Print ("Prior session Open: "+PriorDayOHLC().PriorOpen[0]);
      				Print ("Prior session High: "+PriorDayOHLC().PriorHigh[0]);
      				Print ("Prior session Low: "+PriorDayOHLC().PriorLow[0]);
      				Print ("Prior session Close: "+PriorDayOHLC().PriorClose[0]);
      			}
      The reason for the change is that previously I advised [1] as I was thinking of CurrentDayOHL, so for PriorDayOHLC using [0] on the first bar of the session will provide the values needed of the prior session, otherwise with [1] it was sending you back 2 sessions.
      Paul H.NinjaTrader Customer Service

      Comment


        #4
        Originally posted by NinjaTrader_Paul View Post
        Hello cgeorgan,

        This post is to provide a correction, the better code to use is:

        Code:
        if (Bars.FirstBarOfSession)
        			{	
        				Print ("Prior session Open: "+PriorDayOHLC().PriorOpen[0]);
        				Print ("Prior session High: "+PriorDayOHLC().PriorHigh[0]);
        				Print ("Prior session Low: "+PriorDayOHLC().PriorLow[0]);
        				Print ("Prior session Close: "+PriorDayOHLC().PriorClose[0]);
        			}
        The reason for the change is that previously I advised [1] as I was thinking of CurrentDayOHL, so for PriorDayOHLC using [0] on the first bar of the session will provide the values needed of the prior session, otherwise with [1] it was sending you back 2 sessions.
        Hi there -

        So I've got this; my only question really revolves around the asynchronous loading that is noted in the @Pivots indicator. In this case I'm using tick data; how can I ensure that PriorDayOHLC is loaded? And how to ensure that I've loaded the correct # of sessions (i.e. let's say I want the last 5 session PriorDayOHLC)?

        Comment


          #5
          Hello cgeorgan,

          Thanks for your reply.

          I'm not sure where you are going with async data loading or making sure the indicator is loaded but what happens when you apply an indicator is it will start processing on the first historical bar (bar 0) and begin executing code going earliest data to realtime data. This gives you the opportunity to collect the historical data of the previous sessions.

          To do so, it would be a matter of creating an array for each of the 4 values (Prior day OHLC) and using a counter that is incremented on each new session. So on FirstBarOfSession perhaps something like an int sessionCounter++;

          Store the values in their array using the sessionCounter variable as the array pointer on each FirstBarOfSession.

          When you get to realtime data and want to use the values of the last 5 sessions use a for loop to go back through the last 5 using the sessionCounter variable.
          Paul H.NinjaTrader Customer Service

          Comment


            #6
            Originally posted by NinjaTrader_Paul View Post
            Hello cgeorgan,

            Thanks for your reply.

            I'm not sure where you are going with async data loading or making sure the indicator is loaded but what happens when you apply an indicator is it will start processing on the first historical bar (bar 0) and begin executing code going earliest data to realtime data. This gives you the opportunity to collect the historical data of the previous sessions.

            To do so, it would be a matter of creating an array for each of the 4 values (Prior day OHLC) and using a counter that is incremented on each new session. So on FirstBarOfSession perhaps something like an int sessionCounter++;

            Store the values in their array using the sessionCounter variable as the array pointer on each FirstBarOfSession.

            When you get to realtime data and want to use the values of the last 5 sessions use a for loop to go back through the last 5 using the sessionCounter variable.
            I'm referring to a "Tip" that's part of the Pivots indicator (this is from the help file:

            When using HLCCalculationMode.DailyBars it can be expected that a value of 0 is returned when the daily bars have not been loaded yet. Due to the asynchronous nature of this indicator calling daily bars you should only access the pivot values when the indicator has loaded all required Bars objects. To ensure you are accessing accurate values you can use .ContainsValue() as a check:
            This is reflected in the Pivots code as follows:

            Code:
            if (!isDailyDataLoaded)
            {
            	if (priorDayHLC == HLCCalculationMode.DailyBars && Bars.BarsType.IsIntraday) 
            	{
            		Enabled = false;
            		System.Threading.ThreadPool.QueueUserWorkItem(new System.Threading.WaitCallback(GetBarsNow));
            		return;
            	}
            
            	existsHistDailyData = false;
            	isDailyDataLoaded	= true;
            }
            
            IBar dailyBar;
            if (existsHistDailyData) 
            {
            	sessionDateDaily = GetLastBarSessionDate(Time[0], Bars, PivotRange.Daily);
            	dailyBar = dailyBars.Get(dailyBars.GetBar(sessionDateDaily));
            
            	if (dailyBar.Time.Date > sessionDateDaily.Date)
            	{
            		for (DateTime i = sessionDateDaily; i >= dailyBars.GetTime(0); i = i.AddDays(-1))
            		{
            			dailyBar = dailyBars.Get(dailyBars.GetBar(i));
            			if (dailyBar.Time.Date == i.Date)
            				break;
            		}
            	}
            }

            Comment

            Latest Posts

            Collapse

            Topics Statistics Last Post
            Started by stafe, Today, 12:34 PM
            1 response
            6 views
            0 likes
            Last Post NinjaTrader_Jim  
            Started by asmmbillah, Today, 11:18 AM
            1 response
            13 views
            0 likes
            Last Post NinjaTrader_ChrisL  
            Started by nickse2003, Today, 09:56 AM
            1 response
            23 views
            0 likes
            Last Post NinjaTrader_ChristopherJ  
            Started by ATMtrader0001, Today, 10:08 AM
            5 responses
            30 views
            0 likes
            Last Post ATMtrader0001  
            Started by WHICKED, Today, 09:47 AM
            1 response
            20 views
            0 likes
            Last Post NinjaTrader_Spencer  
            Working...
            X