Thanks in Advance.
Here is my code:
using System;
using System.Windows.Media;
using NinjaTrader.NinjaScript.Indicators;
using NinjaTrader.Cbi;
using NinjaTrader.Gui.Tools;
using NinjaTrader.NinjaScript;
using NinjaTrader.NinjaScript.Strategies;
public class MyRSIDivergenceIndicator : Indicator
{
private RSI rsiIndicator;
protected override void OnStateChange()
{
if (State == State.SetDefaults)
{
Description = "Detects bullish and bearish RSI divergences.";
Name = "MyRSIDivergenceIndicator";
Calculate = Calculate.OnBarClose;
IsOverlay = false;
AddPlot(Brushes.Orange, "RSIDivergencePlot");
}
else if (State == State.DataLoaded)
{
rsiIndicator = RSI(13, 3);
}
}
protected override void OnBarUpdate()
{
if (CurrentBar < 50) return; // Ensure there are enough bars to perform the analysis
// Use Draw.ArrowUp to indicate bullish divergences
if (IsBullishDivergence())
{
Draw.ArrowUp(this, "BullDiv" + CurrentBar, 0, Low[0] - (2 * TickSize), Brushes.Green);
}
// Use Draw.ArrowDown to indicate bearish divergences
if (IsBearishDivergence())
{
Draw.ArrowDown(this, "BearDiv" + CurrentBar, 0, High[0] + (2 * TickSize), Brushes.Red);
}
}
private bool IsBullishDivergence()
{
int lookBackPeriod = 50; // Maximum look-back period
int minimumLookBack = 5; // Minimum look-back period
double lowestLowPrice = double.MaxValue;
double lowestRSI = double.MaxValue;
int lowestLowIndex = -1;
// Search for the lowest low in price and RSI within the last 50 bars
for (int i = minimumLookBack; i <= lookBackPeriod; i++)
{
if (Low[i] < lowestLowPrice)
{
lowestLowPrice = Low[i];
lowestRSI = rsiIndicator[i];
lowestLowIndex = i;
}
}
// Check for bullish divergence within the last 5 to 50 bars
if (CurrentBar - lowestLowIndex <= lookBackPeriod && CurrentBar - lowestLowIndex >= minimumLookBack)
{
if (Low[0] < lowestLowPrice && rsiIndicator[0] > lowestRSI)
{
return true; // Bullish divergence found
}
}
return false;
}
private bool IsBearishDivergence()
{
int lookBackPeriod = 50; // Maximum look-back period
int minimumLookBack = 5; // Minimum look-back period
double highestHighPrice = double.MinValue;
double highestRSI = double.MinValue;
int highestHighIndex = -1;
// Search for the highest high in price and RSI within the last 50 bars
for (int i = minimumLookBack; i <= lookBackPeriod; i++)
{
if (High[i] > highestHighPrice)
{
highestHighPrice = High[i];
highestRSI = rsiIndicator[i];
highestHighIndex = i;
}
}
// Check for bearish divergence within the last 5 to 50 bars
if (CurrentBar - highestHighIndex <= lookBackPeriod && CurrentBar - highestHighIndex >= minimumLookBack)
{
if (High[0] > highestHighPrice && rsiIndicator[0] < highestRSI)
{
return true; // Bearish divergence found
}
}
return false;
}
}

Comment