Guide · NinjaScript

How to add a session time filter to a NinjaTrader strategy

How to make a NinjaScript strategy trade only inside the hours you choose: what Time[0] really holds, how ToTime works, converting bar times to New York or London time, windows that cross midnight, a flat-by exit, and the time zone and daylight-saving mistakes that shift a window by an hour.

How to add a session time filter to a NinjaTrader strategy: cover illustration

Short answer. To make a NinjaScript strategy trade only during set hours, compare the bar time with your window in OnBarUpdate, for example with ToTime(Time[0]), and skip the entry logic outside it. Convert the bar time to a named time zone such as Eastern Standard Time so daylight saving doesn't shift the window. Add a separate flat-by check too, because a filter on entries doesn't close a position that is already open.

Template or time filter: which one you need

There are two ways to keep a NinjaTrader strategy inside a session, and they do different jobs.

Trading Hours template vs a time filter in code
Trading Hours templateTime filter in the strategy
What it changesWhich data the strategy sees at allWhen the strategy is allowed to act on the data it sees
Moving averages and other lookbacksCalculated only on bars inside the sessionsCalculated on every bar; only entries are restricted
Where you set itTools, then Trading Hours, and the strategy's Trading hours propertyIn the NinjaScript code, often exposed as start and end properties
Often used forStudying or running on one session's data onlyTrading a window while still reading the full session

Most automated strategies use a full-session template such as CME US Index Futures ETH and a time filter in code. The strategy's moving averages and other calculations then see the whole session, overnight included, and the filter decides when entries are allowed and when the strategy must be flat. If a template is what you need, see NinjaTrader trading hours templates. For the session times themselves, see futures session times.

What Time[0] really holds

In a NinjaScript strategy, Time[0] is the time stamp of the current bar, Time[1] the bar before it, and so on. Two facts about it cause most time-filter bugs:

  • Bars are stamped with their closing time. NinjaTrader's help guide gives the example that a minute bar stamped 9:31 holds the data from 9:30:00 through 9:30:59. So the bar stamped 9:30 is the last minute before the open.
  • The time is in NinjaTrader's display time zone. NinjaTrader converts all bar times to the time zone set under Tools, then Options, General, Preferences, Time zone. The same strategy reads 9:30 in New York and 6:30 for someone whose platform is set to Pacific time. In code, that zone is Core.Globals.GeneralOptions.TimeZoneInfo.

Neither is a problem once you know about it. Both are a problem if your filter assumes start-of-bar times or a particular time zone.

ToTime: comparing times as numbers

ToTime() turns a time into a whole number in the form Hmmss: 9:30 AM becomes 93000, 2 PM becomes 140000, and 12 seconds past 2:15 in the afternoon becomes 141512. Comparing numbers is easier than comparing DateTime objects, which is why most NinjaScript time filters use it. ToTime(9, 30, 0) builds the same number from hours, minutes and seconds.

The simplest filter, close to the example in NinjaTrader's help guide, looks like this:

protected override void OnBarUpdate()
{
    if (CurrentBar < BarsRequiredToTrade)
        return;

    // only look for entries from the open to late morning (platform time)
    int now = ToTime(Time[0]);
    if (now > 93000 && now <= 113000)
    {
        // entry logic goes here
    }
}

Note the > on the start. Because of closing-time stamps, the first one-minute bar that is entirely after the 9:30 AM open is stamped 9:31, so now > 93000 excludes the pre-open minute that now >= 93000 would let in. On five-minute bars the first full bar after the open is stamped 9:35, and the same rule applies.

This version works only if the platform's display time zone is Eastern. That's fine for your own strategy on your own PC. It isn't fine for a strategy someone else will run, or for a window tied to another market's clock.

Converting the bar time to New York or London time

To make a filter independent of the platform's time zone, convert the bar time to the market's own time zone before you compare it. .NET's TimeZoneInfo.ConvertTime does the conversion, including daylight saving:

private TimeZoneInfo newYork;
private TimeZoneInfo london;

protected override void OnStateChange()
{
    if (State == State.SetDefaults)
    {
        Name = "TimeFilterExample";
        Calculate = Calculate.OnBarClose;
    }
    else if (State == State.DataLoaded)
    {
        newYork = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time");
        london  = TimeZoneInfo.FindSystemTimeZoneById("GMT Standard Time");
    }
}

