I would like a CMA whose value will be equal to Current price.
I created a cma whose loop looks for the value that equals the current price.
protected override void OnBarUpdate()
{
// Ensure there is enough data (we must have at least the number of bars required)
if (CurrentBar >= 1)
{
// Get the close price of the CurrentBar (the latest completed bar)
double currentBarClosePrice = Close[0]; // Close of the current bar (the last bar)
// Arrays to store close prices and volumes for bars
double[] closePrices = new double[CurrentBar];
double[] volumes = new double[CurrentBar];
// Fill the arrays with close prices and volumes for each bar up to the CurrentBar
for (int i = 0; i < CurrentBar; i++)
{
closePrices[i] = Bars.GetClose(i); // Get close price for the bar at index i
volumes[i] = Bars.GetVolume(i); // Get volume for the bar at index i
}
// Efficient cumulative sum and weighted sum using LINQ
double clovolSum = closePrices.Zip(volumes, (price, volume) => price * volume).Sum(); // Weighted sum of close prices and volumes
double volumeSum = volumes.Sum(); // Total volume
// Calculate the CMA (Cumulative Moving Average)
double cma = clovolSum / volumeSum;
// Calculate the absolute difference between CMA and the current bar's close price
double difference = Math.Abs(cma - currentBarClosePrice);
// Print the calculated CMA value for the current bar but not breaking at the right place
Print("CMA: " + cma);
// Break the loop if the CMA is closest to the CurrentBar close price but still not breaking at the right place
if (difference < 0.001)
{
Print("Breaking as CMA is equal to CurrentBar Close price.");
}
}
}
With a nested loop we could look for the matching average but this requires a lot of calculation and slows down the process to the point of making NT crash when there are too many bars in the chart.
protected override void OnBarUpdate()
{
if (CurrentBar == 0)
{
// Target average value
double targetAverage = 4.0;
// Loop through the rows (starting from 0 to 4)
for (int i = 0; i <= 4; i++)
{
int sum = 0;
int count = 0;
// Print the series and calculate the sum and count in one loop
string seriesOutput = "Series: ";
for (int j = i; j <= 5; j++) //or for (int barIndex = i; barIndex < CurrentBar; barIndex++)
{
seriesOutput += j + " "; // Add to series output
sum += j; // Add to sum
count++; // Increment count
}
// Calculate the average
double average = (double)sum / count;
// Print the series and average
Print(seriesOutput + $"| Average: {average:F2}");
// Check if the average matches the target
if (average.ApproxCompare(targetAverage) == 0)
{
Print($"Found series with average {targetAverage} at row starting with {i}");
}
}
}
Thank you
