Don't process bars outside of regular trading hours as the components aren't trading then

This commit is contained in:
moshferatu 2024-03-12 09:35:25 -07:00
parent c96dc4aa8c
commit 0507316830

View File

@ -31,7 +31,12 @@ namespace NinjaTrader.NinjaScript.Indicators
public class IndexTopN : Indicator
{
private const int PrimaryBars = 0;
private const int RegularTradingHoursBars = 1;
private const int ComponentBarsStartIndex = 2;
private TimeSpan RegularTradingHoursOpen;
private TimeSpan RegularTradingHoursClose;
private const string UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3";
// Regular expression to match the Slickcharts table row containing the components' symbols and index weightings.
@ -60,19 +65,30 @@ namespace NinjaTrader.NinjaScript.Indicators
}
else if (State == State.Configure)
{
RetrieveComponentData();
// For determining when RTH begins and ends.
AddDataSeries(Instrument.FullName,
new BarsPeriod { BarsPeriodType = BarsPeriodType.Day, Value = 1 }, "US Equities RTH");
RetrieveComponentData();
foreach (var component in Components)
{
//Replace "." with "_" in component name to avoid issues with NinjaTrader's naming conventions and "BRK.B".
AddDataSeries(component.Replace(".", "_"));
}
}
else if (State == State.DataLoaded)
{
SessionIterator regularTradingHoursSession = new SessionIterator(BarsArray[RegularTradingHoursBars]);
RegularTradingHoursOpen = regularTradingHoursSession
.GetTradingDayBeginLocal(regularTradingHoursSession.ActualTradingDayExchange).TimeOfDay;
RegularTradingHoursClose = regularTradingHoursSession
.GetTradingDayEndLocal(regularTradingHoursSession.ActualTradingDayExchange).TimeOfDay;
}
}
protected override void OnBarUpdate()
{
if (BarsInProgress == PrimaryBars)
if (BarsInProgress == PrimaryBars && IsRegularTradingHours())
{
double indexValue = 0;
foreach (var component in Components)
@ -84,13 +100,18 @@ namespace NinjaTrader.NinjaScript.Indicators
if (indexValue > 0)
Index[0] = indexValue;
}
else
else if (BarsInProgress >= ComponentBarsStartIndex)
{
string component = Components[BarsInProgress - 1];
string component = Components[BarsInProgress - ComponentBarsStartIndex];
ComponentPrices[component] = Closes[BarsInProgress][0];
}
}
private bool IsRegularTradingHours()
{
return Time[0].TimeOfDay > RegularTradingHoursOpen && Time[0].TimeOfDay <= RegularTradingHoursClose;
}
private void RetrieveComponentData()
{
const string url = "https://www.slickcharts.com/sp500";