Add automatic order id assignment to order book

This commit is contained in:
Tim Kächele 2023-10-28 23:06:39 +02:00
parent 8668ad8927
commit 7191df2a90
2 changed files with 13 additions and 1 deletions

View File

@ -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

View File

@ -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) }