Guide · Building strategies

How to automate a NinjaTrader strategy: complete guide

The full path from a trading idea to an automated strategy running on a simulated account: writing rules a computer can follow, building them with or without code, the settings that quietly change behaviour, and how to test before you rely on it.

How to automate a NinjaTrader strategy: complete guide: cover illustration

Short answer. To automate a NinjaTrader strategy, first write your trading rules as an exact, testable spec: market, chart, session window, entry, stop, target, size and daily limits. Then build it in the Strategy Builder (no code) or write it in C# in the NinjaScript Editor, compile it, backtest it in the Strategy Analyzer, replay it in Playback, run it on a simulated account, and only then decide whether to use it. Most of the work is in the spec and the testing, not the code.

Who this guide is for

You trade futures by hand in NinjaTrader and you have a set of rules you follow, or mean to follow. You want the platform to follow them for you. This guide walks through the full path from "I have an idea" to "a strategy is running on a simulated account and I understand what it does". It covers the two ways to build the strategy, the settings that change its behaviour without you noticing, and a testing order that catches most mistakes before they cost money.

If you only want to know what automation in NinjaTrader is, or how to enable a strategy someone else built, start with automated futures trading in NinjaTrader: how it works and how to import a strategy. This page is about building one.

Compatibility note: menu names and NinjaScript members below refer to NinjaTrader 8 (the current desktop platform). Older NinjaTrader 7 scripts use a different structure and don't compile in NinjaTrader 8 without changes.

Step 1: turn your idea into a written spec

A computer can't "buy the pullback when it looks strong". It can buy when the close is above a 20-period EMA, the previous bar closed below it, and the time is between 9:35 and 11:00 New York time. The single biggest cause of strategies that don't behave the way their owners expect is a vague rule that the code had to interpret.

Before you open any editor, write down answers to every question in this table. If you can't answer one, you aren't ready to automate yet, and that's useful to know.

Strategy spec checklist
QuestionExample of a precise answer
InstrumentMNQ, current front month, rolled the week of expiry
Chart5-minute bars, CME US Index Futures ETH template
Trading windowNew entries only 09:35 to 11:00 New York time
Entry triggerBar closes above the 20 EMA after the previous bar closed below it
FiltersOnly long when the 20 EMA is above the 50 EMA
Order typeMarket order on the open of the next bar
Initial stop40 ticks below entry, placed with the entry
Target or exit80-tick target, or exit at 11:45 if neither is hit
Size1 contract, fixed
Daily limitsMaximum 2 trades and stop for the day after a set dollar loss
Position ruleOne position at a time, no adding, no reversing

The numbers in that table are placeholders to show the level of detail, not a recommendation. Notice that every line can be checked against a chart: you could take a printout of the rules, scroll back through history, and mark each trade by hand. That is the test of a good spec. If two people reading it would mark different trades, rewrite it.

Two parts of the spec deserve extra care. The first is time. NinjaTrader shows bar times in the time zone set in the platform's General options, while your rules are probably written in exchange or New York time. Decide which one the strategy uses and write it down; the session time filter guide shows how to handle both. The second is what happens at the edges: a position still open at the end of the window, a signal on the last bar of the session, a gap through your stop. Write a rule for each.

Step 2: choose how to build it

NinjaTrader gives you two ways to turn a spec into a strategy, and you can move from the first to the second later.

Strategy Builder vs NinjaScript Editor
Strategy BuilderNinjaScript Editor
Coding neededNoneC#
Good forIndicator crosses, price comparisons, time windows, fixed stops and targetsAnything: custom order handling, multiple timeframes, state tracking, complex exits
LimitsLogic has to fit the condition and action grid; some order handling is hidden from youYou own every bug, including the ones in order and error handling
Upgrade path"Unlock Code" turns it into editable NinjaScript (one way)n/a

A sensible approach for most traders: build the first version in the Strategy Builder, even if you plan to code. It forces your spec into explicit conditions, and the generated code is a working template you can study.

Step 3: build it in the Strategy Builder

From the Control Center choose New, then Strategy Builder. The wizard moves through a series of screens. In order:

  1. General. Name the strategy and add a description. Use a name you'll recognise in a list of dozens; include the market and version, for example "MNQ_EMA_Pullback_v1".
  2. Default properties. Set the defaults the strategy will load with: how it calculates (more on that below), entries per direction, exit on session close, bars required to trade and similar. These are the same properties you see when you add a strategy to a chart.
  3. Additional data. Add a second instrument or timeframe if your rules need one, such as a 60-minute trend filter on a 5-minute strategy.
  4. Inputs and variables. Create user inputs for every number in your spec (EMA period, stop ticks, start and end time). Inputs let you change values without rebuilding, and they're what the Strategy Analyzer optimizes.
  5. Conditions and actions. The core. Each set pairs conditions (all must be true, or any, depending on how you group them) with actions such as "Enter long position by a market order" or "Exit long position". Build one set per rule: one for the entry, one for the time exit, one for any daily stop.
  6. Stops and targets. Attach a stop loss and profit target, set in ticks, currency, percent or price. These are placed automatically when an entry fills.
  7. Summary. Review the generated logic. Then compile, which happens when you click Finish.

Inside Conditions and actions, time conditions use the bar's time stamp, so a condition "Time is greater than or equal to 09:35" compares against the bar time in your platform's time zone. Comparing "Close[0]" to "Close[1]" means the current bar's close against the previous bar's close. Index numbers count backwards: [0] is the most recent bar, [1] the one before it. Getting this off by one is the most common Strategy Builder bug, so check every condition against your spec.

When the logic outgrows the grid, click Unlock Code. NinjaTrader opens the generated C# in the NinjaScript Editor. From then on that strategy can't go back into the Builder, so keep a copy of the Builder version first.

Step 4: or write it in NinjaScript

Open New, NinjaScript Editor, right-click the Strategies folder and create a new strategy. Every NinjaScript strategy is a C# class with a few methods NinjaTrader calls for you. You don't need to be a professional developer to read them, but you do need to understand when each runs.

OnStateChange: setup and lifecycle

NinjaTrader moves a strategy through a series of states and calls OnStateChange() each time. The ones you'll use most:

  • SetDefaults. Name, default property values and inputs. Keep it light; this state runs often, including when NinjaTrader just lists the strategy.
  • Configure. Add extra data series and set up order-related behaviour.
  • DataLoaded. Create indicator instances once the data exists.
  • Historical, Transition, Realtime. The strategy processes historical bars first, then transitions to live data. Its "position" during Historical is calculated, not real, which is why start behavior matters (see start behavior explained).
  • Terminated. Clean up anything you created.

OnBarUpdate: where the rules live

OnBarUpdate() runs on each bar update and is where your conditions and orders go. A skeleton that matches the spec above looks like this in outline:

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

    int t = ToTime(Time[0]);
    bool inWindow = t >= 93500 && t < 110000;

    if (Position.MarketPosition == MarketPosition.Flat && inWindow
        && CrossAbove(Close, fastEma, 1) && fastEma[0] > slowEma[0])
        EnterLong(1, "Long");

    if (Position.MarketPosition == MarketPosition.Long && t >= 114500)
        ExitLong("TimeExit", "Long");
}

This is a teaching outline, not a finished strategy. It leaves out the daily trade count, the daily loss stop and handling for rejected orders, all of which a real strategy needs. The stop and target would be set once in State.Configure with SetStopLoss and SetProfitTarget, so NinjaTrader submits them as soon as the entry fills.

Properties that change behaviour quietly

Strategy properties that change behaviour
PropertyWhat it doesWhy it matters
CalculateOn bar close, on each tick, or on price changeOn bar close only acts after a bar finishes. On each tick acts intrabar, which behaves differently live than in a standard backtest.
BarsRequiredToTradeBars the strategy waits for before it can tradeToo low and indicators aren't ready; too high and the strategy seems "stuck".
EntriesPerDirectionHow many entries allowed in one directionLeft at 1, a second long signal is ignored while long. Raised, it can add to a position you didn't plan for.
IsExitOnSessionCloseStrategyFlattens before the session closeUses the trading hours template's close, which may not be the time you think. See exit on session close.
StartBehaviorHow it syncs with the account on enableDecides whether the first live order waits for a flat calculated position.
Trading hours templateWhich session the data series coversChanges which bars exist, so it changes signals. See trading hours templates.

Write the value of each of these into your spec. Two people running "the same strategy" with different Calculate settings or templates are running different strategies.

Step 5: compile and fix errors

Press F5 in the NinjaScript Editor to compile. NinjaTrader compiles every script in the folder together, so an error in any file, even one you didn't write, stops your new strategy from appearing. If your strategy is missing from the list after compiling, the strategy not showing guide covers every cause, including compile errors in other files and OneDrive moving your documents folder.

Step 6: test in four stages

