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

View File

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

View File

@ -15,10 +15,10 @@ RSpec.describe Rex::Book::TradeTracker do
end
end
describe "#fetch_trades" do
describe "#each" do
let(:n) { 3 }
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