USE CODE: SAVE10NOW  your country

Got a Question? Call Us

1 (609) 375-8448‬

Mon-Sat 9am-6pm Eastern

NinjaTrader Strategy Lifecycle Overview

By Sut Zal June 02, 2025

 

Step-by-step breakdown of the NinjaTrader 8 strategy lifecycle and all relevant methods, states, and event handlers. This guide will help you understand exactly what happens when a strategy is loaded, enabled, starts receiving data, places orders (especially unmanaged), and terminates.

NinjaTrader 8 Strategy Lifecycle Guide

1. Strategy Lifecycle Overview

When a strategy is loaded or enabled in NinjaTrader 8, it passes through several State phases via the OnStateChange() method. Each phase serves a distinct purpose.

2. OnStateChange() and Strategy States

✅ State.SetDefaults

  • Called: When strategy is added to a chart or Strategy Analyzer
  • Use: Define default values and metadata
if (State == State.SetDefaults)
{
    Name = "MyStrategy";
    Calculate = MarketCalculate.OnBarClose;
    IsOverlay = false;
    AddDataSeries(Data.BarsPeriodType.Minute, 1);
}

🔧 State.Configure

  • Called: After SetDefaults, before data is loaded
  • Use: Add data series, indicators
if (State == State.Configure)
{
    AddDataSeries(Data.BarsPeriodType.Minute, 5);
}

📊 State.DataLoaded

  • Called: When historical data is ready
  • Use: Assign references to indicators, series, etc.
if (State == State.DataLoaded)
{
    sma = SMA(14);
    myCustomSeries = new Series<double>(this);
}

🟢 State.Realtime

  • Called: Just before real-time starts
  • Use: Reset live-only logic

❌ State.Terminated

  • Called: When disabled or removed
  • Use: Final cleanup or logging

3. OnBarUpdate()

  • Called: On every bar/tick depending on Calculate mode
  • Use: Entry/Exit logic
protected override void OnBarUpdate()
{
    if (CurrentBar < BarsRequiredToTrade)
        return;

    if (BarsInProgress != 0)
        return;

    if (CrossAbove(sma, Close, 1))
        EnterLong();
}

4. Unmanaged Orders and Execution Events

🧾 OnExecutionUpdate()

  • Called: When an order is filled
  • Use: Fill tracking
protected override void OnExecutionUpdate(Execution execution, string executionId, double price, int quantity,
    MarketPosition marketPosition, string orderId, DateTime time)
{
    if (execution.Order != null && execution.Order.Name == "MyEntry")
    {
        // Handle fill logic
    }
}

📤 OnOrderUpdate()

  • Called: When order status changes
  • Use: Manage order references
protected override void OnOrderUpdate(Order order, double limitPrice, double stopPrice, int quantity, int filled,
    double avgFillPrice, OrderState state, DateTime time, ErrorCode error, string nativeError)
{
    if (order.Name == "MyEntry")
        myEntryOrder = order;
}

📈 OnPositionUpdate()

  • Called: When position or average price changes
  • Use: Internal position tracking

💰 OnAccountItemUpdate()

  • Called: When account metrics change (e.g., cash, equity)
  • Use: Real-time monitoring
AccountItemUpdate += OnAccountItemUpdate;

void OnAccountItemUpdate(object sender, AccountItemEventArgs e)
{
    if (e.AccountItem == AccountItem.CashValue)
        Print($"Cash value updated: {e.Value}");
}

5. Bar Loading Flow

  1. OnStateChange(State.SetDefaults)
  2. OnStateChange(State.Configure)
  3. OnStateChange(State.DataLoaded)
  4. Historical bars are fed to OnBarUpdate()
  5. OnStateChange(State.Realtime)
  6. Real-time bars now call OnBarUpdate()
  7. Unmanaged orders trigger: OnOrderUpdate → OnExecutionUpdate → OnPositionUpdate

6. When to Load Indicators

Best practice: State.DataLoaded
Why: All series and historical data are fully available here. Don’t load indicators before this state.

📌 Summary Table of Events

Event/State Purpose Best Use
State.SetDefaults Define default values and metadata Set name, Calculate mode, overlay, etc.
State.Configure Add data series Multi-timeframe setup
State.DataLoaded Indicators and historical data ready Assign references to indicators
State.Realtime Real-time begins Reset flags, counters, state
State.Terminated Strategy ends Logging, cleanup
OnBarUpdate() Strategy logic per bar Entry/exit, indicator conditions
OnOrderUpdate() Track order state Order reference management
OnExecutionUpdate() Order filled Track fill price/qty
OnPositionUpdate() Position size changes Monitor average price and qty
OnAccountItemUpdate() Account-level metrics update Track cash, margin, PnL

Older Post Newer Post


0 comments


Leave a comment

Please note, comments must be approved before they are published

Newsletter