Each stage catches problems the one before can't. Skip none of them.

  1. Visual check on a chart. Add the strategy to a chart with plenty of history and look at where it marks trades. Compare ten or twenty of them with your written spec, by eye. Does each entry match the rule? Is the stop where you expected? This catches logic errors faster than any statistic.
  2. Strategy Analyzer backtest. Run it across a long period with realistic commission and slippage. You're looking for bugs and for whether the behaviour is plausible, not for a number to celebrate. The backtesting guide covers the settings that make this honest.
  3. Playback. Connect to the Playback connection and replay recorded market data at speed. Playback feeds the strategy tick by tick, the way live data does, so it exposes problems a bar-based backtest hides: intrabar entries, stops hit inside a bar, order timing.
  4. Simulated account in real time. Run it on Sim101 or another simulated account for long enough to see a range of sessions: quiet days, fast days, a holiday schedule, a contract roll. Watch the Strategies, Orders and Log tabs. A strategy that runs cleanly in real time on a simulated account for weeks is far better understood than one that only has a backtest.

At every stage, keep a short log: date, version, settings, what you saw, what you changed. When something odd happens three weeks later, that log is how you'll find out whether it's the market or a change you made.

Step 7: add the safety rules before you rely on it

A strategy that trades correctly most of the time still needs rules for the rest of the time. At minimum:

  • A stop on every position, submitted with the entry, not added later.
  • A daily loss limit inside the strategy, plus the account-level limits NinjaTrader and your account provider offer. The daily loss limit settings guide covers both layers.
  • A maximum trade count per day, so a logic bug can't fire twenty entries.
  • A flat-by time, so nothing is left open into a session close you didn't plan for.
  • Size from a rule, not a mood. Use the position size calculator and tick value calculator to see what a stop in ticks means in dollars for your contract.

These rules don't make a strategy profitable. They limit how much a bad day, a bug or a disconnect can cost.

Step 8: decide where it runs

An enabled strategy only works while NinjaTrader is open, connected and the computer is awake. Decide before you start whether that's your own PC with sleep turned off or a Windows VPS. The VPS guide compares the two, and the requirements checklist lists what you need in place first.

Common mistakes when automating a strategy

  • Automating rules you've never traded by hand. If you haven't watched the setup play out, you can't tell whether the code is wrong or the idea is.
  • Optimizing before debugging. Running thousands of parameter combinations on code that has a bug just finds the combination that best exploits the bug.
  • Different settings in test and use. A backtest on one trading hours template and live use on another, or a backtest with Calculate on bar close and live use on each tick.
  • No plan for a manual override. Know how you'll stop it: disable the strategy, then check the Orders and Positions tabs for anything left working.
  • Trading the same instrument by hand on the same account. The strategy tracks its own position and won't know about your manual trade.

Build it yourself or start from a ready-made strategy

Building your own strategy teaches you more about your trading than almost anything else, and the Strategy Builder means you can start without code. It also takes time: a clear spec, a careful build and weeks of testing. If you'd rather study and run finished strategies whose rules are written down for you, every FuturesBotLab bot publishes its market, session, entry style and risk rules on its page, for example Dawn Range (MGC · GC) and Nasdaq Reload (MNQ · NQ). You still test them on a simulated account and decide yourself whether to use them.

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. Code examples are for education only. This guide is educational, not investment advice. Risk disclosure.

FAQ

Common questions

Can I automate a NinjaTrader strategy without coding?

Yes. The Strategy Builder lets you define conditions, actions, stops and targets point-and-click, and it generates the NinjaScript code for you.

What language are NinjaTrader strategies written in?

NinjaScript, which is C# with NinjaTrader's own classes and methods. You write and compile it in the NinjaScript Editor inside the platform.

Can I convert a Strategy Builder strategy to code?

Yes. Unlock Code opens the generated C# in the NinjaScript Editor. After that, the strategy can no longer be edited in the Builder, so keep a copy first.

How long should I test an automated strategy before using it?

Long enough to see a range of sessions, including quiet and fast days and a contract roll. Test it visually, in the Strategy Analyzer, in Playback and on a simulated account first.

Will automating my strategy make it profitable?

No. Automation follows your rules consistently, but it can't make a losing approach work. Futures trading involves substantial risk of loss.

Founding Lifetime offer

Lifetime access at $1,297 for the first 50 buyers

FuturesBotLab is a lineup of 9 NinjaScript strategies for gold and US index futures, each with its risk rules written into the code. Founding Lifetime is one payment for every current and future bot. Licensing uses your NinjaTrader account email. The $1,297 founding price is for the first 50 Lifetime buyers only. Prefer to start small? Weekly is $49, Monthly $97 and Yearly $597.

Futures trading involves substantial risk of loss and is not suitable for every investor. No bot guarantees any result. Risk disclosure.

How checkout works

  1. Choose your membership on the purchase page.
  2. Enter your email.
  3. Complete payment using the secure Stripe Checkout link sent to your email. Your account is set up after payment.

Choose a plan

Compare all plans

Questions first? Email support@futuresbotlab.com.

Founding price · first 50 buyers

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

Every bot, every update, one membership.