I use a dictionary to store price and volume info of a chart. Price is used as Key and a class containing all the volume info as Value. For some reason, when using a for loop with calculated price steps (taking the highest price and subtracting it with each iteration by the step size and then using Math.Round() to make sure it doesn't have unwanted decimals), it appears that the dictionary can't find some price levels / Keys which are actually existent. Then it creates a duplicate Key according to my code. Just as if the price Key, a double, would have invisible decimals. With a foreach loop, though, there is no problem, apart from that in some cases it has to be a for loop. Here is some code
double highestTick = Math.Round(ChartPanel.Y);
double lowestTick = Math.Round(ChartPanel.Y + ChartPanel.H);
for (double i = highestTick; i >= lowestTick; i -= TickSize)
double price = RoundToTickSize(i);
if (!traderLevelYDict.ContainsKey(price))
{
traderLevelYDict.Add(price, new volClass{});
}
else { ...... }
Where RoundToTickSize() is simply:
public double RoundToTickSize(double x)
{
return Math.Round(x / TickSize, MidpointRounding.ToEven) * TickSize; // TickSize is < 1
}
And in the end, I end up with a duplicate Key in the dictionary, as you can see in the picture. Note that there isn't an empty space or so behind the price, and that I don't round the value before printing.
Any idea why it does it, and how to stop it? I appreciate all answers!