// bar time (platform time zone) converted to another time zone
private DateTime BarTimeIn(TimeZoneInfo zone, DateTime barTime)
{
    DateTime t = DateTime.SpecifyKind(barTime, DateTimeKind.Unspecified);
    return TimeZoneInfo.ConvertTime(t, Core.Globals.GeneralOptions.TimeZoneInfo, zone);
}

The Windows time zone IDs look odd but are standard: "Eastern Standard Time" is US Eastern time and switches to daylight time automatically, "GMT Standard Time" is UK time including British Summer Time, and "Tokyo Standard Time" is Japan time. Setting the DateTime kind to Unspecified avoids an error .NET raises when a time marked as local is converted from a zone other than the PC's own.

Now the filter reads in market time whatever the platform is set to:

int ny = ToTime(BarTimeIn(newYork, Time[0]));
bool inNewYorkWindow = ny > 93000 && ny <= 113000;

int ldn = ToTime(BarTimeIn(london, Time[0]));
bool inLondonWindow = ldn > 80000 && ldn <= 100000;

The London window is written in London time, so it stays on the real London open during the weeks when US and UK clocks are out of step. Written in Eastern time it would be an hour off for those weeks.

Windows that cross midnight

An Asia-session window in US time crosses midnight. A test such as now >= 190000 && now < 20000 can never be true, because no number is both above 190000 and below 20000. Use || instead:

int ny = ToTime(BarTimeIn(newYork, Time[0]));
// Asia window in New York time: 7 PM to 2 AM
bool inAsiaWindow = ny > 190000 || ny <= 20000;

Or convert to Tokyo time instead, where the same window doesn't cross midnight and doesn't move when US clocks change, because Japan doesn't use daylight saving.

Making the window adjustable

Hard-coded numbers are fine for a test. For a strategy you'll keep, expose the window as properties so it can be changed from the strategy's settings without editing code:

[NinjaScriptProperty]
[Range(0, 235959)]
[Display(Name = "Start time (New York, Hmmss)", Order = 1, GroupName = "Time filter")]
public int StartTimeNY { get; set; }

[NinjaScriptProperty]
[Range(0, 235959)]
[Display(Name = "End time (New York, Hmmss)", Order = 2, GroupName = "Time filter")]
public int EndTimeNY { get; set; }

Set their defaults in State.SetDefaults, then compare against StartTimeNY and EndTimeNY instead of fixed numbers. Writing the zone into the property name keeps whoever sets it from guessing which clock it uses.

A flat-by time

A time filter on entries doesn't close a position that's still open when the window ends. If the strategy must be flat by a certain time, code that separately and check it before any entry logic:

int ny = ToTime(BarTimeIn(newYork, Time[0]));

if (ny >= FlatByTimeNY)
{
    if (Position.MarketPosition == MarketPosition.Long)
        ExitLong();
    else if (Position.MarketPosition == MarketPosition.Short)
        ExitShort();
    return;   // no new entries after the flat-by time
}

Pick the flat-by time with your bar size in mind. With Calculate.OnBarClose, the check runs only when a bar closes, so on 15-minute bars a position can stay open for up to 15 minutes past a time that falls between bar closes. Running the check on a smaller added data series, or with Calculate.OnPriceChange or Calculate.OnEachTick, makes it react sooner.

Exit on session close: the built-in backstop

