Use ring buffer to keep track of previous trades

This commit is contained in:
Tim Kächele 2024-05-25 14:34:25 +02:00
parent a515e88f27
commit 62837116c3
3 changed files with 14 additions and 14 deletions

View File

@ -1,28 +1,28 @@
module Rex module Rex
module Book module Book
# Trade Tracker implemented as a simple ring buffer
class TradeTracker class TradeTracker
include Enumerable
DEFAULT_TRADE_HISTORY_LIMIT = 200 DEFAULT_TRADE_HISTORY_LIMIT = 200
attr_reader :trades attr_reader :trades
def initialize(limit: DEFAULT_TRADE_HISTORY_LIMIT) def initialize(limit: DEFAULT_TRADE_HISTORY_LIMIT)
@limit = limit @limit = limit
@trades = [] @trades = Array.new(limit)
@current_id = -1
end end
def add(trade) def add(trade)
@trades.push(trade) @current_id += 1
cap idx = (@current_id % @limit)
@trades[idx] = trade
end end
def fetch_trades(limit) def each(&block)
@trades.last(limit) (([@current_id - @limit, 0].max)..@current_id ).each do |id|
yield @trades[id % @limit]
end end
private
def cap
@trades = @trades.last(@limit)
end end
end end
end end

View File

@ -50,7 +50,7 @@ module Rex
end end
def fetch_trades(user_id) def fetch_trades(user_id)
@trade_tracker.fetch_trades(50).each do |trade| @trade_tracker.each do |trade|
@outbox.push( @outbox.push(
Messages::TradeFetchEvent.new( Messages::TradeFetchEvent.new(
trade.id, trade.id,

View File

@ -15,10 +15,10 @@ RSpec.describe Rex::Book::TradeTracker do
end end
end end
describe "#fetch_trades" do describe "#each" do
let(:n) { 3 } let(:n) { 3 }
it "returns only the last n trades" do it "returns only the last n trades" do
expect(instance.fetch_trades(1)).to eq([11]) expect(instance.to_a).to eq([10, 11])
end end
end end
end end