diff --git a/lib/rex/order_book.rb b/lib/rex/order_book.rb index ed839a1..0ba3363 100644 --- a/lib/rex/order_book.rb +++ b/lib/rex/order_book.rb @@ -10,10 +10,12 @@ module Rex @buy_side = RBTree.new @order_ids = {} # order_id => order @current_trade_id = 0 + @current_order_id = 0 end def add_order(order) side = side_for_order(order) + order.id = next_order_id side[order.price] ||= Limit.new(order.price) side[order.price].add_order(order) @@ -66,6 +68,10 @@ module Rex attr_reader :order_ids, :buy_side, :sell_side + def next_order_id + @current_order_id += 1 + end + def side_for_order(order) if order.is_buy buy_side diff --git a/spec/order_book_spec.rb b/spec/order_book_spec.rb index 5672c53..a8c4a47 100644 --- a/spec/order_book_spec.rb +++ b/spec/order_book_spec.rb @@ -4,7 +4,8 @@ RSpec.describe Rex::OrderBook do let(:instance) { described_class.new } describe "#add_order" do - let(:order_a) { build(:order, is_buy: true, price: 100) } + let(:order_a) { build(:order, id: nil, is_buy: true, price: 100) } + let(:order_b) { build(:order, id: nil, is_buy: true, price: 101) } it "adds the order to the order book" do instance.add_order(order_a) @@ -12,6 +13,11 @@ RSpec.describe Rex::OrderBook do expect(instance.best_buy_price).to eq(100) end + it "assigns an order id" do + expect { instance.add_order(order_a) }.to change(order_a, :id).from(nil).to(1) + expect { instance.add_order(order_b) }.to change(order_b, :id).from(nil).to(2) + end + context "with multiple orders at the same price" do let(:order_b) { build(:order, is_buy: true, price: 100) }