Add method to retrieve a user's orders in a limit order book

This commit is contained in:
Tim Kächele 2024-02-03 21:29:27 +01:00
parent 1bdb619f6c
commit 14557d2a34
2 changed files with 48 additions and 1 deletions

View File

@ -8,6 +8,7 @@ module Rex
@sell_side = RBTree.new @sell_side = RBTree.new
@buy_side = RBTree.new @buy_side = RBTree.new
@order_ids = {} # order_id => order @order_ids = {} # order_id => order
@user_order_ids = {} # user_id => Set<OrderId>
@current_order_id = 0 @current_order_id = 0
end end
@ -19,6 +20,8 @@ module Rex
side[order.price].add_order(order) side[order.price].add_order(order)
order_ids[order.id] = order order_ids[order.id] = order
user_order_ids[order.user_id] ||= Set.new
user_order_ids[order.user_id].add(order.id)
end end
def add_and_match_order(order) def add_and_match_order(order)
@ -43,6 +46,10 @@ module Rex
end end
order_ids.delete(order.id) order_ids.delete(order.id)
user_order_ids[order.user_id].delete(order.id)
user_order_ids.delete(order.user_id) if user_order_ids[order.user_id].empty?
order order
end end
@ -72,12 +79,19 @@ module Rex
sell_side.first&.[](0) sell_side.first&.[](0)
end end
def orders_for_user(user_id)
(@user_order_ids[user_id] || []).map do |order_id|
order_ids[order_id]
end
end
private private
attr_reader( attr_reader(
:order_ids, :order_ids,
:buy_side, :buy_side,
:sell_side :sell_side,
:user_order_ids
) )
def next_order_id def next_order_id

View File

@ -101,6 +101,39 @@ RSpec.describe Rex::Book::LimitOrderBook do
end end
end end
describe "#orders_for_user" do
context "when user does not have any orders" do
it "returns an empty list" do
expect(instance.orders_for_user("unknown_id")).to eq([])
end
end
context "when user has orders" do
let(:order) { build(:order, id: nil, is_buy: true, price: 100) }
before do
instance.add_order(order)
end
it "returns a list of the user's orders" do
expect(instance.orders_for_user(order.user_id)).to eq([order])
end
end
context "when the user had orders" do
let(:order) { build(:order, id: nil, is_buy: true, price: 100) }
before do
instance.add_order(order)
instance.cancel_order(order.id)
end
it "returns an empty list" do
expect(instance.orders_for_user(order.user_id)).to eq([])
end
end
end
describe "#cancel_order" do describe "#cancel_order" do
let(:buy_order) { build(:order, is_buy: true, price: 100) } let(:buy_order) { build(:order, is_buy: true, price: 100) }
let(:sell_order) { build(:order, is_buy: false, price: 121) } let(:sell_order) { build(:order, is_buy: false, price: 121) }