Add add_and_match_order method to orderbook

This commit is contained in:
Tim Kächele 2023-10-28 23:00:09 +02:00
parent 37435355ae
commit 8668ad8927
3 changed files with 32 additions and 3 deletions

View File

@ -2,7 +2,10 @@ require "rbtree"
module Rex module Rex
class OrderBook class OrderBook
def initialize class NoMatcherProvidedError < StandardError; end
def initialize(matcher: Matcher.new)
@matcher = matcher
@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
@ -17,6 +20,11 @@ module Rex
order_ids[order.id] = order order_ids[order.id] = order
end end
def add_and_match_order(order)
add_order(order)
@matcher.match(self)
end
def remove_order(order_id) def remove_order(order_id)
order = order_ids[order_id] order = order_ids[order_id]
return nil if order.nil? return nil if order.nil?

View File

@ -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(: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) } let(:pricier_sell_order) { build(:order, price: 100, is_buy: false, amount: 70, remaining_amount: 70) }
context "when order book has unmatched orders" do context "when order book has unmatched orders" do
before do before do
order_book.add_order(buy_order) order_book.add_order(buy_order)

View File

@ -49,6 +49,28 @@ RSpec.describe Rex::OrderBook do
end end
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 describe "#highest_buy_order" do
context "when there is nothing in the book" do context "when there is nothing in the book" do
it "returns nil " do it "returns nil " do
@ -96,7 +118,7 @@ RSpec.describe Rex::OrderBook do
end end
describe "#next_trade_id" do 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(1)
expect(instance.next_trade_id).to eq(2) expect(instance.next_trade_id).to eq(2)
expect(instance.next_trade_id).to eq(3) expect(instance.next_trade_id).to eq(3)