Commit 671505e4 authored by Rohit Prasad's avatar Rohit Prasad

Implement method to find all buy orders for a sell order

parent 0154d87a
...@@ -2,8 +2,8 @@ import java.util.*; ...@@ -2,8 +2,8 @@ import java.util.*;
public class OrderMatching { public class OrderMatching {
List<SellOrder> sellOrderQueue = new LinkedList<>(); private List<SellOrder> sellOrderQueue = new LinkedList<>();
List<BuyOrder> buyOrderQueue = new LinkedList<>(); private List<BuyOrder> buyOrderQueue = new LinkedList<>();
/* /*
* Checks if the order is valid * Checks if the order is valid
...@@ -12,4 +12,47 @@ public class OrderMatching { ...@@ -12,4 +12,47 @@ public class OrderMatching {
return order.getQty() > 0 && order.getPrice() > 0.0; return order.getQty() > 0 && order.getPrice() > 0.0;
} }
/*
* Checks if trade can happen between buy order and
* sell order
*/
boolean buySellOrderMatch(BuyOrder b, SellOrder s) {
return !b.getCustomer().equals(s.getCustomer()) &&
b.getStock().equals(s.getStock()) &&
b.getPrice() >= s.getPrice() &&
b.getQty() <= s.getQty();
}
ArrayList<BuyOrder> findBuyOrders(SellOrder s) {
ArrayList<BuyOrder> matchedOrders = new ArrayList<>();
// Iterate over buy orders queue
for (BuyOrder b : buyOrderQueue) {
// if current sell orders have already found all buyers,
// exit the loop
if (s.getQty() <= 0) break;
// check if trade is possible
if (buySellOrderMatch(b, s)) {
matchedOrders.add(b);
// modify sell order quantity to prevent
// repeated purchases
s.setQty(s.getQty() - b.getQty());
}
}
// if there is still some stocks to sell
// add it to sell orders queue
if (s.getQty() > 0) sellOrderQueue.add(s);
// remove all buy orders that were matched from
// buy order queue
for (BuyOrder b : matchedOrders) {
buyOrderQueue.remove(b);
}
return matchedOrders;
}
} }
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