class RTCBX::Orderbook
Attributes
Array of asks
Array of bids
Sequence number of most recently received message
Sequence number from the initial level 3 snapshot
Reads from the queue and updates the Orderbook
.
Public Class Methods
Creates a new live copy of the orderbook.
If start
is set to false, the orderbook will not start automatically.
If a block
is given it is passed each message as it is received.
RTCBX::new
# File lib/rtcbx/orderbook.rb, line 39 def initialize(options = {}, &block) @bids = [] @asks = [] @snapshot_sequence = 0 @last_sequence = 0 super(options, &block) end
Public Instance Methods
Used to start the thread that listens to updates on the websocket and applies them to the current orderbook to create a live book.
RTCBX#start!
# File lib/rtcbx/orderbook.rb, line 50 def start! super sleep 1 apply_orderbook_snapshot start_update_thread end
Stop the thread that listens to updates on the websocket
RTCBX#stop!
# File lib/rtcbx/orderbook.rb, line 59 def stop! super update_thread.kill end
Private Instance Methods
Fetch orderbook snapshot from API and convert order arrays to hashes.
# File lib/rtcbx/orderbook.rb, line 76 def apply_orderbook_snapshot client.orderbook(level: 3) do |resp| @bids = resp['bids'].map { |b| order_to_hash(*b) } @asks = resp['asks'].map { |a| order_to_hash(*a) } @snapshot_sequence = resp['sequence'] @last_sequence = resp['sequence'] end end
Converts an order array from the API into a hash.
# File lib/rtcbx/orderbook.rb, line 68 def order_to_hash(price, size, order_id) { price: BigDecimal(price), size: BigDecimal(size), order_id: order_id } end
Private method to actually start the thread that reads from the queue and updates the Orderbook
state
# File lib/rtcbx/orderbook.rb, line 87 def start_update_thread @update_thread = Thread.new do begin loop do message = queue.pop apply(message) end rescue StandardError => e puts e end end end