Class: PolygonInterface

Inherits:
Object
  • Object
show all
Defined in:
lib/polygon/socket.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(auth, stream) ⇒ PolygonInterface

Returns a new instance of PolygonInterface.



11
12
13
14
15
16
17
18
# File 'lib/polygon/socket.rb', line 11

def initialize auth, stream
  @auth = auth
  @stream = stream
  @ws = nil
  @subs = Set.new
  @ready = false
  @thread = nil
end

Instance Attribute Details

#threadObject

Returns the value of attribute thread.



9
10
11
# File 'lib/polygon/socket.rb', line 9

def thread
  @thread
end

Instance Method Details

#runObject



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/polygon/socket.rb', line 24

def run
  @thread = Thread.new do
    EM.run {
      @ws = Faye::WebSocket::Client.new("wss://socket.polygon.io/#{@stream}")

      @ws.on :open do |event|
        p [:open]
        @ws.send('{"action":"auth","params":"' + @auth + '"}')
      end

      @ws.on :message do |event|
        p [:message, event.data]

        msgs = JSON.parse event.data
        msgs.each do |msg|
          case msg['ev']
          when 'T'
            on_T(msg)
          when 'status'
            on_connected if msg['status'] == 'connected'
            on_auth if msg['status'] == 'auth_success'

            ms = msg['message'].split(': ')
            on_subscribed(ms.last.strip) if ms.first == 'subscribed to'
            on_unsubscribed(ms.last.strip) if ms.first == 'unsubscribed to'
          end
        end
      end

      @ws.on :close do |event|
        p [:close, event.code, event.reason]
        @ws = nil
      end
   }
  end

  nil until @ready 
end

#sub(tickers) ⇒ Object



63
64
65
66
67
# File 'lib/polygon/socket.rb', line 63

def sub tickers
  tp = tickers.map {|t| "T.#{t}"}.join ','

  @ws.send('{"action":"subscribe","params": "' + tp + '"}')
end

#subsObject



20
21
22
# File 'lib/polygon/socket.rb', line 20

def subs
  @subs
end

#unsub(tickers) ⇒ Object



69
70
71
72
73
# File 'lib/polygon/socket.rb', line 69

def unsub tickers
  tp = tickers.map {|t| "T.#{t}"}.join ','

  @ws.send('{"action":"unsubscribe","params": "' + tp + '"}')
end