Update bar indices in order to support both historical and real-time processing of patterns

This commit is contained in:
moshferatu 2024-07-13 05:30:55 -07:00
parent f0ab540422
commit 99c71f59f2

View File

@ -77,15 +77,17 @@ namespace NinjaTrader.NinjaScript.Indicators
DetectedPatterns[0] = null;
int candleIndex = (State == State.Realtime) ? 1 : 0;
bool isSwingHigh = true, isSwingLow = true;
for (int i = 2; i <= (BarLookback + 1); i++)
for (int i = (candleIndex + 1); i <= (BarLookback + 1); i++)
{
if (Highs[0][1] <= Highs[0][i]) isSwingHigh = false;
if (Lows[0][1] >= Lows[0][i]) isSwingLow = false;
if (Highs[0][candleIndex] <= Highs[0][i]) isSwingHigh = false;
if (Lows[0][candleIndex] >= Lows[0][i]) isSwingLow = false;
}
// Skip inside bars and get the proper penultimate candle.
int penultimateIndex = 2;
int penultimateIndex = candleIndex + 1;
while (Highs[0][penultimateIndex] <= Highs[0][penultimateIndex + 1] && Lows[0][penultimateIndex] >= Lows[0][penultimateIndex + 1])
{
penultimateIndex++;
@ -95,7 +97,7 @@ namespace NinjaTrader.NinjaScript.Indicators
{
detectedPatterns.Add(new Pattern
{
UltimateLevel = Highs[0][1],
UltimateLevel = Highs[0][candleIndex],
PenultimateLevel = Lows[0][penultimateIndex],
StartBarIndex = CurrentBar - penultimateIndex,
IsSwingHigh = true
@ -105,7 +107,7 @@ namespace NinjaTrader.NinjaScript.Indicators
{
detectedPatterns.Add(new Pattern
{
UltimateLevel = Lows[0][1],
UltimateLevel = Lows[0][candleIndex],
PenultimateLevel = Highs[0][penultimateIndex],
StartBarIndex = CurrentBar - penultimateIndex,
IsSwingLow = true
@ -117,16 +119,16 @@ namespace NinjaTrader.NinjaScript.Indicators
var pattern = detectedPatterns[i];
// Check for completed 3CRs.
if ((pattern.IsSwingHigh && Closes[0][1] < pattern.PenultimateLevel && pattern.EndBarIndex == 0) ||
(pattern.IsSwingLow && Closes[0][1] > pattern.PenultimateLevel && pattern.EndBarIndex == 0))
if ((pattern.IsSwingHigh && Closes[0][candleIndex] < pattern.PenultimateLevel && pattern.EndBarIndex == 0) ||
(pattern.IsSwingLow && Closes[0][candleIndex] > pattern.PenultimateLevel && pattern.EndBarIndex == 0))
{
pattern.EndBarIndex = CurrentBar - 1;
pattern.EndBarIndex = CurrentBar - candleIndex;
DetectedPatterns[0] = pattern;
}
// Check for invalidated 3CRs.
if ((pattern.IsSwingHigh && Highs[0][1] > pattern.UltimateLevel && pattern.EndBarIndex == 0) ||
(pattern.IsSwingLow && Lows[0][1] < pattern.UltimateLevel && pattern.EndBarIndex == 0))
if ((pattern.IsSwingHigh && Highs[0][candleIndex] > pattern.UltimateLevel && pattern.EndBarIndex == 0) ||
(pattern.IsSwingLow && Lows[0][candleIndex] < pattern.UltimateLevel && pattern.EndBarIndex == 0))
{
detectedPatterns.RemoveAt(i);
}