Class: Deribit::Websocket

Inherits:
Object
  • Object
show all
Defined in:
lib/deribit/websocket.rb

Overview

Websocket API adapter

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(host, key: nil, secret: nil) ⇒ Deribit::Websocket

Create new websocket instance

Parameters:

  • host (String)

    the underlying host to connect to

  • key (String) (defaults to: nil)

    the api key

  • secret (String) (defaults to: nil)

    the api secret



15
16
17
18
19
20
21
# File 'lib/deribit/websocket.rb', line 15

def initialize(host, key: nil, secret: nil)
  @host = host
  @key = key
  @secret = secret
  @callbacks = {}
  @ws = nil
end

Instance Attribute Details

#access_tokenObject (readonly)

Returns the value of attribute access_token.



8
9
10
# File 'lib/deribit/websocket.rb', line 8

def access_token
  @access_token
end

#callbacksObject (readonly)

Returns the value of attribute callbacks.



8
9
10
# File 'lib/deribit/websocket.rb', line 8

def callbacks
  @callbacks
end

#hostObject (readonly)

Returns the value of attribute host.



8
9
10
# File 'lib/deribit/websocket.rb', line 8

def host
  @host
end

#keyObject (readonly)

Returns the value of attribute key.



8
9
10
# File 'lib/deribit/websocket.rb', line 8

def key
  @key
end

#secretObject (readonly)

Returns the value of attribute secret.



8
9
10
# File 'lib/deribit/websocket.rb', line 8

def secret
  @secret
end

Instance Method Details

#authorized?Boolean

Returns:

  • (Boolean)


50
51
52
# File 'lib/deribit/websocket.rb', line 50

def authorized?
  !access_token.nil?
end

#subscribe(topic, params: {}) {|Array| ... } ⇒ Object

Subscribe to a specific topic and optionally filter by symbol

Parameters:

  • topic (String)

    topic to subscribe to e.g. ‘trade’

  • params (Hash) (defaults to: {})

    the arguments for subscription

Yields:

  • (Array)

    data payload



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/deribit/websocket.rb', line 27

def subscribe(topic, params: {}, &callback)
  raise 'block is required' unless block_given?

  # connect on demand
  @ws = connect unless connected?
  raise 'websocket is closed' unless @ws.open?

  # save callback handler
  @callbacks[topic.to_s] = callback

  # authorize if needed
  authorize if authorization_required?(topic)

  # subscription request
  payload = {
    jsonrpc: '2.0',
    method: 'public/subscribe',
    id: rand(9999),
    params: { channels: [topic] }
  }
  @ws.send payload.to_json.to_s
end