NinjaTrader also has a built-in session-end exit. IsExitOnSessionCloseStrategy (shown as Exit on session close in the strategy's settings, on by default) cancels the strategy's orders and closes its positions shortly before the end of the session, and ExitOnSessionCloseSeconds (default 30) sets how many seconds before. The end time comes from the EOD session in the strategy's Trading Hours template, not from a clock time in your code.

  • The seconds setting works in real time only. In a backtest, positions are exited at the close of the last bar of the session.
  • Because it follows the template, a custom template that ends early moves the exit early too.
  • Treat it as a backstop, not as your flat-by rule. Your own flat-by time says exactly when you want out; the session-close exit catches anything left over.

One trade per session and per-session resets

Many session strategies allow one entry per session, or reset a range at the start of each session. Don't reset on a clock time: the first bar of a session isn't always at the time you expect. Use Bars.IsFirstBarOfSession, which is true on the first bar processed in each session of the Trading Hours template:

private int tradesThisSession;

protected override void OnBarUpdate()
{
    if (Bars.IsFirstBarOfSession)
        tradesThisSession = 0;

    // ... after an entry order is submitted: tradesThisSession++;
    if (tradesThisSession >= 1)
        return;
}

When you need the session's actual start or end time, for example to stop entries an hour before an early close, use a SessionIterator. Create it in State.DataLoaded with new SessionIterator(Bars), call GetNextSession(Time[0], true) on the first bar of each session, and read ActualSessionBegin and ActualSessionEnd, which NinjaTrader has already converted to your local time zone.

Daylight-saving and time zone pitfalls

  • Hard-coded Eastern numbers on a non-Eastern platform. The filter is off by the time zone difference for everyone not on Eastern time. Convert the bar time, as above.
  • Another market's session in Eastern numbers. A London window written as 3 AM to 5 AM ET starts an hour early relative to the London open during the gap weeks (October 25 to November 1 this year, and March 14 to March 28, 2027). Write it in London time.
  • Converting with a fixed offset. Adding or subtracting a fixed number of hours breaks twice a year. Use TimeZoneInfo.ConvertTime with a named zone, which applies each zone's daylight-saving rules for the date being converted.
  • Confusing the template zone with the display zone. Bars.TradingHours.TimeZoneInfo is the zone the Trading Hours template is written in (Central for the CME templates). The bar times you read are in the display zone, Core.Globals.GeneralOptions.TimeZoneInfo. Convert from the display zone.
  • Using DateTime.Now. It's the PC's clock, not the bar's time. In a backtest it's today's date for every historical bar, so a filter built on it means nothing there. Use Time[0].
  • Off-by-one at the open. Closing-time stamps mean >= 93000 includes the last pre-open bar. Decide which one you mean and test it.
  • Old Windows time zone data. Conversions use the PC's time zone rules, so keep Windows updated.

Testing a time filter before you rely on it

  1. Print the times. Open the Output window (Control Center, then New, then NinjaScript Output) and print the bar time and the converted time on each bar that passes the filter, for example Print(Time[0] + " NY " + BarTimeIn(newYork, Time[0]));.
  2. Backtest across a clock change. Run the strategy in the Strategy Analyzer over dates that include the late-October and early-November changes, or March. Check that the first and last trades of each day land where you expect on both sides of each change.
  3. Change the display time zone and repeat. On a test installation, set Tools, then Options to a different time zone and run the same test. A correctly converted filter trades at the same market times.
  4. Check early-close days. Around US holidays the session can end before your window does. Make sure the flat-by logic or the session-close exit still gets the strategy flat.
  5. Run it on a simulated account in real time through at least one full session and compare its entries and exits with the printed times.

Time windows in FuturesBotLab bots

Each FuturesBotLab bot has its trading window, its daily exit and its chart-timeframe check written into the code, so it doesn't depend on you building a filter. Its spec sheet lists the session it trades, for example Nasdaq Blitz (MNQ · NQ) in New York and Bullion Break (MGC · GC) in London. If you write your own strategies, the patterns above are the ones to get right first.

See the trading session of each one on the bots page or see pricing.

Free tools: tick value calculator · position size calculator · futures market hours · daily loss limit calculator.

Related guides

Bots mentioned in this guide

Futures trading involves substantial risk of loss and is not suitable for every investor. Past or hypothetical results don't guarantee future results. This guide is educational, not investment advice. Risk disclosure.

FAQ

Common questions

How do I make a NinjaTrader strategy trade only during certain hours?

Compare the bar time with your window in OnBarUpdate, for example with ToTime(Time[0]), and only run your entry logic when the time is inside it. Add a separate flat-by check so open positions are closed when the window ends.

What time zone is Time[0] in NinjaScript?

The display time zone set under Tools, Options, General, Preferences, Time zone. In code it's Core.Globals.GeneralOptions.TimeZoneInfo. Convert from it to a named zone if the filter must follow a market's clock.

Is a NinjaTrader bar time the start or the end of the bar?

The end. NinjaTrader stamps each bar with its closing time, so the one-minute bar stamped 9:31 holds the 9:30 minute.

How do I handle daylight saving in a NinjaScript time filter?

Convert the bar time with TimeZoneInfo.ConvertTime to a named zone such as Eastern Standard Time or GMT Standard Time, and write the window in that zone. Don't add or subtract a fixed number of hours.

How do I write a time filter that crosses midnight?

Use OR instead of AND: the time is inside the window if it's after the start or before the end. Or convert to a time zone where the window doesn't cross midnight.

What does exit on session close do in NinjaTrader?

It cancels the strategy's orders and closes its positions a set number of seconds before the end of the EOD session in the strategy's Trading Hours template, 30 seconds by default, in real time. In a backtest it exits at the close of the session's last bar.

Membership details

Let the bot follow the rules, so you don't have to.

Every bot, every update, one membership.