Here is the code. Any help would be great as I have beat my head on the wall for 2 days.
namespace NinjaTrader.NinjaScript.Indicators
{
public class Lynn50percent : Indicator
{
private double swingHigh = 0;
private double swingLow = 0;
private double retracementLevel = 0;
private double priceDifference = 0;
// Flag to detect if price has crossed the retracement level
private bool priceHa****Retracement = false;
// Period to look back for swing highs and lows
private int lookBackPeriod = 20;
[Range(1, int.MaxValue), NinjaScriptProperty]
public int LookBackPeriod
{
get { return lookBackPeriod; }
set { lookBackPeriod = value; }
}
protected override void OnBarUpdate()
{
// Ensure that enough bars are available for the calculations
if (CurrentBar < lookBackPeriod)
return;
// 1. Calculate swing high and swing low based on the look-back period
int swingHighIndex = HighestBar(High, lookBackPeriod);
int swingLowIndex = LowestBar(Low, lookBackPeriod);
// If the indices are valid, update the swingHigh and swingLow values
if (swingHighIndex >= 0 && swingLowIndex >= 0)
{
swingHigh = High[swingHighIndex];
swingLow = Low[swingLowIndex];
}
// 2. Calculate the 50% retracement level
retracementLevel = swingLow + (swingHigh - swingLow) * 0.5;
// 3. Check if price has crossed the retracement level
if (Close[0] <= retracementLevel && !priceHa****Retracement)
{
priceHa****Retracement = true; // Mark that price has hit the retracement level
}
// 4. If price has hit the retracement level, calculate the price difference
if (priceHa****Retracement)
{
if (Close[0] > retracementLevel)
{
// Calculate price difference from swing high (for long position)
priceDifference = Math.Abs(Close[0] - swingHigh);
}
else
{
// Calculate price difference from swing low (for short position)
priceDifference = Math.Abs(Close[0] - swingLow);
}
}
// 5. Plot the Swing High, Swing Low, and 50% Retracement Level
// Plot the Swing High
Draw.HorizontalLine("SwingHigh", swingHigh, Brushes.Blue);
// Plot the Swing Low
Draw.HorizontalLine("SwingLow", swingLow, Brushes.Blue);
// Plot the 50% Retracement Level
Draw.HorizontalLine("RetracementLevel", retracementLevel, Brushes.Red);
// 6. If price has crossed the retracement level, display the price difference on the chart
if (priceHa****Retracement)
{
string priceDiffText = "Price Diff: " + priceDifference.ToString("0.00");
// Create a unique label ID by appending CurrentBar
string labelId = "PriceDiffLabel_" + CurrentBar;
// Adjust the y-position for visibility of the text
double yPosition = High[0] + (swingHigh - swingLow) * 0.1;
// Draw the text label on the chart with the unique label
Draw.Text(this, labelId, priceDiffText, 0, yPosition, Brushes.Black);
}
}
}
}

Comment