class RTCBX::Orderbook

Attributes

asks[R]

Array of asks

bids[R]

Array of bids

last_sequence[R]

Sequence number of most recently received message

snapshot_sequence[R]

Sequence number from the initial level 3 snapshot

update_thread[R]

Reads from the queue and updates the Orderbook.

Public Class Methods

new(options = {}, &block) click to toggle source

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.

Calls superclass method 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

start!() click to toggle source

Used to start the thread that listens to updates on the websocket and applies them to the current orderbook to create a live book.

Calls superclass method RTCBX#start!
# File lib/rtcbx/orderbook.rb, line 50
def start!
  super
  sleep 1
  apply_orderbook_snapshot
  start_update_thread
end
stop!() click to toggle source

Stop the thread that listens to updates on the websocket

Calls superclass method RTCBX#stop!
# File lib/rtcbx/orderbook.rb, line 59
def stop!
  super
  update_thread.kill
end

Private Instance Methods

apply_orderbook_snapshot() click to toggle source

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
order_to_hash(price, size, order_id) click to toggle source

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
start_update_thread() click to toggle source

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