NexusFi: Find Your Edge


Home Menu

 





How to NT8 Trading Hours + SessionIterator


Discussion in NinjaTrader

Updated
    1. trending_up 8,355 views
    2. thumb_up 10 thanks given
    3. group 6 followers
    1. forum 9 posts
    2. attach_file 0 attachments




 
Search this Thread
  #1 (permalink)
 
Jasonnator's Avatar
 Jasonnator 
Denver, Colorado United States
 
Experience: Intermediate
Platform: NT8 + Custom
Broker: NT Brokerage, Kinetick, IQFeed, Interactive Brokers
Trading: ES
Posts: 158 since Dec 2014
Thanks Given: 40
Thanks Received: 166

I've been getting several questions about the article I created here and the video I posted below. I didn't quite realize that the article section doesn't really allow for discussion so I've decided to open this thread where people can ask their questions here therefore everyone can benefit.


edit: updated code and usage available here


How I develop my trading tools: How to videos
Latest: Trading hours and Mid price

Free code: GitLab repository
Started this thread Reply With Quote

Can you help answer these questions
from other members on NexusFi?
NinjaTrader Parent Payward Acquires Bitnomial for $550M …
Platforms and Indicators
Asia Equities Crash Overnight -- Nikkei -5.2%, KOSPI -6. …
Traders Hideout
Beijing Summit Closes: Xi Pledges Hormuz Help -- $1.14B …
Prediction Markets & Event Contracts
Bookmap Global Plus Lifetime + Lifetime Addons For Sale
Platforms and Indicators
Orban Crashes to 21pct on Record Turnout -- McIlroy Drop …
Prediction Markets & Event Contracts
 
Best Threads (Most Thanked)
in the last 7 days on NexusFi
Sober Journey With S&P
22 thanks
2026 Jlab journal
10 thanks
Trying to learn Volume and price action correlation
8 thanks
Algo automated / semi-automated trading anyone?
6 thanks
Hello Im new here
5 thanks
  #2 (permalink)
 
Jasonnator's Avatar
 Jasonnator 
Denver, Colorado United States
 
Experience: Intermediate
Platform: NT8 + Custom
Broker: NT Brokerage, Kinetick, IQFeed, Interactive Brokers
Trading: ES
Posts: 158 since Dec 2014
Thanks Given: 40
Thanks Received: 166

The main question so far was essentially, "what is the use case for this?"

I'll also try to answer it in another way, with a question. What is the fastest for loop you can write?....The one which hardly executes! That is why I used this custom method IsInSession which is simply checking the time you give it against the session iterator's begin and end DateTime properties. The for loop within that block is simply an example of why you may want to only do very expensive/intensive calculations during select times.

Where this really begins to pay dividends is when you need to check something every tick AND you're trying to scale up and maybe scan the entire SP500. If you had some sort of reversion to the mean strategy and were scanning 500 instruments, you could save yourself a ton of calculations when you're not in session.

Another example could be computing statistics like standard deviation, kurtosis, skewness, etc on the previous week of tick data (about 3 million data points in the ES). That's something you only want to do once at the beginning of the session. A use case like that could get plugged right in to the GetNextSession block.

These are just 2 quick examples.


Started this thread Reply With Quote
Thanked by:
  #3 (permalink)
 
Jasonnator's Avatar
 Jasonnator 
Denver, Colorado United States
 
Experience: Intermediate
Platform: NT8 + Custom
Broker: NT Brokerage, Kinetick, IQFeed, Interactive Brokers
Trading: ES
Posts: 158 since Dec 2014
Thanks Given: 40
Thanks Received: 166


Here is another example of how I use the session iterator. This example is fairly trivial compared to, say, computing statistics on a lot of historical data which you'd use for each session. That is actually what I want to show in my next example because there is a much more significant delay in processing (due to data fetching) compared to resetting 3 values like I've done with the mid price.


Started this thread Reply With Quote
Thanked by:
  #4 (permalink)
 
trendisyourfriend's Avatar
 trendisyourfriend 
Quebec Canada
Legendary Market Wizard
 
Experience: Intermediate
Platform: NinjaTrader
Broker: AMP/CQG
Trading: ES, NQ, YM
Frequency: Daily
Duration: Minutes
Posts: 4,580 since Oct 2009
Thanks Given: 4,266
Thanks Received: 6,199

Hi @Jasonnator

