NinjaScript > Language Reference > Data >

OnMarketData()

Print this Topic Previous pageReturn to chapter overviewNext page

Definition
The OnMarketData() method is called and guaranteed to be in the correct sequence for every change in level one market data for the underlying instrument. This can include but is not limited to the bid, ask, last price and volume.

 

Programming to this method is considered advanced programming and exposed for experienced programmer
This is a real-time data stream and can be CPU intensive if your program code is compute intensive (not optimal)
This method is not called on historical data (backtest)

 

Method Return Value

This method does not return a value.

 

Method Parameters

MarketDataEventArgs e

 

Syntax
You must override the method in your strategy or indicator with the following syntax.

 

protected override void OnMarketData(MarketDataEventArgs e)
{
 
}

 
 

Examples

protected override void OnMarketData(MarketDataEventArgs e)
{
    // Print some data to the Output window
    if (e.MarketDataType == MarketDataType.Last)
          Print("Last = " + e.Price + " " + e.Volume);
 

    else if (e.MarketDataType == MarketDataType.Ask)
         Print("Ask = " + e.Price + " " + e.Volume);
    else if (e.MarketDataType == MarketDataType.Bid)
         Print("Bid = " + e.Price + " " + e.Volume);
}

 
Additional Reference Samples
Additional reference code samples are available the NinjaScript Educational Resources section of our support forum.

 
Tips

1.With multi-time frame and instrument strategies, OnMarketData() will be called for all unique instruments in your strategy. Use the BarsInProgress to filter the OnMarketData() method for a specific instrument. (BarsInProgress will return the first BarsInProgress series that matches the instrument for the event)
2.Do not leave an unused OnMarketData() method declared in your NinjaScript object. This will unnecessarily attach a data stream to your strategy which uses unnecessary CPU cycles.
3.Should you wish to run comparisons against prior values you will need to store and update local variables to track the relevant values.
4.With NinjaTrader being multi-threaded, you should not rely on any particular sequence of events like OnMarketData() always being called before OnBarUpdate() or vice versa.