Use nested hash instead of tuple for hash keys

This commit is contained in:
Tim Kächele 2024-01-22 08:58:19 +01:00
parent dd441df8ff
commit bd0aa1245a
2 changed files with 16 additions and 13 deletions

View File

@ -6,29 +6,32 @@ module Rex
attr_reader :volumes
def initialize
@volumes = Hash.new { 0 }
@volumes = {
true => Hash.new { 0 },
false => Hash.new { 0 }
}
end
def add_order(order)
volumes[[order.is_buy, order.price]] += order.remaining_quantity
volumes[order.is_buy][order.price] += order.remaining_quantity
[
LimitVolumeChange.new(
side(order),
order.price,
volumes[[order.is_buy, order.price]]
volumes[order.is_buy][order.price]
)
]
end
def remove_order(order)
volumes[[order.is_buy, order.price]] -= order.remaining_quantity
volumes[order.is_buy][order.price] -= order.remaining_quantity
[
LimitVolumeChange.new(
side(order),
order.price,
volumes[[order.is_buy, order.price]]
volumes[order.is_buy][order.price]
)
]
end
@ -37,18 +40,18 @@ module Rex
buy_order = trade.buy_order
sell_order = trade.sell_order
volumes[[buy_order.is_buy, buy_order.price]] -= trade.quantity
volumes[[sell_order.is_buy, sell_order.price]] -= trade.quantity
volumes[buy_order.is_buy][buy_order.price] -= trade.quantity
volumes[sell_order.is_buy][sell_order.price] -= trade.quantity
[
LimitVolumeChange.new(
:buy,
buy_order.price,
volumes[[buy_order.is_buy, buy_order.price]]
volumes[buy_order.is_buy][buy_order.price]
),
LimitVolumeChange.new(
:sell,
sell_order.price,
volumes[[sell_order.is_buy, sell_order.price]]
volumes[sell_order.is_buy][sell_order.price]
)
]
end

View File

@ -8,7 +8,7 @@ RSpec.describe Rex::Book::LimitVolumeTracker do
describe "#add_order" do
it "adds the quantity to the limit volume" do
expect { instance.add_order(sell_order) }.to(
change { instance.volumes[[false, 100]] }.to(250)
change { instance.volumes[false][100] }.to(250)
)
end
@ -26,7 +26,7 @@ RSpec.describe Rex::Book::LimitVolumeTracker do
it "removes the quantity from the limit volume" do
expect { instance.remove_order(sell_order) }.to(
change { instance.volumes[[false, 100]] }.from(250).to(0)
change { instance.volumes[false][100] }.from(250).to(0)
)
end
@ -54,9 +54,9 @@ RSpec.describe Rex::Book::LimitVolumeTracker do
it "adjusts the volumes of the involved limits" do
expect { instance.process_trade(trade) }.to(
change { instance.volumes[[false, 100]] }.from(250).to(50)
change { instance.volumes[false][100] }.from(250).to(50)
.and(
change { instance.volumes[[true, 100]] }.from(200).to(0)
change { instance.volumes[true][100] }.from(200).to(0)
)
)
end