I agree to subscribe to updates from PriceIsKing.com

Full Risk Disclosure

This website is hosted and operated by Vulture Data Solutions Inc. (“PriceIsKing.com”), a software development company which owns and supports all proprietary technology relating to and including the RAM Indicator. This website is intended for educational and informational purposes only and should not be viewed as a solicitation or recommendation of any product, service or trading strategy. No offer or solicitation to buy or sell securities, securities derivative or futures products of any kind, or any type of trading or investment advice, recommendation or strategy, is made, given, or in any manner endorsed by any PriceIsKing.com affiliate and the information made available on this Web site is not an offer or solicitation of any kind. Specific questions related to a brokerage account should be sent to your broker directly. The content and opinions expressed on this website are those of the authors and do not necessarily reflect the official policy or position of any third party vendors or any of its affiliates.

Important Futures Trading Disclaimer

Trading futures and options involves the risk of loss. Please consider carefully whether futures or options are appropriate to your financial situation. Only risk capital should be used when trading futures or options. Investors could lose more than their initial investment.

Past results are not necessarily indicative of future results. The risk of loss in trading can be substantial, carefully consider the inherent risks of such an investment in light of your financial condition.

CFTC Rules 4.41

Hypothetical or Simulated performance results have certain limitations, unlike an actual performance record, simulated results do not represent actual trading. Also, since the trades have not been executed, the results may have under-or-over compensated for the impact, if any, of certain market factors, such as lack of liquidity. Simulated trading programs in general are also subject to the fact that they are designed with the benefit of hindsight. No representation is being made that any account will or is likely to achieve profit or losses similar to those shown.

Separator

Forex Risk Disclosure

High Risk Investment

Trading foreign exchange on margin carries a high level of risk, and may not be suitable for all investors. Before deciding to trade foreign exchange you should carefully consider your investment objectives, level of experience, and risk appetite. The possibility exists that you could sustain a loss of some or all of your investment and therefore you should not invest money that you cannot afford to lose. You should be aware of all the risks associated with foreign exchange trading, and seek advice from an independent financial advisor if you have any doubts.

Market Opinions

Any opinions, news, research, analysis, prices, or other information contained on this website is provided as general market commentary, and does not constitute investment advice. Vulture Data Solutions Inc. / PriceIsKing.com will not accept liability for any loss or damage, including without limitation to, any loss of profit, which may arise directly or indirectly from use of or reliance on such information.

Internet Trading Risks

There are risks associated with utilizing an Internet-based deal execution trading system including, but not limited to, the failure of hardware, software, and Internet connection. Since Vulture Data Solutions Inc. / PriceIsKing.com do not provide any trading platform you should directly work with your broker as we do not control signal power, its reception or routing via Internet, configuration of your equipment or reliability of its connection, we cannot be responsible for communication failures, distortions or delays when trading via the Internet. Vulture Data Solutions Inc. / PriceIsKing.com employ back up systems and contingency plans to minimize the possibility of system failure. We cannot control training videos hosted on third party provides such as YouTube or any other social media platform.

Accuracy of Information

The content on this website is subject to change at any time without notice, and is provided for the sole purpose of assisting traders to make independent investment decisions. Vulture Data Solutions Inc. / PriceIsKing.com have taken reasonable measures to ensure the accuracy of the information on the website, however, does not guarantee its accuracy, and will not accept liability for any loss or damage which may arise directly or indirectly from the content or your inability to access the website, for any delay in or failure of the transmission or the receipt of any instruction or notifications sent through this website.

Distribution

This site is not intended for distribution, or use by, any person in any country where such distribution or use would be contrary to local law or regulation. None of the services or products referred to in this website are available to persons residing in any country where the provision of such services or products would be contrary to local law or regulation. It is the responsibility of visitors to this website to ascertain the terms of and comply with any local law or regulation to which they are subject.

FX Futures Risk

Trading futures and options involves the risk of loss. Please consider carefully whether futures or options are appropriate to your financial situation. Only risk capital should be used when trading futures or options.

Testimonials

Testimonials appearing on this website may not be representative of other clients or customers and is not a guarantee of future performance or success.

Live Trade Room

This presentation is for educational purposes only and the opinions expressed are those of the presenter only. All trades presented should be considered hypothetical and should not be expected to be replicated in a live trading account..

 

THIS BRIEF STATEMENT CANNOT, OF COURSE, DISCLOSE ALL THE RISKS AND OTHER ASPECTS OF THE COMMODITY AND FOREIGN CURRENCY MARKETS.
Separator
Added to cart!
Save 10%: CODE: SAVE10NOW Free shipping when you order over XX You Have Qualified for Free Shipping USE CODE: SAVE10NOW Get your code: SAVE10NOW Free Shipping On Various Physical Products! USE CODE: SAVE10NOW You Have Achieved Free Shipping Free shipping on most physical products! Free Shipping!