diff --git a/lib/rex/order_book.rb b/lib/rex/order_book.rb index 2b38845..ed839a1 100644 --- a/lib/rex/order_book.rb +++ b/lib/rex/order_book.rb @@ -2,7 +2,10 @@ require "rbtree" module Rex class OrderBook - def initialize + class NoMatcherProvidedError < StandardError; end + + def initialize(matcher: Matcher.new) + @matcher = matcher @sell_side = RBTree.new @buy_side = RBTree.new @order_ids = {} # order_id => order @@ -17,6 +20,11 @@ module Rex order_ids[order.id] = order end + def add_and_match_order(order) + add_order(order) + @matcher.match(self) + end + def remove_order(order_id) order = order_ids[order_id] return nil if order.nil? diff --git a/spec/matcher_spec.rb b/spec/matcher_spec.rb index 65a2ca5..c75c8b9 100644 --- a/spec/matcher_spec.rb +++ b/spec/matcher_spec.rb @@ -9,7 +9,6 @@ RSpec.describe Rex::Matcher do let(:cheaper_sell_order) { build(:order, price: 99, is_buy: false, amount: 50, remaining_amount: 50) } let(:pricier_sell_order) { build(:order, price: 100, is_buy: false, amount: 70, remaining_amount: 70) } - context "when order book has unmatched orders" do before do order_book.add_order(buy_order) diff --git a/spec/order_book_spec.rb b/spec/order_book_spec.rb index f7f869e..5672c53 100644 --- a/spec/order_book_spec.rb +++ b/spec/order_book_spec.rb @@ -49,6 +49,28 @@ RSpec.describe Rex::OrderBook do end end + describe "add_and_match_order" do + context "when matcher is given" do + let(:matcher) { instance_double(Rex::Matcher) } + let(:instance) { described_class.new(matcher: matcher) } + let(:order) { build(:order, is_buy: true, price: 100) } + + before do + allow(matcher).to receive(:match).with(instance) + end + + it "adds the order" do + expect(instance).to receive(:add_order).with(order) + instance.add_and_match_order(order) + end + + it "calls the matcher" do + expect(matcher).to receive(:match).with(instance) + instance.add_and_match_order(order) + end + end + end + describe "#highest_buy_order" do context "when there is nothing in the book" do it "returns nil " do @@ -96,7 +118,7 @@ RSpec.describe Rex::OrderBook do end describe "#next_trade_id" do - it 'returns an increasing trade id' do + it "returns an increasing trade id" do expect(instance.next_trade_id).to eq(1) expect(instance.next_trade_id).to eq(2) expect(instance.next_trade_id).to eq(3)