Commit 37592709 authored by Rohit Prasad's avatar Rohit Prasad

Add method to find sell orders for a buy order

parent be0f60d7
......@@ -42,11 +42,9 @@ public class OrderMatching {
if (qty >= 0) {
// modify sell order quantity to prevent
// repeated purchases
s.setQty(s.getQty() - b.getQty());
s.setQty(qty);
matchedOrders.add(b);
} else {
s.setQty(0);
// create a temporary BuyOrder with quantity equal to
// the remaining stocks in sell order
BuyOrder _b = new BuyOrder(b);
......@@ -54,9 +52,11 @@ public class OrderMatching {
// add it to buy orders queue
matchedOrders.add(_b);
s.setQty(0);
// modify buy order's quantity to reflect quantity
// remaining after trade
b.setQty(b.getQty() - s.getQty());
b.setQty(b.getQty() - _b.getQty());
}
}
}
......@@ -74,4 +74,63 @@ public class OrderMatching {
return matchedOrders;
}
/*
* Finds all sell orders for current buy order
*/
ArrayList<SellOrder> findSellOrders(BuyOrder b) {
ArrayList<SellOrder> matchedOrders = new ArrayList<>();
// Iterate over sell orders queue
for (SellOrder s : sellOrderQueue) {
// if current buy order has already found all sellers,
// exit the loop
if (b.getQty() <= 0) break;
// check if trade is possible
if (buySellOrderMatch(b, s)) {
int qty = b.getQty() - s.getQty();
if (qty >= 0) {
// modify buy order quantity to prevent
// repeated purchases
b.setQty(qty);
matchedOrders.add(s);
} else {
// create a temporary SellOrder with quantity equal to
// the remaining stocks in buy order
SellOrder _s = new SellOrder(s);
_s.setQty(b.getQty());
// add it to matched orders queue
matchedOrders.add(_s);
b.setQty(0);
// modify sell order's quantity to reflect quantity
// remaining after trade
s.setQty(s.getQty() - _s.getQty());
}
}
}
// if there is still some stocks to buy
// add it to buy orders queue
if (b.getQty() > 0) buyOrderQueue.add(b);
// remove all sell orders that were matched from
// sell order queue
for (SellOrder s : matchedOrders) {
sellOrderQueue.remove(s);
}
return matchedOrders;
}
List<SellOrder> printSellOrderQueue() {
return sellOrderQueue;
}
List<BuyOrder> printBuyOrderQueue() {
return buyOrderQueue;
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment