module RTCBX::Orderbook::BookMethods

This class provides methods to apply updates to the state of the orderbook as they are received by the websocket.

Constants

BIGDECIMAL_KEYS

Names of attributes that should be converted to BigDecimal

Public Instance Methods

apply(msg) click to toggle source

Applies a message to an Orderbook object by making relevant changes to @bids, @asks, and @last_sequence.

# File lib/rtcbx/orderbook/book_methods.rb, line 16
def apply(msg)
  return if msg.fetch('sequence') != @last_sequence + 1

  # if msg.fetch('sequence') != @last_sequence + 1
  #  puts "Expected #{@last_sequence + 1}, got #{msg.fetch('sequence')}"
  #  @websocket.stop!
  # end

  @last_sequence = msg.fetch('sequence')
  BIGDECIMAL_KEYS.each do |key|
    msg[key] = BigDecimal(msg.fetch(key)) if msg.fetch(key, false)
  end

  __send__(msg.fetch('type'), msg)
end

Private Instance Methods

activate(_) click to toggle source
# File lib/rtcbx/orderbook/book_methods.rb, line 82
def activate(_)
  # The book doesn't change for this message type.
end
change(msg) click to toggle source
# File lib/rtcbx/orderbook/book_methods.rb, line 63
def change(msg)
  change_order = lambda do |o|
    if o.fetch(:order_id) == msg.fetch('order_id')
      o[:size] = msg.fetch('new_size')
    end
  end

  @asks.map(&change_order) if msg.fetch('side') == 'sell'
  @bids.map(&change_order) if msg.fetch('side') == 'buy'
end
done(msg) click to toggle source
# File lib/rtcbx/orderbook/book_methods.rb, line 56
def done(msg)
  matching_order = ->(o) { o.fetch(:order_id) == msg.fetch('order_id') }

  @asks.reject!(&matching_order) if msg.fetch('side') == 'sell'
  @bids.reject!(&matching_order) if msg.fetch('side') == 'buy'
end
margin_profile_update(_) click to toggle source
# File lib/rtcbx/orderbook/book_methods.rb, line 78
def margin_profile_update(_)
  # The book doesn't change for this message type.
end
match(msg) click to toggle source
# File lib/rtcbx/orderbook/book_methods.rb, line 45
def match(msg)
  decrement_match = lambda do |o|
    if o.fetch(:order_id) == msg.fetch('maker_order_id')
      o[:size] = o.fetch(:size) - msg.fetch('size')
    end
  end

  @asks.map(&decrement_match) if msg.fetch('side') == 'sell'
  @bids.map(&decrement_match) if msg.fetch('side') == 'buy'
end
open(msg) click to toggle source
# File lib/rtcbx/orderbook/book_methods.rb, line 34
def open(msg)
  order = {
    price: msg.fetch('price'),
    size: msg.fetch('remaining_size'),
    order_id: msg.fetch('order_id')
  }

  @bids << order if msg.fetch('side') == 'buy'
  @asks << order if msg.fetch('side') == 'sell'
end
received(_) click to toggle source
# File lib/rtcbx/orderbook/book_methods.rb, line 74
def received(_)
  # The book doesn't change for this message type.
end