The fulfilling part checks to see if our order has a smaller depth than the
other one. If so, our order is completed at their exchange rate and closed. The
matching finishes up.
It's completed at 'our' exchange rate, ie. the newly processed order's, not the old order's.
partly using their order.
[...]
We need to calculate how much of our order will be chipped off, while
preserving their exchange rate.
Again, what the code is doing is using the new order's rate, not theirs.
I think the description you wrote is how it should be, and how you wanted it to be. But I think the code is backwards. This explains why people are getting the rate they ask for, rather than the best available rate in the order book.
price first so we move up the orderbook, rather than select random matches.
Order by price, and then by date. The first person to offer to sell at a certain price should be the first person to get matched at that price.
for two given orders given the constraints- although that isn't too important.
What's the optimised rate? For the seller, higher is better. For the buyer, lower is better. I think the way most exchanges work is that new orders get matched at the best price possible, and if they don't immediately match then they are left as standing orders and will only be matched at the requested price or not at all.
doesn't produce a perfectly divisible amount so we don't get these random
remainders that are credited to a random account once the order matching is
completed.
I don't think that helps because different parts of the order can be matched at different prices.