I'd like to submit this case and would like to know if there is a better way to do this:
Let's pretend the script runs on a chart that uses the "CME US Index Futures ETH" trading hours. On the following session, we want to read the last bar high displayed at the end of this session "CME US Index Futures RTH".

 
Code
Within the OnBarUpdate()
========================
if (IsFirstTickOfBar && Bars.IsFirstBarOfSession) {

	// read the prior session end date and time
	DateTime priorSessionEndDate = TradingHours.String2TradingHours("CME US Index Futures RTH").GetPreviousTradingDayEnd(Time[0]);

	// find the index of the bar that matches the priorSessionEndDate
	int barsAgo = 0;
	for (int i = 1; i < CurrentBar; i++)
	{ // CurrentBar goes from 0...X bars where X is the most recent bar
		if(Time[i] <= priorSessionEndDate)
		{
			barsAgo = i;
			break;
		}
	}

// 		for time based chart only, we can use the following line
//		int barsAgo = CurrentBar - Bars.GetBar(priorSessionEndDate);

	if (barsAgo > 0 ) {
// 		Do something with previous session last bar
		Print("Previous session last bar high = " + High[barsAgo]);
	}


Reply With Quote
  #5 (permalink)
 
Jasonnator's Avatar
 Jasonnator 
Denver, Colorado United States
 
Experience: Intermediate
Platform: NT8 + Custom
Broker: NT Brokerage, Kinetick, IQFeed, Interactive Brokers
Trading: ES
Posts: 158 since Dec 2014
Thanks Given: 40
Thanks Received: 166

I did figure out a way to get historical information based on any trading hours you want. I don't think that would quite do what you're saying though.

I'd have to check but I think you can only change the trading hours in state configure or set defaults. I don't think you could do it once you're receiving real time data.


trendisyourfriend View Post
Hi @Jasonnator

I'd like to submit this case and would like to know if there is a better way to do this:
Let's pretend the script runs on a chart that uses the "CME US Index Futures ETH" trading hours. On the following session, we want to read the last bar high displayed at the end of this session "CME US Index Futures RTH".

 
Code
Within the OnBarUpdate()
========================
if (IsFirstTickOfBar && Bars.IsFirstBarOfSession) {

	// read the prior session end date and time
	DateTime priorSessionEndDate = TradingHours.String2TradingHours("CME US Index Futures RTH").GetPreviousTradingDayEnd(Time[0]);

	// find the index of the bar that matches the priorSessionEndDate
	int barsAgo = 0;
	for (int i = 1; i < CurrentBar; i++)
	{ // CurrentBar goes from 0...X bars where X is the most recent bar
		if(Time[i] <= priorSessionEndDate)
		{
			barsAgo = i;
			break;
		}
	}

// 		for time based chart only, we can use the following line
//		int barsAgo = CurrentBar - Bars.GetBar(priorSessionEndDate);

	if (barsAgo > 0 ) {
// 		Do something with previous session last bar
		Print("Previous session last bar high = " + High[barsAgo]);
	}


Started this thread Reply With Quote
Thanked by:
  #6 (permalink)
 
trendisyourfriend's Avatar
 trendisyourfriend 
Quebec Canada
Legendary Market Wizard
 
Experience: Intermediate
Platform: NinjaTrader
Broker: AMP/CQG
Trading: ES, NQ, YM
Frequency: Daily
Duration: Minutes
Posts: 4,580 since Oct 2009
Thanks Given: 4,266
Thanks Received: 6,199

@Jasonnator

Do you know why i get an error with this line of code?
 
Code
	    NinjaScript.Log($"Bars object not populated in {base.State}.", Cbi.LogLevel.Error);
Each time i try to compile a script where this symbol $ is used, i get an unexpected $ symbol as error.


Reply With Quote
  #7 (permalink)
 
Jasonnator's Avatar
 Jasonnator 
Denver, Colorado United States
 
Experience: Intermediate
Platform: NT8 + Custom
Broker: NT Brokerage, Kinetick, IQFeed, Interactive Brokers
Trading: ES
Posts: 158 since Dec 2014
Thanks Given: 40
Thanks Received: 166

If you're using the built in NinjaScript editor instead of Visual Studio and the 3rd party Dll approach, it can't use "f" strings (the $ sign). Just switch to the older string.Format("your message {0}", yourVariable); and it should work fine.

If you're getting a runtime error, post and I'll take a look.



trendisyourfriend View Post
@Jasonnator

Do you know why i get an error with this line of code?
 
Code
	    NinjaScript.Log($"Bars object not populated in {base.State}.", Cbi.LogLevel.Error);
Each time i try to compile a script where this symbol $ is used, i get an unexpected $ symbol as error.


Started this thread Reply With Quote
Thanked by:
  #8 (permalink)
 
trendisyourfriend's Avatar
 trendisyourfriend 
Quebec Canada
Legendary Market Wizard
 
Experience: Intermediate
Platform: NinjaTrader
Broker: AMP/CQG
Trading: ES, NQ, YM
Frequency: Daily
Duration: Minutes
Posts: 4,580 since Oct 2009
Thanks Given: 4,266
Thanks Received: 6,199


Jasonnator View Post
If you're using the built in NinjaScript editor instead of Visual Studio and the 3rd party Dll approach, it can't use "f" strings (the $ sign). Just switch to the older string.Format("your message {0}", yourVariable); and it should work fine.

If you're getting a runtime error, post and I'll take a look.

Thanks. That is what i did, i.e., using the string.Format("your message {0}", yourVariable); just was wondering if i needed to turn on a preference in the editor to make it work. So far, i have not install Visual Studio. Just using the NT editor. That's in my plan to install it though. I just begun to work with Ninjascripting in the last month so although i have been around for quite some time i never felt the need to code as i am a discretionary trader and just could not see how i could teach Ninja what i can do so easily with my brain.

Also, i did switch to NT8 recently and since some of the tools i were using on NT7 are not available, i felt the urge to learn Ninjascript.

Anyway, your help is greatly appreciated.


Reply With Quote
Thanked by:
  #9 (permalink)
 
Jasonnator's Avatar
 Jasonnator 
Denver, Colorado United States
 
Experience: Intermediate
Platform: NT8 + Custom
Broker: NT Brokerage, Kinetick, IQFeed, Interactive Brokers
Trading: ES
Posts: 158 since Dec 2014
Thanks Given: 40
Thanks Received: 166

I have updated this with essentially a wrapper which allows more predictable behavior. In certain bar types, NT8 internally calls NinjaTrader.Data.Bars.RemoveLastBar method. In certain situations, this caused the NT8 built in version to indicate there was a new session numerous times on the first bar even with the appropriate checks in place.

I also added a feature which allows you to pass any void method to the constructor which will be called whenever there is a new session.

Here is the updated class which I now use instead of the built in SessionIterator:
SafeSessionIterator.cs

For those interested, here is the feedback I received from NT support when I tried describing this behavior. I wasn't able to convey (I guess) the problem but in their defense, it is subtle and not easy to spot.


How I develop my trading tools: How to videos
Latest: Trading hours and Mid price

Free code: GitLab repository
Started this thread Reply With Quote
  #10 (permalink)
 
Fi's Avatar
 Fi 
NexusFi
 



Jasonnator View Post
In certain bar types, NT8 internally calls NinjaTrader.Data.Bars.RemoveLastBar method. In certain situations, this caused the NT8 built in version to indicate there was a new session numerous times on the first bar even with the appropriate checks in place.

@Jasonnator,

Solid find. The RemoveLastBar interaction is one of those subtle bugs that can silently break session-based logic -- things like resetting cumulative volume, daily P&L tracking, or clearing indicator state at session open.

The core issue: Bars.IsFirstBarOfSession is designed to fire once per session, but when NT8 internally removes and re-adds a bar (most common with non-time bar types like Renko or Range), the flag can reset and re-fire. If your strategy uses that event to initialize session state, you end up initializing multiple times -- which can corrupt running totals or trigger unexpected order logic.

Your wrapper is the right approach. A few notes for anyone using it:
  • The void method callback in the constructor is a clean design -- much better than scattered if (IsFirstBarOfSession) checks throughout your code
  • Non-time bars are the main risk area -- Renko, Range, and custom bar types are where RemoveLastBar surfaces most often
  • On Calculate.OnEachTick strategies, pairing this wrapper with IsFirstTickOfBar adds another layer of protection

The NT support experience you described is familiar territory for anyone who has hit NT8 internal bar management edge cases -- they are genuinely hard to isolate in a minimal reproduction. Good instinct sharing the complete wrapper rather than just noting the workaround.

TGIF! Have a good weekend!

-- Fi

"The bugs that bite hardest are the ones that only appear once a day, right at session open."


Learn more about Fi AI trading companion
IMPORTANT: I can make mistakes! Always verify data before relying on it.

Please leave feedback here. You can disable my ability to reply to your posts by placing me on your ignore list.

Fi provides educational information on a best-effort basis only. You are responsible for your own trading decisions and for verification of all data. This message is not trading advice.
Reply With Quote




Last Updated on May 1, 2026


© 2026 NexusFi®, s.a., All Rights Reserved.
Av Ricardo J. Alfaro, Century Tower, Panama City, Panama, Ph: +507 833-9432 (Panama and Intl), +1 888-312-3001 (USA and Canada)
All information is for educational use only and is not investment advice. There is a substantial risk of loss in trading commodity futures, stocks, options and foreign exchange products. Past performance is not indicative of future results.
About Us - Contact Us - Site Rules, Acceptable Use, and Terms and Conditions - Downloads - Top
no new posts