Class: CBX::Feed

Inherits:
Object
  • Object
show all
Defined in:
lib/cbx/feed.rb

Overview

Provides an interface to the Coinbase Exchange WebSocket feed.

Constant Summary collapse

API_URL =
'wss://ws-feed.exchange.coinbase.com'
SUBSCRIPTION_REQUEST =
{ 'type' => 'subscribe', 'product_id' => 'BTC-USD' }

Instance Method Summary collapse

Constructor Details

#initialize(on_message, on_close = nil, on_error = nil) ⇒ Feed

Returns a new instance of Feed.



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/cbx/feed.rb', line 7

def initialize(on_message, on_close = nil, on_error = nil)
  ws = WebSocket::Client::Simple.connect API_URL
  @ws = ws
  ws.on :message do |event|
    msg = JSON.parse event.data
    on_message.call(msg)
  end

  ws.on :open do
    ws.send SUBSCRIPTION_REQUEST.to_json
  end

  ws.on :close do |e|
    on_close && on_close.call(e)
    exit 1
  end

  ws.on :error do |e|
    on_error && on_error.call(e)
  end
end

Instance Method Details

#closeObject



29
30
31
# File 'lib/cbx/feed.rb', line 29

def close
  @ws.close
end