I'm attempting to add a conditional test to the onpaint method using the Quantower API. While I'm not asking specific questions about that API, my query relates to the correct use for conditional tests.
What i'm trying to achieve is:
- If current price is above a target price, draw a line;
- if current price is above the line drawn in 1 above, draw another line; and so on.
At the moment, I have the code below (simplified for this post) which is nested if statements. What I was looking for was 1) is there a more efficient way of achieving the same result without nested if statements; and 2) how to make it dynamic (i.e. so its not limited to only 5 if statements and therefore 5 lines - if price increased significantly, 10 lines might need to be drawn)
double PTLevel = 10.5;
double PT1 = this.HighPrice.Value PTLevel;
double PT2 = PT1 PTLevel;
double PT3 = PT2 PTLevel;
double PT4 = PT3 PTLevel;
double PT5 = PT4 PTLevel;
if (bar.Close > this.HighPrice.Value)
{
float PT1 = (float)this.CurrentChart.MainWindow.CoordinatesConverter.GetChartY(PT1);
graphics.DrawLine(Pen.Purple, X1, PT1, X2, PT1);
if (bar.Close > PT1)
{
float PT2 = (float)this.CurrentChart.MainWindow.CoordinatesConverter.GetChartY(PT2);
graphics.DrawLine(Pen.Purple, X1, PT2, X2, PT2);
if (bar.Close > PT2)
{
float PT3 = (float)this.CurrentChart.MainWindow.CoordinatesConverter.GetChartY(PT3);
graphics.DrawLine(Pen.Purple, X1, PT3, X2, PT3);
if (bar.Close > PT3)
{
float PT4 = (float)this.CurrentChart.MainWindow.CoordinatesConverter.GetChartY(PT4);
graphics.DrawLine(Pen.Purple, X1, PT4, X2, PT4);
if (bar.Close > PT4)
{
float PT5 = (float)this.CurrentChart.MainWindow.CoordinatesConverter.GetChartY(PT5);
graphics.DrawLine(Pen.Purple, X1, PT5, X2, PT5);
}
}
}
}
}
CodePudding user response:
That's where loops come in handy. Put your prices in a list (in whichever order you need to check them in) and then loop through them updating the target whenever there's a higher value:
var prices = new [] { PT1, PT2, PT3, PT4, PT5 };
var currentTarget = this.HighPrice.Value;
foreach (var price in prices)
{
if (price > currentTarget)
{
currentTarget = this.CurrentChart
.MainWindow
.CoordinatesConverter
.GetChartY(price);
graphics.DrawLine(Pen.Purple, X1, currentTarget, X2, currentTarget);
}
}
CodePudding user response:
Xerillo's answer is good, but doesn't express the intent of your code. This seems more what you are trying to do.
var pricePoint = HighPrice.Value;
while (bar.Close > pricePoint )
{
pricePoint = 10.5;
var y = CurrentChart.MainWindow.CoordinatesConverter.GetChartY(pricePoint);
graphics.DrawLine(Pen.Purple, X1, y, X2, y);
}
Do any casting if you deem necessary. Often it's not.