/* Example of subscribing/unsubscribing to bars data events from an Add On as well as making bars requests.
The concept can be carried over to any NinjaScript object you may be working on. */
public class MyAddOnTab : NTTabPage
{
private int daysBack = 5;
private bool barsRequestSubscribed = false;
private BarsRequest barsRequest;
public MyAddOnTab()
{
// create a new bars request. This will determine the insturment and range for the bars to be requested
barsRequest = new BarsRequest(Cbi.Instrument.GetInstrument("AAPL"), DateTime.Now.AddDays(-daysBack), DateTime.Now);
// Parametrize your request.
barsRequest.BarsPeriod = new BarsPeriod { BarsPeriodType = BarsPeriodType.Minute, Value = 1 };
barsRequest.TradingHours = TradingHours.Get("Default 24 x 7");
// Attach event handler for real-time events if you want to process real-time data
barsRequest.Update += OnBarUpdate;
// Request the bars
barsRequest.Request(new Action<BarsRequest, ErrorCode, string>((bars, errorCode, errorMessage) =>
{
if (errorCode != ErrorCode.NoError)
{
// Handle any errors in requesting bars here
NinjaTrader.Code.Output.Process(string.Format("Error on requesting bars: {0}, {1}",
errorCode, errorMessage), PrintTo.OutputTab1);
return;
}
// Output the bars we requested. Note: The last returned bar may be a currently in-progress bar
for (int i = 0; i < bars.Bars.Count; i++)
{
// Output the bars
NinjaTrader.Code.Output.Process(string.Format("Time: {0} Open: {1} High: {2} Low: {3} Close: {4} Volume: {5}",
bars.Bars.GetTime(i),
bars.Bars.GetOpen(i),
bars.Bars.GetHigh(i),
bars.Bars.GetLow(i),
bars.Bars.GetClose(i),
bars.Bars.GetVolume(i)), PrintTo.OutputTab1);
}
// If requesting real-time bars, but there are currently no connections
lock (Connection.Connections)
if (Connection.Connections.FirstOrDefault() == null)
NinjaTrader.Code.Output.Process("Real-Time Bars: Not connected.", PrintTo.OutputTab1);
}));
}
// This method is fired on real-time bar events
private void OnBarUpdate(object sender, BarsUpdateEventArgs e)
{
/* Depending on the BarsPeriod type of your barsRequest you can have situations where more than one bar is
updated by a single tick. Be sure to process the full range of updated bars to ensure you did not miss a bar. */
// Output bar information on each tick
for (int i = e.MinIndex; i <= e.MaxIndex; i++)
{
// Processing every single tick
NinjaTrader.Code.Output.Process(string.Format("Time: {0} Open: {1} High: {2} Low: {3} Close: {4}",
e.BarsSeries.GetTime(i),
e.BarsSeries.GetOpen(i),
e.BarsSeries.GetHigh(i),
e.BarsSeries.GetLow(i),
e.BarsSeries.GetClose(i)), PrintTo.OutputTab1);
}
}
// Called by TabControl when tab is being removed or window is closed
public override void Cleanup()
{
// Make sure to unsubscribe to the bars request subscription
if (barsRequest != null)
{
barsRequest.Update -= OnBarUpdate;
barsRequest.Dispose();
barsRequest = null;
}
}
// Other required NTTabPage members left out for demonstration purposes. Be sure to add them in your own code.
}